LLVM 24.0.0git
ARMLoadStoreOptimizer.cpp
Go to the documentation of this file.
1//===- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file This file contains a pass that performs load / store related peephole
10/// optimizations. This pass should be run after register allocation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARM.h"
15#include "ARMBaseInstrInfo.h"
16#include "ARMBaseRegisterInfo.h"
17#include "ARMISelLowering.h"
19#include "ARMSubtarget.h"
22#include "Utils/ARMBaseInfo.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/Statistic.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/DebugLoc.h"
53#include "llvm/IR/Function.h"
54#include "llvm/IR/Type.h"
56#include "llvm/MC/MCInstrDesc.h"
57#include "llvm/Pass.h"
59#include "llvm/Support/Debug.h"
62#include <cassert>
63#include <cstddef>
64#include <cstdlib>
65#include <iterator>
66#include <limits>
67#include <utility>
68
69using namespace llvm;
70
71#define DEBUG_TYPE "arm-ldst-opt"
72
73STATISTIC(NumLDMGened , "Number of ldm instructions generated");
74STATISTIC(NumSTMGened , "Number of stm instructions generated");
75STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
76STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
77STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
78STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
79STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
80STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm");
81STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm");
82STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's");
83STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's");
84
85#define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
86
87namespace {
88
89/// Post- register allocation pass the combine load / store instructions to
90/// form ldm / stm instructions.
91struct ARMLoadStoreOpt {
92 const MachineFunction *MF;
93 const TargetInstrInfo *TII;
95 const ARMSubtarget *STI;
96 const TargetLowering *TL;
97 ARMFunctionInfo *AFI;
99 const RegisterClassInfo *RCI = nullptr;
101 bool LiveRegsValid;
102 bool isThumb1, isThumb2;
103
104 bool runOnMachineFunction(MachineFunction &Fn,
105 const RegisterClassInfo &RegClassInfo);
106
107private:
108 /// A set of load/store MachineInstrs with same base register sorted by
109 /// offset.
110 struct MemOpQueueEntry {
112 int Offset; ///< Load/Store offset.
113 unsigned Position; ///< Position as counted from end of basic block.
114
115 MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)
116 : MI(&MI), Offset(Offset), Position(Position) {}
117 };
118 using MemOpQueue = SmallVector<MemOpQueueEntry, 8>;
119
120 /// A set of MachineInstrs that fulfill (nearly all) conditions to get
121 /// merged into a LDM/STM.
122 struct MergeCandidate {
123 /// List of instructions ordered by load/store offset.
125
126 /// Index in Instrs of the instruction being latest in the schedule.
127 unsigned LatestMIIdx;
128
129 /// Index in Instrs of the instruction being earliest in the schedule.
130 unsigned EarliestMIIdx;
131
132 /// Index into the basic block where the merged instruction will be
133 /// inserted. (See MemOpQueueEntry.Position)
134 unsigned InsertPos;
135
136 /// Whether the instructions can be merged into a ldm/stm instruction.
137 bool CanMergeToLSMulti;
138
139 /// Whether the instructions can be merged into a ldrd/strd instruction.
140 bool CanMergeToLSDouble;
141 };
144 SmallVector<MachineInstr *, 4> MergeBaseCandidates;
145
147
148 void moveLiveRegsBefore(const MachineBasicBlock &MBB,
150 unsigned findFreeReg(const TargetRegisterClass &RegClass);
151 void UpdateBaseRegUses(MachineBasicBlock &MBB,
153 unsigned Base, unsigned WordOffset,
154 ARMCC::CondCodes Pred, unsigned PredReg);
155 MachineInstr *CreateLoadStoreMulti(MachineBasicBlock &MBB,
156 MachineBasicBlock::iterator InsertBefore,
157 int Offset, unsigned Base, bool BaseKill,
158 unsigned Opcode, ARMCC::CondCodes Pred,
159 unsigned PredReg, const DebugLoc &DL,
160 ArrayRef<std::pair<unsigned, bool>> Regs,
162 MachineInstr *CreateLoadStoreDouble(MachineBasicBlock &MBB,
163 MachineBasicBlock::iterator InsertBefore,
164 int Offset, unsigned Base, bool BaseKill,
165 unsigned Opcode, ARMCC::CondCodes Pred,
166 unsigned PredReg, const DebugLoc &DL,
167 ArrayRef<std::pair<unsigned, bool>> Regs,
168 ArrayRef<MachineInstr *> Instrs) const;
169 void FormCandidates(const MemOpQueue &MemOps);
170 MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
171 bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
173 bool MergeBaseUpdateLoadStore(MachineInstr *MI);
174 bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
175 bool MergeBaseUpdateLSDouble(MachineInstr &MI);
176 bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
177 bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
178 bool CombineMovBx(MachineBasicBlock &MBB);
179};
180
181struct ARMLoadStoreOptLegacy : public MachineFunctionPass {
182 static char ID;
183
184 ARMLoadStoreOptLegacy() : MachineFunctionPass(ID) {}
185
186 bool runOnMachineFunction(MachineFunction &Fn) override;
187
188 MachineFunctionProperties getRequiredProperties() const override {
189 return MachineFunctionProperties().setNoVRegs();
190 }
191
192 StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; }
193
194 void getAnalysisUsage(AnalysisUsage &AU) const override {
198 }
199};
200
201char ARMLoadStoreOptLegacy::ID = 0;
202
203} // end anonymous namespace
204
205INITIALIZE_PASS_BEGIN(ARMLoadStoreOptLegacy, "arm-ldst-opt",
206 ARM_LOAD_STORE_OPT_NAME, false, false)
208INITIALIZE_PASS_END(ARMLoadStoreOptLegacy, "arm-ldst-opt",
210
212 for (const auto &MO : MI.operands()) {
213 if (!MO.isReg())
214 continue;
215 if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
216 // If the instruction has live CPSR def, then it's not safe to fold it
217 // into load / store.
218 return true;
219 }
220
221 return false;
222}
223
225 unsigned Opcode = MI.getOpcode();
226 bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
227 unsigned NumOperands = MI.getDesc().getNumOperands();
228 unsigned OffField = MI.getOperand(NumOperands - 3).getImm();
229
230 if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
231 Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
232 Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
233 Opcode == ARM::LDRi12 || Opcode == ARM::STRi12)
234 return OffField;
235
236 // Thumb1 immediate offsets are scaled by 4
237 if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
238 Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
239 return OffField * 4;
240
241 int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
242 : ARM_AM::getAM5Offset(OffField) * 4;
243 ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
244 : ARM_AM::getAM5Op(OffField);
245
246 if (Op == ARM_AM::sub)
247 return -Offset;
248
249 return Offset;
250}
251
253 return MI.getOperand(1);
254}
255
257 return MI.getOperand(0);
258}
259
261 switch (Opcode) {
262 default: llvm_unreachable("Unhandled opcode!");
263 case ARM::LDRi12:
264 ++NumLDMGened;
265 switch (Mode) {
266 default: llvm_unreachable("Unhandled submode!");
267 case ARM_AM::ia: return ARM::LDMIA;
268 case ARM_AM::da: return ARM::LDMDA;
269 case ARM_AM::db: return ARM::LDMDB;
270 case ARM_AM::ib: return ARM::LDMIB;
271 }
272 case ARM::STRi12:
273 ++NumSTMGened;
274 switch (Mode) {
275 default: llvm_unreachable("Unhandled submode!");
276 case ARM_AM::ia: return ARM::STMIA;
277 case ARM_AM::da: return ARM::STMDA;
278 case ARM_AM::db: return ARM::STMDB;
279 case ARM_AM::ib: return ARM::STMIB;
280 }
281 case ARM::tLDRi:
282 case ARM::tLDRspi:
283 // tLDMIA is writeback-only - unless the base register is in the input
284 // reglist.
285 ++NumLDMGened;
286 switch (Mode) {
287 default: llvm_unreachable("Unhandled submode!");
288 case ARM_AM::ia: return ARM::tLDMIA;
289 }
290 case ARM::tSTRi:
291 case ARM::tSTRspi:
292 // There is no non-writeback tSTMIA either.
293 ++NumSTMGened;
294 switch (Mode) {
295 default: llvm_unreachable("Unhandled submode!");
296 case ARM_AM::ia: return ARM::tSTMIA_UPD;
297 }
298 case ARM::t2LDRi8:
299 case ARM::t2LDRi12:
300 ++NumLDMGened;
301 switch (Mode) {
302 default: llvm_unreachable("Unhandled submode!");
303 case ARM_AM::ia: return ARM::t2LDMIA;
304 case ARM_AM::db: return ARM::t2LDMDB;
305 }
306 case ARM::t2STRi8:
307 case ARM::t2STRi12:
308 ++NumSTMGened;
309 switch (Mode) {
310 default: llvm_unreachable("Unhandled submode!");
311 case ARM_AM::ia: return ARM::t2STMIA;
312 case ARM_AM::db: return ARM::t2STMDB;
313 }
314 case ARM::VLDRS:
315 ++NumVLDMGened;
316 switch (Mode) {
317 default: llvm_unreachable("Unhandled submode!");
318 case ARM_AM::ia: return ARM::VLDMSIA;
319 case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
320 }
321 case ARM::VSTRS:
322 ++NumVSTMGened;
323 switch (Mode) {
324 default: llvm_unreachable("Unhandled submode!");
325 case ARM_AM::ia: return ARM::VSTMSIA;
326 case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
327 }
328 case ARM::VLDRD:
329 ++NumVLDMGened;
330 switch (Mode) {
331 default: llvm_unreachable("Unhandled submode!");
332 case ARM_AM::ia: return ARM::VLDMDIA;
333 case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
334 }
335 case ARM::VSTRD:
336 ++NumVSTMGened;
337 switch (Mode) {
338 default: llvm_unreachable("Unhandled submode!");
339 case ARM_AM::ia: return ARM::VSTMDIA;
340 case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
341 }
342 }
343}
344
346 switch (Opcode) {
347 default: llvm_unreachable("Unhandled opcode!");
348 case ARM::LDMIA_RET:
349 case ARM::LDMIA:
350 case ARM::LDMIA_UPD:
351 case ARM::STMIA:
352 case ARM::STMIA_UPD:
353 case ARM::tLDMIA:
354 case ARM::tLDMIA_UPD:
355 case ARM::tSTMIA_UPD:
356 case ARM::t2LDMIA_RET:
357 case ARM::t2LDMIA:
358 case ARM::t2LDMIA_UPD:
359 case ARM::t2STMIA:
360 case ARM::t2STMIA_UPD:
361 case ARM::VLDMSIA:
362 case ARM::VLDMSIA_UPD:
363 case ARM::VSTMSIA:
364 case ARM::VSTMSIA_UPD:
365 case ARM::VLDMDIA:
366 case ARM::VLDMDIA_UPD:
367 case ARM::VSTMDIA:
368 case ARM::VSTMDIA_UPD:
369 return ARM_AM::ia;
370
371 case ARM::LDMDA:
372 case ARM::LDMDA_UPD:
373 case ARM::STMDA:
374 case ARM::STMDA_UPD:
375 return ARM_AM::da;
376
377 case ARM::LDMDB:
378 case ARM::LDMDB_UPD:
379 case ARM::STMDB:
380 case ARM::STMDB_UPD:
381 case ARM::t2LDMDB:
382 case ARM::t2LDMDB_UPD:
383 case ARM::t2STMDB:
384 case ARM::t2STMDB_UPD:
385 case ARM::VLDMSDB_UPD:
386 case ARM::VSTMSDB_UPD:
387 case ARM::VLDMDDB_UPD:
388 case ARM::VSTMDDB_UPD:
389 return ARM_AM::db;
390
391 case ARM::LDMIB:
392 case ARM::LDMIB_UPD:
393 case ARM::STMIB:
394 case ARM::STMIB_UPD:
395 return ARM_AM::ib;
396 }
397}
398
399static bool isT1i32Load(unsigned Opc) {
400 return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
401}
402
403static bool isT2i32Load(unsigned Opc) {
404 return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
405}
406
407static bool isi32Load(unsigned Opc) {
408 return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
409}
410
411static bool isT1i32Store(unsigned Opc) {
412 return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
413}
414
415static bool isT2i32Store(unsigned Opc) {
416 return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
417}
418
419static bool isi32Store(unsigned Opc) {
420 return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
421}
422
423static bool isLoadSingle(unsigned Opc) {
424 return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
425}
426
427static unsigned getImmScale(unsigned Opc) {
428 switch (Opc) {
429 default: llvm_unreachable("Unhandled opcode!");
430 case ARM::tLDRi:
431 case ARM::tSTRi:
432 case ARM::tLDRspi:
433 case ARM::tSTRspi:
434 return 1;
435 case ARM::tLDRHi:
436 case ARM::tSTRHi:
437 return 2;
438 case ARM::tLDRBi:
439 case ARM::tSTRBi:
440 return 4;
441 }
442}
443
445 switch (MI->getOpcode()) {
446 default: return 0;
447 case ARM::LDRi12:
448 case ARM::STRi12:
449 case ARM::tLDRi:
450 case ARM::tSTRi:
451 case ARM::tLDRspi:
452 case ARM::tSTRspi:
453 case ARM::t2LDRi8:
454 case ARM::t2LDRi12:
455 case ARM::t2STRi8:
456 case ARM::t2STRi12:
457 case ARM::VLDRS:
458 case ARM::VSTRS:
459 return 4;
460 case ARM::VLDRD:
461 case ARM::VSTRD:
462 return 8;
463 case ARM::LDMIA:
464 case ARM::LDMDA:
465 case ARM::LDMDB:
466 case ARM::LDMIB:
467 case ARM::STMIA:
468 case ARM::STMDA:
469 case ARM::STMDB:
470 case ARM::STMIB:
471 case ARM::tLDMIA:
472 case ARM::tLDMIA_UPD:
473 case ARM::tSTMIA_UPD:
474 case ARM::t2LDMIA:
475 case ARM::t2LDMDB:
476 case ARM::t2STMIA:
477 case ARM::t2STMDB:
478 case ARM::VLDMSIA:
479 case ARM::VSTMSIA:
480 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
481 case ARM::VLDMDIA:
482 case ARM::VSTMDIA:
483 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
484 }
485}
486
487/// Update future uses of the base register with the offset introduced
488/// due to writeback. This function only works on Thumb1.
489void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
491 const DebugLoc &DL, unsigned Base,
492 unsigned WordOffset,
494 unsigned PredReg) {
495 assert(isThumb1 && "Can only update base register uses for Thumb1!");
496 // Start updating any instructions with immediate offsets. Insert a SUB before
497 // the first non-updateable instruction (if any).
498 for (; MBBI != MBB.end(); ++MBBI) {
499 bool InsertSub = false;
500 unsigned Opc = MBBI->getOpcode();
501
502 if (MBBI->readsRegister(Base, /*TRI=*/nullptr)) {
503 int Offset;
504 bool IsLoad =
505 Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
506 bool IsStore =
507 Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
508
509 if (IsLoad || IsStore) {
510 // Loads and stores with immediate offsets can be updated, but only if
511 // the new offset isn't negative.
512 // The MachineOperand containing the offset immediate is the last one
513 // before predicates.
514 MachineOperand &MO =
515 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
516 // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
517 Offset = MO.getImm() - WordOffset * getImmScale(Opc);
518
519 // If storing the base register, it needs to be reset first.
520 Register InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
521
522 if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
523 MO.setImm(Offset);
524 else
525 InsertSub = true;
526 } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
527 !definesCPSR(*MBBI)) {
528 // SUBS/ADDS using this register, with a dead def of the CPSR.
529 // Merge it with the update; if the merged offset is too large,
530 // insert a new sub instead.
531 MachineOperand &MO =
532 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
533 Offset = (Opc == ARM::tSUBi8) ?
534 MO.getImm() + WordOffset * 4 :
535 MO.getImm() - WordOffset * 4 ;
536 if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
537 // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
538 // Offset == 0.
539 MO.setImm(Offset);
540 // The base register has now been reset, so exit early.
541 return;
542 } else {
543 InsertSub = true;
544 }
545 } else {
546 // Can't update the instruction.
547 InsertSub = true;
548 }
549 } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {
550 // Since SUBS sets the condition flags, we can't place the base reset
551 // after an instruction that has a live CPSR def.
552 // The base register might also contain an argument for a function call.
553 InsertSub = true;
554 }
555
556 if (InsertSub) {
557 // An instruction above couldn't be updated, so insert a sub.
558 BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
559 .add(t1CondCodeOp(true))
560 .addReg(Base)
561 .addImm(WordOffset * 4)
562 .addImm(Pred)
563 .addReg(PredReg);
564 return;
565 }
566
567 if (MBBI->killsRegister(Base, /*TRI=*/nullptr) ||
568 MBBI->definesRegister(Base, /*TRI=*/nullptr))
569 // Register got killed. Stop updating.
570 return;
571 }
572
573 // End of block was reached.
574 if (!MBB.succ_empty()) {
575 // FIXME: Because of a bug, live registers are sometimes missing from
576 // the successor blocks' live-in sets. This means we can't trust that
577 // information and *always* have to reset at the end of a block.
578 // See PR21029.
579 if (MBBI != MBB.end()) --MBBI;
580 BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
581 .add(t1CondCodeOp(true))
582 .addReg(Base)
583 .addImm(WordOffset * 4)
584 .addImm(Pred)
585 .addReg(PredReg);
586 }
587}
588
590ARMLoadStoreOpt::eraseInstr(MachineBasicBlock::iterator MI) {
591 if (LiveRegsValid && LiveRegPos == MI)
592 LiveRegsValid = false;
593 return MI->eraseFromParent();
594}
595
596/// Return the first register of class \p RegClass that is not in \p Regs.
597unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
598 for (unsigned Reg : RCI->getOrder(&RegClass))
599 if (LiveRegs.available(Reg))
600 return Reg;
601 return 0;
602}
603
604/// Compute live registers just before instruction \p Before (in normal schedule
605/// direction). Computes backwards so multiple queries in the same block must
606/// come in reverse order.
607void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
609 // Initialize if we never queried in this block.
610 if (!LiveRegsValid) {
611 LiveRegs.init(*TRI);
612 LiveRegs.addLiveOuts(MBB);
613 LiveRegPos = MBB.end();
614 LiveRegsValid = true;
615 }
616 // Move backward just before the "Before" position.
617 while (LiveRegPos != Before) {
618 --LiveRegPos;
619 if (!LiveRegPos->isDebugInstr())
620 LiveRegs.stepBackward(*LiveRegPos);
621 }
622}
623
624static bool ContainsReg(ArrayRef<std::pair<unsigned, bool>> Regs,
625 unsigned Reg) {
626 for (const std::pair<unsigned, bool> &R : Regs)
627 if (R.first == Reg)
628 return true;
629 return false;
630}
631
632/// Create and insert a LDM or STM with Base as base register and registers in
633/// Regs as the register operands that would be loaded / stored. It returns
634/// true if the transformation is done.
635MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(
636 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
637 int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
638 ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
639 ArrayRef<std::pair<unsigned, bool>> Regs,
641 unsigned NumRegs = Regs.size();
642 assert(NumRegs > 1);
643
644 // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
645 // Compute liveness information for that register to make the decision.
646 bool SafeToClobberCPSR = !isThumb1 ||
647 (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
649
650 bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
651
652 // Exception: If the base register is in the input reglist, Thumb1 LDM is
653 // non-writeback.
654 // It's also not possible to merge an STR of the base register in Thumb1.
655 if (isThumb1 && ContainsReg(Regs, Base)) {
656 assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
657 if (Opcode == ARM::tLDRi)
658 Writeback = false;
659 else if (Opcode == ARM::tSTRi)
660 return nullptr;
661 }
662
664 // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
665 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
666 bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
667
668 if (Offset == 4 && haveIBAndDA) {
670 } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
672 } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
673 // VLDM/VSTM do not support DB mode without also updating the base reg.
675 } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
676 // Check if this is a supported opcode before inserting instructions to
677 // calculate a new base register.
678 if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
679
680 // If starting offset isn't zero, insert a MI to materialize a new base.
681 // But only do so if it is cost effective, i.e. merging more than two
682 // loads / stores.
683 if (NumRegs <= 2)
684 return nullptr;
685
686 // On Thumb1, it's not worth materializing a new base register without
687 // clobbering the CPSR (i.e. not using ADDS/SUBS).
688 if (!SafeToClobberCPSR)
689 return nullptr;
690
691 unsigned NewBase;
692 if (isi32Load(Opcode)) {
693 // If it is a load, then just use one of the destination registers
694 // as the new base. Will no longer be writeback in Thumb1.
695 NewBase = Regs[NumRegs-1].first;
696 Writeback = false;
697 } else {
698 // Find a free register that we can use as scratch register.
699 moveLiveRegsBefore(MBB, InsertBefore);
700 // The merged instruction does not exist yet but will use several Regs if
701 // it is a Store.
702 if (!isLoadSingle(Opcode))
703 for (const std::pair<unsigned, bool> &R : Regs)
704 LiveRegs.addReg(R.first);
705
706 NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
707 if (NewBase == 0)
708 return nullptr;
709 }
710
711 int BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2ADDspImm
712 : ARM::t2ADDri)
713 : (isThumb1 && Base == ARM::SP)
714 ? ARM::tADDrSPi
715 : (isThumb1 && Offset < 8)
716 ? ARM::tADDi3
717 : isThumb1 ? ARM::tADDi8 : ARM::ADDri;
718
719 if (Offset < 0) {
720 // FIXME: There are no Thumb1 load/store instructions with negative
721 // offsets. So the Base != ARM::SP might be unnecessary.
722 Offset = -Offset;
723 BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2SUBspImm
724 : ARM::t2SUBri)
725 : (isThumb1 && Offset < 8 && Base != ARM::SP)
726 ? ARM::tSUBi3
727 : isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
728 }
729
730 if (!TL->isLegalAddImmediate(Offset))
731 // FIXME: Try add with register operand?
732 return nullptr; // Probably not worth it then.
733
734 // We can only append a kill flag to the add/sub input if the value is not
735 // used in the register list of the stm as well.
736 bool KillOldBase = BaseKill &&
737 (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
738
739 if (isThumb1) {
740 // Thumb1: depending on immediate size, use either
741 // ADDS NewBase, Base, #imm3
742 // or
743 // MOV NewBase, Base
744 // ADDS NewBase, #imm8.
745 if (Base != NewBase &&
746 (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
747 // Need to insert a MOV to the new base first.
748 if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
749 !STI->hasV6Ops()) {
750 // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
751 if (Pred != ARMCC::AL)
752 return nullptr;
753 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
754 .addReg(Base, getKillRegState(KillOldBase));
755 } else
756 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
757 .addReg(Base, getKillRegState(KillOldBase))
758 .add(predOps(Pred, PredReg));
759
760 // The following ADDS/SUBS becomes an update.
761 Base = NewBase;
762 KillOldBase = true;
763 }
764 if (BaseOpc == ARM::tADDrSPi) {
765 assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
766 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
767 .addReg(Base, getKillRegState(KillOldBase))
768 .addImm(Offset / 4)
769 .add(predOps(Pred, PredReg));
770 } else
771 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
772 .add(t1CondCodeOp(true))
773 .addReg(Base, getKillRegState(KillOldBase))
774 .addImm(Offset)
775 .add(predOps(Pred, PredReg));
776 } else {
777 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
778 .addReg(Base, getKillRegState(KillOldBase))
779 .addImm(Offset)
780 .add(predOps(Pred, PredReg))
781 .add(condCodeOp());
782 }
783 Base = NewBase;
784 BaseKill = true; // New base is always killed straight away.
785 }
786
787 bool isDef = isLoadSingle(Opcode);
788
789 // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
790 // base register writeback.
791 Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
792 if (!Opcode)
793 return nullptr;
794
795 // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
796 // - There is no writeback (LDM of base register),
797 // - the base register is killed by the merged instruction,
798 // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
799 // to reset the base register.
800 // Otherwise, don't merge.
801 // It's safe to return here since the code to materialize a new base register
802 // above is also conditional on SafeToClobberCPSR.
803 if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
804 return nullptr;
805
806 MachineInstrBuilder MIB;
807
808 if (Writeback) {
809 assert(isThumb1 && "expected Writeback only inThumb1");
810 if (Opcode == ARM::tLDMIA) {
811 assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
812 // Update tLDMIA with writeback if necessary.
813 Opcode = ARM::tLDMIA_UPD;
814 }
815
816 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
817
818 // Thumb1: we might need to set base writeback when building the MI.
819 MIB.addReg(Base, getDefRegState(true))
820 .addReg(Base, getKillRegState(BaseKill));
821
822 // The base isn't dead after a merged instruction with writeback.
823 // Insert a sub instruction after the newly formed instruction to reset.
824 if (!BaseKill)
825 UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
826 } else {
827 // No writeback, simply build the MachineInstr.
828 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
829 MIB.addReg(Base, getKillRegState(BaseKill));
830 }
831
832 MIB.addImm(Pred).addReg(PredReg);
833
834 for (const std::pair<unsigned, bool> &R : Regs)
835 MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
836
837 MIB.cloneMergedMemRefs(Instrs);
838
839 return MIB.getInstr();
840}
841
842MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(
843 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
844 int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
845 ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
846 ArrayRef<std::pair<unsigned, bool>> Regs,
847 ArrayRef<MachineInstr*> Instrs) const {
848 bool IsLoad = isi32Load(Opcode);
849 assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
850 unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
851
852 assert(Regs.size() == 2);
853 MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
854 TII->get(LoadStoreOpcode));
855 if (IsLoad) {
856 MIB.addReg(Regs[0].first, RegState::Define)
857 .addReg(Regs[1].first, RegState::Define);
858 } else {
859 MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
860 .addReg(Regs[1].first, getKillRegState(Regs[1].second));
861 }
862 MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
863 MIB.cloneMergedMemRefs(Instrs);
864 return MIB.getInstr();
865}
866
867/// Call MergeOps and update MemOps and merges accordingly on success.
868MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
869 const MachineInstr *First = Cand.Instrs.front();
870 unsigned Opcode = First->getOpcode();
871 bool IsLoad = isLoadSingle(Opcode);
873 SmallVector<unsigned, 4> ImpDefs;
874 DenseSet<unsigned> KilledRegs;
875 DenseSet<unsigned> UsedRegs;
876 // Determine list of registers and list of implicit super-register defs.
877 for (const MachineInstr *MI : Cand.Instrs) {
878 const MachineOperand &MO = getLoadStoreRegOp(*MI);
879 Register Reg = MO.getReg();
880 bool IsKill = MO.isKill();
881 if (IsKill)
882 KilledRegs.insert(Reg);
883 Regs.push_back(std::make_pair(Reg, IsKill));
884 UsedRegs.insert(Reg);
885
886 if (IsLoad) {
887 // Collect any implicit defs of super-registers, after merging we can't
888 // be sure anymore that we properly preserved these live ranges and must
889 // removed these implicit operands.
890 for (const MachineOperand &MO : MI->implicit_operands()) {
891 if (!MO.isReg() || !MO.isDef() || MO.isDead())
892 continue;
893 assert(MO.isImplicit());
894 Register DefReg = MO.getReg();
895
896 if (is_contained(ImpDefs, DefReg))
897 continue;
898 // We can ignore cases where the super-reg is read and written.
899 if (MI->readsRegister(DefReg, /*TRI=*/nullptr))
900 continue;
901 ImpDefs.push_back(DefReg);
902 }
903 }
904 }
905
906 // Attempt the merge.
908
909 MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
910 iterator InsertBefore = std::next(iterator(LatestMI));
911 MachineBasicBlock &MBB = *LatestMI->getParent();
912 unsigned Offset = getMemoryOpOffset(*First);
914 bool BaseKill = LatestMI->killsRegister(Base, /*TRI=*/nullptr);
915 Register PredReg;
917 DebugLoc DL = First->getDebugLoc();
918 MachineInstr *Merged = nullptr;
919 if (Cand.CanMergeToLSDouble)
920 Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
921 Opcode, Pred, PredReg, DL, Regs,
922 Cand.Instrs);
923 if (!Merged && Cand.CanMergeToLSMulti)
924 Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
925 Opcode, Pred, PredReg, DL, Regs, Cand.Instrs);
926 if (!Merged)
927 return nullptr;
928
929 // Determine earliest instruction that will get removed. We then keep an
930 // iterator just above it so the following erases don't invalidated it.
931 iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
932 bool EarliestAtBegin = false;
933 if (EarliestI == MBB.begin()) {
934 EarliestAtBegin = true;
935 } else {
936 EarliestI = std::prev(EarliestI);
937 }
938
939 // Remove instructions which have been merged.
940 for (MachineInstr *MI : Cand.Instrs)
941 eraseInstr(MI);
942
943 // Determine range between the earliest removed instruction and the new one.
944 if (EarliestAtBegin)
945 EarliestI = MBB.begin();
946 else
947 EarliestI = std::next(EarliestI);
948 auto FixupRange = make_range(EarliestI, iterator(Merged));
949
950 if (isLoadSingle(Opcode)) {
951 // If the previous loads defined a super-reg, then we have to mark earlier
952 // operands undef; Replicate the super-reg def on the merged instruction.
953 for (MachineInstr &MI : FixupRange) {
954 for (unsigned &ImpDefReg : ImpDefs) {
955 for (MachineOperand &MO : MI.implicit_operands()) {
956 if (!MO.isReg() || MO.getReg() != ImpDefReg)
957 continue;
958 if (MO.readsReg())
959 MO.setIsUndef();
960 else if (MO.isDef())
961 ImpDefReg = 0;
962 }
963 }
964 }
965
966 MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
967 for (unsigned ImpDef : ImpDefs)
968 MIB.addReg(ImpDef, RegState::ImplicitDefine);
969 } else {
970 // Remove kill flags: We are possibly storing the values later now.
971 assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
972 for (MachineInstr &MI : FixupRange) {
973 for (MachineOperand &MO : MI.uses()) {
974 if (!MO.isReg() || !MO.isKill())
975 continue;
976 if (UsedRegs.count(MO.getReg()))
977 MO.setIsKill(false);
978 }
979 }
980 assert(ImpDefs.empty());
981 }
982
983 return Merged;
984}
985
987 unsigned Value = abs(Offset);
988 // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
989 // multiplied by 4.
990 return (Value % 4) == 0 && Value < 1024;
991}
992
993/// Return true for loads/stores that can be combined to a double/multi
994/// operation without increasing the requirements for alignment.
996 const MachineInstr &MI) {
997 // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
998 // difference.
999 unsigned Opcode = MI.getOpcode();
1000 if (!isi32Load(Opcode) && !isi32Store(Opcode))
1001 return true;
1002
1003 // Stack pointer alignment is out of the programmers control so we can trust
1004 // SP-relative loads/stores.
1005 if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
1007 return true;
1008 return false;
1009}
1010
1011/// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
1012void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
1013 const MachineInstr *FirstMI = MemOps[0].MI;
1014 unsigned Opcode = FirstMI->getOpcode();
1015 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
1016 unsigned Size = getLSMultipleTransferSize(FirstMI);
1017
1018 unsigned SIndex = 0;
1019 unsigned EIndex = MemOps.size();
1020 do {
1021 // Look at the first instruction.
1022 const MachineInstr *MI = MemOps[SIndex].MI;
1023 int Offset = MemOps[SIndex].Offset;
1024 const MachineOperand &PMO = getLoadStoreRegOp(*MI);
1025 Register PReg = PMO.getReg();
1026 unsigned PRegNum = PMO.isUndef() ? std::numeric_limits<unsigned>::max()
1027 : TRI->getEncodingValue(PReg);
1028 unsigned Latest = SIndex;
1029 unsigned Earliest = SIndex;
1030 unsigned Count = 1;
1031 bool CanMergeToLSDouble =
1032 STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
1033 // ARM errata 602117: LDRD with base in list may result in incorrect base
1034 // register when interrupted or faulted.
1035 if (STI->isCortexM3() && isi32Load(Opcode) &&
1036 PReg == getLoadStoreBaseOp(*MI).getReg())
1037 CanMergeToLSDouble = false;
1038
1039 bool CanMergeToLSMulti = true;
1040 // On swift vldm/vstm starting with an odd register number as that needs
1041 // more uops than single vldrs.
1042 if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)
1043 CanMergeToLSMulti = false;
1044
1045 // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
1046 // deprecated; LDM to PC is fine but cannot happen here.
1047 if (PReg == ARM::SP || PReg == ARM::PC)
1048 CanMergeToLSMulti = CanMergeToLSDouble = false;
1049
1050 // Should we be conservative?
1051 if (STI->getCLOpts().assume_misaligned_load_store &&
1052 !mayCombineMisaligned(*STI, *MI))
1053 CanMergeToLSMulti = CanMergeToLSDouble = false;
1054
1055 // vldm / vstm limit are 32 for S variants, 16 for D variants.
1056 unsigned Limit;
1057 switch (Opcode) {
1058 default:
1059 Limit = UINT_MAX;
1060 break;
1061 case ARM::VLDRD:
1062 case ARM::VSTRD:
1063 Limit = 16;
1064 break;
1065 }
1066
1067 // Merge following instructions where possible.
1068 for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
1069 int NewOffset = MemOps[I].Offset;
1070 if (NewOffset != Offset + (int)Size)
1071 break;
1072 const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
1073 Register Reg = MO.getReg();
1074 if (Reg == ARM::SP || Reg == ARM::PC)
1075 break;
1076 if (Count == Limit)
1077 break;
1078
1079 // See if the current load/store may be part of a multi load/store.
1080 unsigned RegNum = MO.isUndef() ? std::numeric_limits<unsigned>::max()
1081 : TRI->getEncodingValue(Reg);
1082 bool PartOfLSMulti = CanMergeToLSMulti;
1083 if (PartOfLSMulti) {
1084 // Register numbers must be in ascending order.
1085 if (RegNum <= PRegNum)
1086 PartOfLSMulti = false;
1087 // For VFP / NEON load/store multiples, the registers must be
1088 // consecutive and within the limit on the number of registers per
1089 // instruction.
1090 else if (!isNotVFP && RegNum != PRegNum+1)
1091 PartOfLSMulti = false;
1092 }
1093 // See if the current load/store may be part of a double load/store.
1094 bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
1095
1096 if (!PartOfLSMulti && !PartOfLSDouble)
1097 break;
1098 CanMergeToLSMulti &= PartOfLSMulti;
1099 CanMergeToLSDouble &= PartOfLSDouble;
1100 // Track MemOp with latest and earliest position (Positions are
1101 // counted in reverse).
1102 unsigned Position = MemOps[I].Position;
1103 if (Position < MemOps[Latest].Position)
1104 Latest = I;
1105 else if (Position > MemOps[Earliest].Position)
1106 Earliest = I;
1107 // Prepare for next MemOp.
1108 Offset += Size;
1109 PRegNum = RegNum;
1110 }
1111
1112 // Form a candidate from the Ops collected so far.
1113 MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
1114 for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1115 Candidate->Instrs.push_back(MemOps[C].MI);
1116 Candidate->LatestMIIdx = Latest - SIndex;
1117 Candidate->EarliestMIIdx = Earliest - SIndex;
1118 Candidate->InsertPos = MemOps[Latest].Position;
1119 if (Count == 1)
1120 CanMergeToLSMulti = CanMergeToLSDouble = false;
1121 Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1122 Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
1123 Candidates.push_back(Candidate);
1124 // Continue after the chain.
1125 SIndex += Count;
1126 } while (SIndex < EIndex);
1127}
1128
1129static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1131 switch (Opc) {
1132 default: llvm_unreachable("Unhandled opcode!");
1133 case ARM::LDMIA:
1134 case ARM::LDMDA:
1135 case ARM::LDMDB:
1136 case ARM::LDMIB:
1137 switch (Mode) {
1138 default: llvm_unreachable("Unhandled submode!");
1139 case ARM_AM::ia: return ARM::LDMIA_UPD;
1140 case ARM_AM::ib: return ARM::LDMIB_UPD;
1141 case ARM_AM::da: return ARM::LDMDA_UPD;
1142 case ARM_AM::db: return ARM::LDMDB_UPD;
1143 }
1144 case ARM::STMIA:
1145 case ARM::STMDA:
1146 case ARM::STMDB:
1147 case ARM::STMIB:
1148 switch (Mode) {
1149 default: llvm_unreachable("Unhandled submode!");
1150 case ARM_AM::ia: return ARM::STMIA_UPD;
1151 case ARM_AM::ib: return ARM::STMIB_UPD;
1152 case ARM_AM::da: return ARM::STMDA_UPD;
1153 case ARM_AM::db: return ARM::STMDB_UPD;
1154 }
1155 case ARM::t2LDMIA:
1156 case ARM::t2LDMDB:
1157 switch (Mode) {
1158 default: llvm_unreachable("Unhandled submode!");
1159 case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1160 case ARM_AM::db: return ARM::t2LDMDB_UPD;
1161 }
1162 case ARM::t2STMIA:
1163 case ARM::t2STMDB:
1164 switch (Mode) {
1165 default: llvm_unreachable("Unhandled submode!");
1166 case ARM_AM::ia: return ARM::t2STMIA_UPD;
1167 case ARM_AM::db: return ARM::t2STMDB_UPD;
1168 }
1169 case ARM::VLDMSIA:
1170 switch (Mode) {
1171 default: llvm_unreachable("Unhandled submode!");
1172 case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1173 case ARM_AM::db: return ARM::VLDMSDB_UPD;
1174 }
1175 case ARM::VLDMDIA:
1176 switch (Mode) {
1177 default: llvm_unreachable("Unhandled submode!");
1178 case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1179 case ARM_AM::db: return ARM::VLDMDDB_UPD;
1180 }
1181 case ARM::VSTMSIA:
1182 switch (Mode) {
1183 default: llvm_unreachable("Unhandled submode!");
1184 case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1185 case ARM_AM::db: return ARM::VSTMSDB_UPD;
1186 }
1187 case ARM::VSTMDIA:
1188 switch (Mode) {
1189 default: llvm_unreachable("Unhandled submode!");
1190 case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1191 case ARM_AM::db: return ARM::VSTMDDB_UPD;
1192 }
1193 }
1194}
1195
1196/// Check if the given instruction increments or decrements a register and
1197/// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1198/// generated by the instruction are possibly read as well.
1200 ARMCC::CondCodes Pred, Register PredReg) {
1201 bool CheckCPSRDef;
1202 int Scale;
1203 switch (MI.getOpcode()) {
1204 case ARM::tADDi8: Scale = 4; CheckCPSRDef = true; break;
1205 case ARM::tSUBi8: Scale = -4; CheckCPSRDef = true; break;
1206 case ARM::t2SUBri:
1207 case ARM::t2SUBspImm:
1208 case ARM::SUBri: Scale = -1; CheckCPSRDef = true; break;
1209 case ARM::t2ADDri:
1210 case ARM::t2ADDspImm:
1211 case ARM::ADDri: Scale = 1; CheckCPSRDef = true; break;
1212 case ARM::tADDspi: Scale = 4; CheckCPSRDef = false; break;
1213 case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1214 default: return 0;
1215 }
1216
1217 Register MIPredReg;
1218 if (MI.getOperand(0).getReg() != Reg ||
1219 MI.getOperand(1).getReg() != Reg ||
1220 getInstrPredicate(MI, MIPredReg) != Pred ||
1221 MIPredReg != PredReg)
1222 return 0;
1223
1224 if (CheckCPSRDef && definesCPSR(MI))
1225 return 0;
1226 return MI.getOperand(2).getImm() * Scale;
1227}
1228
1229/// Searches for an increment or decrement of \p Reg before \p MBBI.
1232 ARMCC::CondCodes Pred, Register PredReg, int &Offset) {
1233 Offset = 0;
1234 MachineBasicBlock &MBB = *MBBI->getParent();
1235 MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1236 MachineBasicBlock::iterator EndMBBI = MBB.end();
1237 if (MBBI == BeginMBBI)
1238 return EndMBBI;
1239
1240 // Skip debug values.
1241 MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1242 while (PrevMBBI->isDebugInstr() && PrevMBBI != BeginMBBI)
1243 --PrevMBBI;
1244
1245 Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1246 return Offset == 0 ? EndMBBI : PrevMBBI;
1247}
1248
1249/// Searches for a increment or decrement of \p Reg after \p MBBI.
1252 ARMCC::CondCodes Pred, Register PredReg, int &Offset,
1253 const TargetRegisterInfo *TRI) {
1254 Offset = 0;
1255 MachineBasicBlock &MBB = *MBBI->getParent();
1256 MachineBasicBlock::iterator EndMBBI = MBB.end();
1257 MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1258 while (NextMBBI != EndMBBI) {
1259 // Skip debug values.
1260 while (NextMBBI != EndMBBI && NextMBBI->isDebugInstr())
1261 ++NextMBBI;
1262 if (NextMBBI == EndMBBI)
1263 return EndMBBI;
1264
1265 unsigned Off = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1266 if (Off) {
1267 Offset = Off;
1268 return NextMBBI;
1269 }
1270
1271 // SP can only be combined if it is the next instruction after the original
1272 // MBBI, otherwise we may be incrementing the stack pointer (invalidating
1273 // anything below the new pointer) when its frame elements are still in
1274 // use. Other registers can attempt to look further, until a different use
1275 // or def of the register is found.
1276 if (Reg == ARM::SP || NextMBBI->readsRegister(Reg, TRI) ||
1277 NextMBBI->definesRegister(Reg, TRI))
1278 return EndMBBI;
1279
1280 ++NextMBBI;
1281 }
1282 return EndMBBI;
1283}
1284
1285/// Fold proceeding/trailing inc/dec of base register into the
1286/// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
1287///
1288/// stmia rn, <ra, rb, rc>
1289/// rn := rn + 4 * 3;
1290/// =>
1291/// stmia rn!, <ra, rb, rc>
1292///
1293/// rn := rn - 4 * 3;
1294/// ldmia rn, <ra, rb, rc>
1295/// =>
1296/// ldmdb rn!, <ra, rb, rc>
1297bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
1298 // Thumb1 is already using updating loads/stores.
1299 if (isThumb1) return false;
1300 LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);
1301
1302 const MachineOperand &BaseOP = MI->getOperand(0);
1303 Register Base = BaseOP.getReg();
1304 bool BaseKill = BaseOP.isKill();
1305 Register PredReg;
1307 unsigned Opcode = MI->getOpcode();
1308 DebugLoc DL = MI->getDebugLoc();
1309
1310 // Can't use an updating ld/st if the base register is also a dest
1311 // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
1312 for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1313 if (MO.getReg() == Base)
1314 return false;
1315
1316 int Bytes = getLSMultipleTransferSize(MI);
1317 MachineBasicBlock &MBB = *MI->getParent();
1319 int Offset;
1321 = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1323 if (Mode == ARM_AM::ia && Offset == -Bytes) {
1324 Mode = ARM_AM::db;
1325 } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1326 Mode = ARM_AM::da;
1327 } else {
1328 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1329 if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
1330 ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {
1331
1332 // We couldn't find an inc/dec to merge. But if the base is dead, we
1333 // can still change to a writeback form as that will save us 2 bytes
1334 // of code size. It can create WAW hazards though, so only do it if
1335 // we're minimizing code size.
1336 if (!STI->hasMinSize() || !BaseKill)
1337 return false;
1338
1339 bool HighRegsUsed = false;
1340 for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1341 if (MO.getReg() >= ARM::R8) {
1342 HighRegsUsed = true;
1343 break;
1344 }
1345
1346 if (!HighRegsUsed)
1347 MergeInstr = MBB.end();
1348 else
1349 return false;
1350 }
1351 }
1352 if (MergeInstr != MBB.end()) {
1353 LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr);
1354 eraseInstr(MergeInstr);
1355 }
1356
1357 unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
1358 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1359 .addReg(Base, getDefRegState(true)) // WB base register
1360 .addReg(Base, getKillRegState(BaseKill))
1361 .addImm(Pred).addReg(PredReg);
1362
1363 // Transfer the rest of operands.
1364 for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 3))
1365 MIB.add(MO);
1366
1367 // Transfer memoperands.
1368 MIB.setMemRefs(MI->memoperands());
1369
1370 LLVM_DEBUG(dbgs() << " Added new load/store: " << *MIB);
1372 return true;
1373}
1374
1375static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1377 switch (Opc) {
1378 case ARM::LDRi12:
1379 return ARM::LDR_PRE_IMM;
1380 case ARM::STRi12:
1381 return ARM::STR_PRE_IMM;
1382 case ARM::VLDRS:
1383 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1384 case ARM::VLDRD:
1385 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1386 case ARM::VSTRS:
1387 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1388 case ARM::VSTRD:
1389 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1390 case ARM::t2LDRi8:
1391 case ARM::t2LDRi12:
1392 return ARM::t2LDR_PRE;
1393 case ARM::t2STRi8:
1394 case ARM::t2STRi12:
1395 return ARM::t2STR_PRE;
1396 default: llvm_unreachable("Unhandled opcode!");
1397 }
1398}
1399
1400static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1402 switch (Opc) {
1403 case ARM::LDRi12:
1404 return ARM::LDR_POST_IMM;
1405 case ARM::STRi12:
1406 return ARM::STR_POST_IMM;
1407 case ARM::VLDRS:
1408 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1409 case ARM::VLDRD:
1410 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1411 case ARM::VSTRS:
1412 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1413 case ARM::VSTRD:
1414 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1415 case ARM::t2LDRi8:
1416 case ARM::t2LDRi12:
1417 return ARM::t2LDR_POST;
1418 case ARM::t2LDRBi8:
1419 case ARM::t2LDRBi12:
1420 return ARM::t2LDRB_POST;
1421 case ARM::t2LDRSBi8:
1422 case ARM::t2LDRSBi12:
1423 return ARM::t2LDRSB_POST;
1424 case ARM::t2LDRHi8:
1425 case ARM::t2LDRHi12:
1426 return ARM::t2LDRH_POST;
1427 case ARM::t2LDRSHi8:
1428 case ARM::t2LDRSHi12:
1429 return ARM::t2LDRSH_POST;
1430 case ARM::t2STRi8:
1431 case ARM::t2STRi12:
1432 return ARM::t2STR_POST;
1433 case ARM::t2STRBi8:
1434 case ARM::t2STRBi12:
1435 return ARM::t2STRB_POST;
1436 case ARM::t2STRHi8:
1437 case ARM::t2STRHi12:
1438 return ARM::t2STRH_POST;
1439
1440 case ARM::MVE_VLDRBS16:
1441 return ARM::MVE_VLDRBS16_post;
1442 case ARM::MVE_VLDRBS32:
1443 return ARM::MVE_VLDRBS32_post;
1444 case ARM::MVE_VLDRBU16:
1445 return ARM::MVE_VLDRBU16_post;
1446 case ARM::MVE_VLDRBU32:
1447 return ARM::MVE_VLDRBU32_post;
1448 case ARM::MVE_VLDRHS32:
1449 return ARM::MVE_VLDRHS32_post;
1450 case ARM::MVE_VLDRHU32:
1451 return ARM::MVE_VLDRHU32_post;
1452 case ARM::MVE_VLDRBU8:
1453 return ARM::MVE_VLDRBU8_post;
1454 case ARM::MVE_VLDRHU16:
1455 return ARM::MVE_VLDRHU16_post;
1456 case ARM::MVE_VLDRWU32:
1457 return ARM::MVE_VLDRWU32_post;
1458 case ARM::MVE_VSTRB16:
1459 return ARM::MVE_VSTRB16_post;
1460 case ARM::MVE_VSTRB32:
1461 return ARM::MVE_VSTRB32_post;
1462 case ARM::MVE_VSTRH32:
1463 return ARM::MVE_VSTRH32_post;
1464 case ARM::MVE_VSTRBU8:
1465 return ARM::MVE_VSTRBU8_post;
1466 case ARM::MVE_VSTRHU16:
1467 return ARM::MVE_VSTRHU16_post;
1468 case ARM::MVE_VSTRWU32:
1469 return ARM::MVE_VSTRWU32_post;
1470
1471 default: llvm_unreachable("Unhandled opcode!");
1472 }
1473}
1474
1475/// Fold proceeding/trailing inc/dec of base register into the
1476/// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
1477bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
1478 // Thumb1 doesn't have updating LDR/STR.
1479 // FIXME: Use LDM/STM with single register instead.
1480 if (isThumb1) return false;
1481 LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);
1482
1484 bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
1485 unsigned Opcode = MI->getOpcode();
1486 DebugLoc DL = MI->getDebugLoc();
1487 bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1488 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
1489 bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1490 if (isi32Load(Opcode) || isi32Store(Opcode))
1491 if (MI->getOperand(2).getImm() != 0)
1492 return false;
1493 if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
1494 return false;
1495
1496 // Can't do the merge if the destination register is the same as the would-be
1497 // writeback register.
1498 if (MI->getOperand(0).getReg() == Base)
1499 return false;
1500
1501 Register PredReg;
1503 int Bytes = getLSMultipleTransferSize(MI);
1504 MachineBasicBlock &MBB = *MI->getParent();
1506 int Offset;
1508 = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1509 unsigned NewOpc;
1510 if (!isAM5 && Offset == Bytes) {
1511 NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1512 } else if (Offset == -Bytes) {
1513 NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1514 } else {
1515 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1516 if (MergeInstr == MBB.end())
1517 return false;
1518
1520 if ((isAM5 && Offset != Bytes) ||
1521 (!isAM5 && !isLegalAddressImm(NewOpc, Offset, TII))) {
1523 if (isAM5 || !isLegalAddressImm(NewOpc, Offset, TII))
1524 return false;
1525 }
1526 }
1527 LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr);
1528 eraseInstr(MergeInstr);
1529
1531
1532 bool isLd = isLoadSingle(Opcode);
1533 if (isAM5) {
1534 // VLDM[SD]_UPD, VSTM[SD]_UPD
1535 // (There are no base-updating versions of VLDR/VSTR instructions, but the
1536 // updating load/store-multiple instructions can be used with only one
1537 // register.)
1538 MachineOperand &MO = MI->getOperand(0);
1539 auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1540 .addReg(Base, getDefRegState(true)) // WB base register
1541 .addReg(Base, getKillRegState(isLd ? BaseKill : false))
1542 .addImm(Pred)
1543 .addReg(PredReg)
1544 .addReg(MO.getReg(), (isLd ? getDefRegState(true)
1545 : getKillRegState(MO.isKill())))
1546 .cloneMemRefs(*MI);
1547 (void)MIB;
1548 LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);
1549 } else if (isLd) {
1550 if (isAM2) {
1551 // LDR_PRE, LDR_POST
1552 if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
1553 auto MIB =
1554 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1555 .addReg(Base, RegState::Define)
1556 .addReg(Base)
1557 .addImm(Offset)
1558 .addImm(Pred)
1559 .addReg(PredReg)
1560 .cloneMemRefs(*MI);
1561 (void)MIB;
1562 LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);
1563 } else {
1565 auto MIB =
1566 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1567 .addReg(Base, RegState::Define)
1568 .addReg(Base)
1569 .addReg(0)
1570 .addImm(Imm)
1571 .add(predOps(Pred, PredReg))
1572 .cloneMemRefs(*MI);
1573 (void)MIB;
1574 LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);
1575 }
1576 } else {
1577 // t2LDR_PRE, t2LDR_POST
1578 auto MIB =
1579 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1580 .addReg(Base, RegState::Define)
1581 .addReg(Base)
1582 .addImm(Offset)
1583 .add(predOps(Pred, PredReg))
1584 .cloneMemRefs(*MI);
1585 (void)MIB;
1586 LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);
1587 }
1588 } else {
1589 MachineOperand &MO = MI->getOperand(0);
1590 // FIXME: post-indexed stores use am2offset_imm, which still encodes
1591 // the vestigial zero-reg offset register. When that's fixed, this clause
1592 // can be removed entirely.
1593 if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
1595 // STR_PRE, STR_POST
1596 auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1597 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1598 .addReg(Base)
1599 .addReg(0)
1600 .addImm(Imm)
1601 .add(predOps(Pred, PredReg))
1602 .cloneMemRefs(*MI);
1603 (void)MIB;
1604 LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);
1605 } else {
1606 // t2STR_PRE, t2STR_POST
1607 auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1608 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1609 .addReg(Base)
1610 .addImm(Offset)
1611 .add(predOps(Pred, PredReg))
1612 .cloneMemRefs(*MI);
1613 (void)MIB;
1614 LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);
1615 }
1616 }
1618
1619 return true;
1620}
1621
1622bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) {
1623 unsigned Opcode = MI.getOpcode();
1624 assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1625 "Must have t2STRDi8 or t2LDRDi8");
1626 if (MI.getOperand(3).getImm() != 0)
1627 return false;
1628 LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << MI);
1629
1630 // Behaviour for writeback is undefined if base register is the same as one
1631 // of the others.
1632 const MachineOperand &BaseOp = MI.getOperand(2);
1633 Register Base = BaseOp.getReg();
1634 const MachineOperand &Reg0Op = MI.getOperand(0);
1635 const MachineOperand &Reg1Op = MI.getOperand(1);
1636 if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1637 return false;
1638
1639 Register PredReg;
1642 MachineBasicBlock &MBB = *MI.getParent();
1643 int Offset;
1645 PredReg, Offset);
1646 unsigned NewOpc;
1647 if (Offset == 8 || Offset == -8) {
1648 NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1649 } else {
1650 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1651 if (MergeInstr == MBB.end())
1652 return false;
1653 NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1654 if (!isLegalAddressImm(NewOpc, Offset, TII))
1655 return false;
1656 }
1657 LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr);
1658 eraseInstr(MergeInstr);
1659
1660 DebugLoc DL = MI.getDebugLoc();
1661 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1662 if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
1663 MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define);
1664 } else {
1665 assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
1666 MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op);
1667 }
1668 MIB.addReg(BaseOp.getReg(), RegState::Kill)
1669 .addImm(Offset).addImm(Pred).addReg(PredReg);
1670 assert(TII->get(Opcode).getNumOperands() == 6 &&
1671 TII->get(NewOpc).getNumOperands() == 7 &&
1672 "Unexpected number of operands in Opcode specification.");
1673
1674 // Transfer implicit operands.
1675 for (const MachineOperand &MO : MI.implicit_operands())
1676 MIB.add(MO);
1677 MIB.cloneMemRefs(MI);
1678
1679 LLVM_DEBUG(dbgs() << " Added new load/store: " << *MIB);
1681 return true;
1682}
1683
1684/// Returns true if instruction is a memory operation that this pass is capable
1685/// of operating on.
1686static bool isMemoryOp(const MachineInstr &MI) {
1687 unsigned Opcode = MI.getOpcode();
1688 switch (Opcode) {
1689 case ARM::VLDRS:
1690 case ARM::VSTRS:
1691 case ARM::VLDRD:
1692 case ARM::VSTRD:
1693 case ARM::LDRi12:
1694 case ARM::STRi12:
1695 case ARM::tLDRi:
1696 case ARM::tSTRi:
1697 case ARM::tLDRspi:
1698 case ARM::tSTRspi:
1699 case ARM::t2LDRi8:
1700 case ARM::t2LDRi12:
1701 case ARM::t2STRi8:
1702 case ARM::t2STRi12:
1703 break;
1704 default:
1705 return false;
1706 }
1707 if (!MI.getOperand(1).isReg())
1708 return false;
1709
1710 // When no memory operands are present, conservatively assume unaligned,
1711 // volatile, unfoldable.
1712 if (!MI.hasOneMemOperand())
1713 return false;
1714
1715 const MachineMemOperand &MMO = **MI.memoperands_begin();
1716
1717 // Don't touch volatile memory accesses - we may be changing their order.
1718 // TODO: We could allow unordered and monotonic atomics here, but we need to
1719 // make sure the resulting ldm/stm is correctly marked as atomic.
1720 if (MMO.isVolatile() || MMO.isAtomic())
1721 return false;
1722
1723 // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1724 // not.
1725 if (MMO.getAlign() < Align(4))
1726 return false;
1727
1728 // str <undef> could probably be eliminated entirely, but for now we just want
1729 // to avoid making a mess of it.
1730 // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1731 if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())
1732 return false;
1733
1734 // Likewise don't mess with references to undefined addresses.
1735 if (MI.getOperand(1).isUndef())
1736 return false;
1737
1738 return true;
1739}
1740
1743 bool isDef, unsigned NewOpc, unsigned Reg,
1744 bool RegDeadKill, bool RegUndef, unsigned BaseReg,
1745 bool BaseKill, bool BaseUndef, ARMCC::CondCodes Pred,
1746 unsigned PredReg, const TargetInstrInfo *TII,
1747 MachineInstr *MI) {
1748 if (isDef) {
1749 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1750 TII->get(NewOpc))
1751 .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
1752 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1753 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1754 // FIXME: This is overly conservative; the new instruction accesses 4
1755 // bytes, not 8.
1756 MIB.cloneMemRefs(*MI);
1757 } else {
1758 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1759 TII->get(NewOpc))
1760 .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
1761 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1762 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1763 // FIXME: This is overly conservative; the new instruction accesses 4
1764 // bytes, not 8.
1765 MIB.cloneMemRefs(*MI);
1766 }
1767}
1768
1769bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1771 MachineInstr *MI = &*MBBI;
1772 unsigned Opcode = MI->getOpcode();
1773 // FIXME: Code/comments below check Opcode == t2STRDi8, but this check returns
1774 // if we see this opcode.
1775 if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
1776 return false;
1777
1778 const MachineOperand &BaseOp = MI->getOperand(2);
1779 Register BaseReg = BaseOp.getReg();
1780 Register EvenReg = MI->getOperand(0).getReg();
1781 Register OddReg = MI->getOperand(1).getReg();
1782 unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1783 unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false);
1784
1785 // ARM errata 602117: LDRD with base in list may result in incorrect base
1786 // register when interrupted or faulted.
1787 bool Errata602117 = EvenReg == BaseReg &&
1788 (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
1789 // ARM LDRD/STRD needs consecutive registers.
1790 bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
1791 (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
1792
1793 if (!Errata602117 && !NonConsecutiveRegs)
1794 return false;
1795
1796 bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
1797 bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1798 bool EvenDeadKill = isLd ?
1799 MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
1800 bool EvenUndef = MI->getOperand(0).isUndef();
1801 bool OddDeadKill = isLd ?
1802 MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
1803 bool OddUndef = MI->getOperand(1).isUndef();
1804 bool BaseKill = BaseOp.isKill();
1805 bool BaseUndef = BaseOp.isUndef();
1806 assert((isT2 || !MI->getOperand(3).getReg().isValid()) &&
1807 "register offset not handled below");
1808 int OffImm = getMemoryOpOffset(*MI);
1809 Register PredReg;
1811
1812 if (OddRegNum > EvenRegNum && OffImm == 0) {
1813 // Ascending register numbers and no offset. It's safe to change it to a
1814 // ldm or stm.
1815 unsigned NewOpc = (isLd)
1816 ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1817 : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1818 if (isLd) {
1819 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1820 .add(BaseOp)
1821 .addImm(Pred)
1822 .addReg(PredReg)
1823 .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1824 .addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill))
1825 .cloneMemRefs(*MI);
1826 ++NumLDRD2LDM;
1827 } else {
1828 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1829 .add(BaseOp)
1830 .addImm(Pred)
1831 .addReg(PredReg)
1832 .addReg(EvenReg,
1833 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
1834 .addReg(OddReg,
1835 getKillRegState(OddDeadKill) | getUndefRegState(OddUndef))
1836 .cloneMemRefs(*MI);
1837 ++NumSTRD2STM;
1838 }
1839 } else {
1840 // Split into two instructions.
1841 unsigned NewOpc = (isLd)
1842 ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1843 : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1844 // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
1845 // so adjust and use t2LDRi12 here for that.
1846 unsigned NewOpc2 = (isLd)
1847 ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1848 : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1849 // If this is a load, make sure the first load does not clobber the base
1850 // register before the second load reads it.
1851 if (isLd && TRI->regsOverlap(EvenReg, BaseReg)) {
1852 assert(!TRI->regsOverlap(OddReg, BaseReg));
1853 InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,
1854 false, BaseReg, false, BaseUndef, Pred, PredReg, TII, MI);
1855 InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,
1856 false, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,
1857 MI);
1858 } else {
1859 if (OddReg == EvenReg && EvenDeadKill) {
1860 // If the two source operands are the same, the kill marker is
1861 // probably on the first one. e.g.
1862 // t2STRDi8 killed %r5, %r5, killed %r9, 0, 14, %reg0
1863 EvenDeadKill = false;
1864 OddDeadKill = true;
1865 }
1866 // Never kill the base register in the first instruction.
1867 if (EvenReg == BaseReg)
1868 EvenDeadKill = false;
1869 InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,
1870 EvenUndef, BaseReg, false, BaseUndef, Pred, PredReg, TII,
1871 MI);
1872 InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,
1873 OddUndef, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,
1874 MI);
1875 }
1876 if (isLd)
1877 ++NumLDRD2LDR;
1878 else
1879 ++NumSTRD2STR;
1880 }
1881
1882 MBBI = eraseInstr(MBBI);
1883 return true;
1884}
1885
1886/// An optimization pass to turn multiple LDR / STR ops of the same base and
1887/// incrementing offset into LDM / STM ops.
1888bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
1889 MemOpQueue MemOps;
1890 unsigned CurrBase = 0;
1891 unsigned CurrOpc = ~0u;
1892 ARMCC::CondCodes CurrPred = ARMCC::AL;
1893 unsigned Position = 0;
1894 assert(Candidates.size() == 0);
1895 assert(MergeBaseCandidates.size() == 0);
1896 LiveRegsValid = false;
1897
1899 I = MBBI) {
1900 // The instruction in front of the iterator is the one we look at.
1901 MBBI = std::prev(I);
1902 if (FixInvalidRegPairOp(MBB, MBBI))
1903 continue;
1904 ++Position;
1905
1906 if (isMemoryOp(*MBBI)) {
1907 unsigned Opcode = MBBI->getOpcode();
1908 const MachineOperand &MO = MBBI->getOperand(0);
1909 Register Reg = MO.getReg();
1911 Register PredReg;
1914 if (CurrBase == 0) {
1915 // Start of a new chain.
1916 CurrBase = Base;
1917 CurrOpc = Opcode;
1918 CurrPred = Pred;
1919 MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1920 continue;
1921 }
1922 // Note: No need to match PredReg in the next if.
1923 if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
1924 // Watch out for:
1925 // r4 := ldr [r0, #8]
1926 // r4 := ldr [r0, #4]
1927 // or
1928 // r0 := ldr [r0]
1929 // If a load overrides the base register or a register loaded by
1930 // another load in our chain, we cannot take this instruction.
1931 bool Overlap = false;
1932 if (isLoadSingle(Opcode)) {
1933 Overlap = (Base == Reg);
1934 if (!Overlap) {
1935 for (const MemOpQueueEntry &E : MemOps) {
1936 if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
1937 Overlap = true;
1938 break;
1939 }
1940 }
1941 }
1942 }
1943
1944 if (!Overlap) {
1945 // Check offset and sort memory operation into the current chain.
1946 if (Offset > MemOps.back().Offset) {
1947 MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1948 continue;
1949 } else {
1950 MemOpQueue::iterator MI, ME;
1951 for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1952 if (Offset < MI->Offset) {
1953 // Found a place to insert.
1954 break;
1955 }
1956 if (Offset == MI->Offset) {
1957 // Collision, abort.
1958 MI = ME;
1959 break;
1960 }
1961 }
1962 if (MI != MemOps.end()) {
1963 MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position));
1964 continue;
1965 }
1966 }
1967 }
1968 }
1969
1970 // Don't advance the iterator; The op will start a new chain next.
1971 MBBI = I;
1972 --Position;
1973 // Fallthrough to look into existing chain.
1974 } else if (MBBI->isDebugInstr()) {
1975 continue;
1976 } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
1977 MBBI->getOpcode() == ARM::t2STRDi8) {
1978 // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
1979 // remember them because we may still be able to merge add/sub into them.
1980 MergeBaseCandidates.push_back(&*MBBI);
1981 }
1982
1983 // If we are here then the chain is broken; Extract candidates for a merge.
1984 if (MemOps.size() > 0) {
1985 FormCandidates(MemOps);
1986 // Reset for the next chain.
1987 CurrBase = 0;
1988 CurrOpc = ~0u;
1989 CurrPred = ARMCC::AL;
1990 MemOps.clear();
1991 }
1992 }
1993 if (MemOps.size() > 0)
1994 FormCandidates(MemOps);
1995
1996 // Sort candidates so they get processed from end to begin of the basic
1997 // block later; This is necessary for liveness calculation.
1998 auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1999 return M0->InsertPos < M1->InsertPos;
2000 };
2001 llvm::sort(Candidates, LessThan);
2002
2003 // Go through list of candidates and merge.
2004 bool Changed = false;
2005 for (const MergeCandidate *Candidate : Candidates) {
2006 if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
2007 MachineInstr *Merged = MergeOpsUpdate(*Candidate);
2008 // Merge preceding/trailing base inc/dec into the merged op.
2009 if (Merged) {
2010 Changed = true;
2011 unsigned Opcode = Merged->getOpcode();
2012 if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
2013 MergeBaseUpdateLSDouble(*Merged);
2014 else
2015 MergeBaseUpdateLSMultiple(Merged);
2016 } else {
2017 for (MachineInstr *MI : Candidate->Instrs) {
2018 if (MergeBaseUpdateLoadStore(MI))
2019 Changed = true;
2020 }
2021 }
2022 } else {
2023 assert(Candidate->Instrs.size() == 1);
2024 if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
2025 Changed = true;
2026 }
2027 }
2028 Candidates.clear();
2029 // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
2030 for (MachineInstr *MI : MergeBaseCandidates)
2031 MergeBaseUpdateLSDouble(*MI);
2032 MergeBaseCandidates.clear();
2033
2034 return Changed;
2035}
2036
2037/// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
2038/// into the preceding stack restore so it directly restore the value of LR
2039/// into pc.
2040/// ldmfd sp!, {..., lr}
2041/// bx lr
2042/// or
2043/// ldmfd sp!, {..., lr}
2044/// mov pc, lr
2045/// =>
2046/// ldmfd sp!, {..., pc}
2047bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
2048 // Thumb1 LDM doesn't allow high registers.
2049 if (isThumb1) return false;
2050 if (MBB.empty()) return false;
2051
2053 if (MBBI != MBB.begin() && MBBI != MBB.end() &&
2054 (MBBI->getOpcode() == ARM::BX_RET ||
2055 MBBI->getOpcode() == ARM::tBX_RET ||
2056 MBBI->getOpcode() == ARM::MOVPCLR)) {
2057 MachineBasicBlock::iterator PrevI = std::prev(MBBI);
2058 // Ignore any debug instructions.
2059 while (PrevI->isDebugInstr() && PrevI != MBB.begin())
2060 --PrevI;
2061 MachineInstr &PrevMI = *PrevI;
2062 unsigned Opcode = PrevMI.getOpcode();
2063 if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
2064 Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
2065 Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
2066 MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1);
2067 if (MO.getReg() != ARM::LR)
2068 return false;
2069 unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
2070 assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
2071 Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
2072 PrevMI.setDesc(TII->get(NewOpc));
2073 MO.setReg(ARM::PC);
2074 PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI);
2076 return true;
2077 }
2078 }
2079 return false;
2080}
2081
2082bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {
2084 if (MBBI == MBB.begin() || MBBI == MBB.end() ||
2085 MBBI->getOpcode() != ARM::tBX_RET)
2086 return false;
2087
2089 --Prev;
2090 if (Prev->getOpcode() != ARM::tMOVr ||
2091 !Prev->definesRegister(ARM::LR, /*TRI=*/nullptr))
2092 return false;
2093
2094 for (auto Use : Prev->uses())
2095 if (Use.isKill()) {
2096 assert(STI->hasV4TOps());
2097 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
2098 .addReg(Use.getReg(), RegState::Kill)
2102 eraseInstr(Prev);
2103 return true;
2104 }
2105
2106 llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
2107}
2108
2109bool ARMLoadStoreOpt::runOnMachineFunction(
2110 MachineFunction &Fn, const RegisterClassInfo &RegClassInfo) {
2111 MF = &Fn;
2112 STI = &Fn.getSubtarget<ARMSubtarget>();
2113 TL = STI->getTargetLowering();
2114 AFI = Fn.getInfo<ARMFunctionInfo>();
2115 TII = STI->getInstrInfo();
2116 TRI = STI->getRegisterInfo();
2117 RCI = &RegClassInfo;
2118
2119 isThumb2 = AFI->isThumb2Function();
2120 isThumb1 = AFI->isThumbFunction() && !isThumb2;
2121
2122 bool Modified = false, ModifiedLDMReturn = false;
2123 for (MachineBasicBlock &MBB : Fn) {
2124 Modified |= LoadStoreMultipleOpti(MBB);
2125 if (STI->hasV5TOps() && !AFI->shouldSignReturnAddress())
2126 ModifiedLDMReturn |= MergeReturnIntoLDM(MBB);
2127 if (isThumb1)
2128 Modified |= CombineMovBx(MBB);
2129 }
2130 Modified |= ModifiedLDMReturn;
2131
2132 // If we merged a BX instruction into an LDM, we need to re-calculate whether
2133 // LR is restored. This check needs to consider the whole function, not just
2134 // the instruction(s) we changed, because there may be other BX returns which
2135 // still need LR to be restored.
2136 if (ModifiedLDMReturn)
2138
2139 Allocator.DestroyAll();
2140 return Modified;
2141}
2142
2143bool ARMLoadStoreOptLegacy::runOnMachineFunction(MachineFunction &MF) {
2144 if (skipFunction(MF.getFunction()))
2145 return false;
2146 ARMLoadStoreOpt Impl;
2147 return Impl.runOnMachineFunction(
2148 MF, getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI());
2149}
2150
2151#define ARM_PREALLOC_LOAD_STORE_OPT_NAME \
2152 "ARM pre- register allocation load / store optimization pass"
2153
2154namespace {
2155
2156/// Pre- register allocation pass that move load / stores from consecutive
2157/// locations close to make it more likely they will be combined later.
2158struct ARMPreAllocLoadStoreOpt {
2160 const DataLayout *TD;
2161 const TargetInstrInfo *TII;
2162 const TargetRegisterInfo *TRI;
2163 const ARMSubtarget *STI;
2166 MachineFunction *MF;
2167
2168 bool runOnMachineFunction(MachineFunction &Fn, AliasAnalysis *AA,
2170
2171private:
2172 bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
2173 unsigned &NewOpc, Register &EvenReg, Register &OddReg,
2174 Register &BaseReg, int &Offset, Register &PredReg,
2175 ARMCC::CondCodes &Pred, bool &isT2);
2176 bool RescheduleOps(
2178 unsigned Base, bool isLd, DenseMap<MachineInstr *, unsigned> &MI2LocMap,
2180 bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
2181 bool DistributeIncrements();
2182 bool DistributeIncrements(Register Base);
2183};
2184
2185struct ARMPreAllocLoadStoreOptLegacy : public MachineFunctionPass {
2186 static char ID;
2187
2188 ARMPreAllocLoadStoreOptLegacy() : MachineFunctionPass(ID) {}
2189
2190 bool runOnMachineFunction(MachineFunction &Fn) override;
2191
2192 StringRef getPassName() const override {
2194 }
2195
2196 void getAnalysisUsage(AnalysisUsage &AU) const override {
2202 }
2203};
2204
2205char ARMPreAllocLoadStoreOptLegacy::ID = 0;
2206
2207} // end anonymous namespace
2208
2209INITIALIZE_PASS_BEGIN(ARMPreAllocLoadStoreOptLegacy, "arm-prera-ldst-opt",
2212INITIALIZE_PASS_END(ARMPreAllocLoadStoreOptLegacy, "arm-prera-ldst-opt",
2214
2215bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn,
2216 AliasAnalysis *AAIn,
2217 MachineDominatorTree *DTIn) {
2218 if (Fn.getSubtarget<ARMSubtarget>().getCLOpts().assume_misaligned_load_store)
2219 return false;
2220
2221 AA = AAIn;
2222 DT = DTIn;
2223 TD = &Fn.getDataLayout();
2224 STI = &Fn.getSubtarget<ARMSubtarget>();
2225 TII = STI->getInstrInfo();
2226 TRI = STI->getRegisterInfo();
2227 MRI = &Fn.getRegInfo();
2228 MF = &Fn;
2229
2230 bool Modified = DistributeIncrements();
2231 for (MachineBasicBlock &MFI : Fn)
2232 Modified |= RescheduleLoadStoreInstrs(&MFI);
2233
2234 return Modified;
2235}
2236
2237bool ARMPreAllocLoadStoreOptLegacy::runOnMachineFunction(MachineFunction &Fn) {
2238 if (skipFunction(Fn.getFunction()))
2239 return false;
2240
2241 ARMPreAllocLoadStoreOpt Impl;
2242 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2243 MachineDominatorTree *DT =
2244 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
2245 return Impl.runOnMachineFunction(Fn, AA, DT);
2246}
2247
2248static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
2252 SmallSet<unsigned, 4> &MemRegs,
2253 const TargetRegisterInfo *TRI,
2254 AliasAnalysis *AA) {
2255 // Are there stores / loads / calls between them?
2256 SmallSet<unsigned, 4> AddedRegPressure;
2257 while (++I != E) {
2258 if (I->isDebugInstr() || MemOps.count(&*I))
2259 continue;
2260 if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
2261 return false;
2262 if (I->mayStore() || (!isLd && I->mayLoad()))
2263 for (MachineInstr *MemOp : MemOps)
2264 if (I->mayAlias(AA, *MemOp, /*UseTBAA*/ false))
2265 return false;
2266 for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
2267 MachineOperand &MO = I->getOperand(j);
2268 if (!MO.isReg())
2269 continue;
2270 Register Reg = MO.getReg();
2271 if (MO.isDef() && TRI->regsOverlap(Reg, Base))
2272 return false;
2273 if (Reg != Base && !MemRegs.count(Reg))
2274 AddedRegPressure.insert(Reg);
2275 }
2276 }
2277
2278 // Estimate register pressure increase due to the transformation.
2279 if (MemRegs.size() <= 4)
2280 // Ok if we are moving small number of instructions.
2281 return true;
2282 return AddedRegPressure.size() <= MemRegs.size() * 2;
2283}
2284
2285bool ARMPreAllocLoadStoreOpt::CanFormLdStDWord(
2286 MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl, unsigned &NewOpc,
2287 Register &FirstReg, Register &SecondReg, Register &BaseReg, int &Offset,
2288 Register &PredReg, ARMCC::CondCodes &Pred, bool &isT2) {
2289 // Make sure we're allowed to generate LDRD/STRD.
2290 if (!STI->hasV5TEOps())
2291 return false;
2292
2293 // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
2294 unsigned Scale = 1;
2295 unsigned Opcode = Op0->getOpcode();
2296 if (Opcode == ARM::LDRi12) {
2297 NewOpc = ARM::LDRD;
2298 } else if (Opcode == ARM::STRi12) {
2299 NewOpc = ARM::STRD;
2300 } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
2301 NewOpc = ARM::t2LDRDi8;
2302 Scale = 4;
2303 isT2 = true;
2304 } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
2305 NewOpc = ARM::t2STRDi8;
2306 Scale = 4;
2307 isT2 = true;
2308 } else {
2309 return false;
2310 }
2311
2312 // Make sure the base address satisfies i64 ld / st alignment requirement.
2313 // At the moment, we ignore the memoryoperand's value.
2314 // If we want to use AliasAnalysis, we should check it accordingly.
2315 if (!Op0->hasOneMemOperand() ||
2316 (*Op0->memoperands_begin())->isVolatile() ||
2317 (*Op0->memoperands_begin())->isAtomic())
2318 return false;
2319
2320 Align Alignment = (*Op0->memoperands_begin())->getAlign();
2321 Align ReqAlign = STI->getDualLoadStoreAlignment();
2322 if (Alignment < ReqAlign)
2323 return false;
2324
2325 // Then make sure the immediate offset fits.
2326 int OffImm = getMemoryOpOffset(*Op0);
2327 if (isT2) {
2328 int Limit = (1 << 8) * Scale;
2329 if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
2330 return false;
2331 Offset = OffImm;
2332 } else {
2334 if (OffImm < 0) {
2336 OffImm = - OffImm;
2337 }
2338 int Limit = (1 << 8) * Scale;
2339 if (OffImm >= Limit || (OffImm & (Scale-1)))
2340 return false;
2341 Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
2342 }
2343 FirstReg = Op0->getOperand(0).getReg();
2344 SecondReg = Op1->getOperand(0).getReg();
2345 if (FirstReg == SecondReg)
2346 return false;
2347 BaseReg = Op0->getOperand(1).getReg();
2348 Pred = getInstrPredicate(*Op0, PredReg);
2349 dl = Op0->getDebugLoc();
2350 return true;
2351}
2352
2353bool ARMPreAllocLoadStoreOpt::RescheduleOps(
2354 MachineBasicBlock *MBB, SmallVectorImpl<MachineInstr *> &Ops, unsigned Base,
2355 bool isLd, DenseMap<MachineInstr *, unsigned> &MI2LocMap,
2356 SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> &RegisterMap) {
2357 bool RetVal = false;
2358
2359 // Sort by offset (in reverse order).
2360 llvm::sort(Ops, [](const MachineInstr *LHS, const MachineInstr *RHS) {
2361 int LOffset = getMemoryOpOffset(*LHS);
2362 int ROffset = getMemoryOpOffset(*RHS);
2363 assert(LHS == RHS || LOffset != ROffset);
2364 return LOffset > ROffset;
2365 });
2366
2367 // The loads / stores of the same base are in order. Scan them from first to
2368 // last and check for the following:
2369 // 1. Any def of base.
2370 // 2. Any gaps.
2371 while (Ops.size() > 1) {
2372 unsigned FirstLoc = ~0U;
2373 unsigned LastLoc = 0;
2374 MachineInstr *FirstOp = nullptr;
2375 MachineInstr *LastOp = nullptr;
2376 int LastOffset = 0;
2377 unsigned LastOpcode = 0;
2378 unsigned LastBytes = 0;
2379 unsigned NumMove = 0;
2380 for (MachineInstr *Op : llvm::reverse(Ops)) {
2381 // Make sure each operation has the same kind.
2382 unsigned LSMOpcode
2383 = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2384 if (LastOpcode && LSMOpcode != LastOpcode)
2385 break;
2386
2387 // Check that we have a continuous set of offsets.
2388 int Offset = getMemoryOpOffset(*Op);
2389 unsigned Bytes = getLSMultipleTransferSize(Op);
2390 if (LastBytes) {
2391 if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2392 break;
2393 }
2394
2395 // Don't try to reschedule too many instructions.
2396 if (NumMove == STI->getCLOpts().prera_ldst_opt_reorder_limit)
2397 break;
2398
2399 // Found a mergeable instruction; save information about it.
2400 ++NumMove;
2401 LastOffset = Offset;
2402 LastBytes = Bytes;
2403 LastOpcode = LSMOpcode;
2404
2405 unsigned Loc = MI2LocMap[Op];
2406 if (Loc <= FirstLoc) {
2407 FirstLoc = Loc;
2408 FirstOp = Op;
2409 }
2410 if (Loc >= LastLoc) {
2411 LastLoc = Loc;
2412 LastOp = Op;
2413 }
2414 }
2415
2416 if (NumMove <= 1)
2417 Ops.pop_back();
2418 else {
2419 SmallPtrSet<MachineInstr*, 4> MemOps;
2420 SmallSet<unsigned, 4> MemRegs;
2421 for (size_t i = Ops.size() - NumMove, e = Ops.size(); i != e; ++i) {
2422 MemOps.insert(Ops[i]);
2423 MemRegs.insert(Ops[i]->getOperand(0).getReg());
2424 }
2425
2426 // Be conservative, if the instructions are too far apart, don't
2427 // move them. We want to limit the increase of register pressure.
2428 bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
2429 if (DoMove)
2430 DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2431 MemOps, MemRegs, TRI, AA);
2432 if (!DoMove) {
2433 for (unsigned i = 0; i != NumMove; ++i)
2434 Ops.pop_back();
2435 } else {
2436 // This is the new location for the loads / stores.
2437 MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
2438 while (InsertPos != MBB->end() &&
2439 (MemOps.count(&*InsertPos) || InsertPos->isDebugInstr()))
2440 ++InsertPos;
2441
2442 // If we are moving a pair of loads / stores, see if it makes sense
2443 // to try to allocate a pair of registers that can form register pairs.
2444 MachineInstr *Op0 = Ops.back();
2445 MachineInstr *Op1 = Ops[Ops.size()-2];
2446 Register FirstReg, SecondReg;
2447 Register BaseReg, PredReg;
2449 bool isT2 = false;
2450 unsigned NewOpc = 0;
2451 int Offset = 0;
2452 DebugLoc dl;
2453 if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
2454 FirstReg, SecondReg, BaseReg,
2455 Offset, PredReg, Pred, isT2)) {
2456 Ops.pop_back();
2457 Ops.pop_back();
2458
2459 const MCInstrDesc &MCID = TII->get(NewOpc);
2460 const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0);
2461 MRI->constrainRegClass(FirstReg, TRC);
2462 MRI->constrainRegClass(SecondReg, TRC);
2463
2464 // Form the pair instruction.
2465 if (isLd) {
2466 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2467 .addReg(FirstReg, RegState::Define)
2468 .addReg(SecondReg, RegState::Define)
2469 .addReg(BaseReg);
2470 // FIXME: We're converting from LDRi12 to an insn that still
2471 // uses addrmode2, so we need an explicit offset reg. It should
2472 // always by reg0 since we're transforming LDRi12s.
2473 if (!isT2)
2474 MIB.addReg(0);
2475 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2476 MIB.cloneMergedMemRefs({Op0, Op1});
2477 LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");
2478 ++NumLDRDFormed;
2479 } else {
2480 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2481 .addReg(FirstReg)
2482 .addReg(SecondReg)
2483 .addReg(BaseReg);
2484 // FIXME: We're converting from LDRi12 to an insn that still
2485 // uses addrmode2, so we need an explicit offset reg. It should
2486 // always by reg0 since we're transforming STRi12s.
2487 if (!isT2)
2488 MIB.addReg(0);
2489 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2490 MIB.cloneMergedMemRefs({Op0, Op1});
2491 LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");
2492 ++NumSTRDFormed;
2493 }
2494 MBB->erase(Op0);
2495 MBB->erase(Op1);
2496
2497 if (!isT2) {
2498 // Add register allocation hints to form register pairs.
2499 MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2500 MRI->setRegAllocationHint(SecondReg, ARMRI::RegPairOdd, FirstReg);
2501 }
2502 } else {
2503 for (unsigned i = 0; i != NumMove; ++i) {
2504 MachineInstr *Op = Ops.pop_back_val();
2505 if (isLd) {
2506 // Populate RegisterMap with all Registers defined by loads.
2507 Register Reg = Op->getOperand(0).getReg();
2508 RegisterMap[Reg];
2509 }
2510
2511 MBB->splice(InsertPos, MBB, Op);
2512 }
2513 }
2514
2515 NumLdStMoved += NumMove;
2516 RetVal = true;
2517 }
2518 }
2519 }
2520
2521 return RetVal;
2522}
2523
2525 std::function<void(MachineOperand &)> Fn) {
2526 if (MI->isNonListDebugValue()) {
2527 auto &Op = MI->getOperand(0);
2528 if (Op.isReg())
2529 Fn(Op);
2530 } else {
2531 for (unsigned I = 2; I < MI->getNumOperands(); I++) {
2532 auto &Op = MI->getOperand(I);
2533 if (Op.isReg())
2534 Fn(Op);
2535 }
2536 }
2537}
2538
2539// Update the RegisterMap with the instruction that was moved because a
2540// DBG_VALUE_LIST may need to be moved again.
2543 MachineInstr *DbgValueListInstr, MachineInstr *InstrToReplace) {
2544
2545 forEachDbgRegOperand(DbgValueListInstr, [&](MachineOperand &Op) {
2546 auto RegIt = RegisterMap.find(Op.getReg());
2547 if (RegIt == RegisterMap.end())
2548 return;
2549 auto &InstrVec = RegIt->getSecond();
2550 llvm::replace(InstrVec, InstrToReplace, DbgValueListInstr);
2551 });
2552}
2553
2555 auto DbgVar = DebugVariable(MI->getDebugVariable(), MI->getDebugExpression(),
2556 MI->getDebugLoc()->getInlinedAt());
2557 return DbgVar;
2558}
2559
2560bool
2561ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2562 bool RetVal = false;
2563
2564 DenseMap<MachineInstr *, unsigned> MI2LocMap;
2565 using Base2InstMap = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>;
2566 using BaseVec = SmallVector<unsigned, 4>;
2567 Base2InstMap Base2LdsMap;
2568 Base2InstMap Base2StsMap;
2569 BaseVec LdBases;
2570 BaseVec StBases;
2571 // This map is used to track the relationship between the virtual
2572 // register that is the result of a load that is moved and the DBG_VALUE
2573 // MachineInstr pointer that uses that virtual register.
2574 SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> RegisterMap;
2575
2576 unsigned Loc = 0;
2579 while (MBBI != E) {
2580 for (; MBBI != E; ++MBBI) {
2581 MachineInstr &MI = *MBBI;
2582 if (MI.isCall() || MI.isTerminator()) {
2583 // Stop at barriers.
2584 ++MBBI;
2585 break;
2586 }
2587
2588 if (!MI.isDebugInstr())
2589 MI2LocMap[&MI] = ++Loc;
2590
2591 if (!isMemoryOp(MI))
2592 continue;
2593 Register PredReg;
2594 if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
2595 continue;
2596
2597 int Opc = MI.getOpcode();
2598 bool isLd = isLoadSingle(Opc);
2599 Register Base = MI.getOperand(1).getReg();
2601 bool StopHere = false;
2602 auto FindBases = [&](Base2InstMap &Base2Ops, BaseVec &Bases) {
2603 auto [BI, Inserted] = Base2Ops.try_emplace(Base);
2604 if (Inserted) {
2605 BI->second.push_back(&MI);
2606 Bases.push_back(Base);
2607 return;
2608 }
2609 for (const MachineInstr *MI : BI->second) {
2610 if (Offset == getMemoryOpOffset(*MI)) {
2611 StopHere = true;
2612 break;
2613 }
2614 }
2615 if (!StopHere)
2616 BI->second.push_back(&MI);
2617 };
2618
2619 if (isLd)
2620 FindBases(Base2LdsMap, LdBases);
2621 else
2622 FindBases(Base2StsMap, StBases);
2623
2624 if (StopHere) {
2625 // Found a duplicate (a base+offset combination that's seen earlier).
2626 // Backtrack.
2627 --Loc;
2628 break;
2629 }
2630 }
2631
2632 // Re-schedule loads.
2633 for (unsigned Base : LdBases) {
2634 SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
2635 if (Lds.size() > 1)
2636 RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap, RegisterMap);
2637 }
2638
2639 // Re-schedule stores.
2640 for (unsigned Base : StBases) {
2641 SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
2642 if (Sts.size() > 1)
2643 RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap, RegisterMap);
2644 }
2645
2646 if (MBBI != E) {
2647 Base2LdsMap.clear();
2648 Base2StsMap.clear();
2649 LdBases.clear();
2650 StBases.clear();
2651 }
2652 }
2653
2654 // Reschedule DBG_VALUEs to match any loads that were moved. When a load is
2655 // sunk beyond a DBG_VALUE that is referring to it, the DBG_VALUE becomes a
2656 // use-before-def, resulting in a loss of debug info.
2657
2658 // Example:
2659 // Before the Pre Register Allocation Load Store Pass
2660 // inst_a
2661 // %2 = ld ...
2662 // inst_b
2663 // DBG_VALUE %2, "x", ...
2664 // %3 = ld ...
2665
2666 // After the Pass:
2667 // inst_a
2668 // inst_b
2669 // DBG_VALUE %2, "x", ...
2670 // %2 = ld ...
2671 // %3 = ld ...
2672
2673 // The code below addresses this by moving the DBG_VALUE to the position
2674 // immediately after the load.
2675
2676 // Example:
2677 // After the code below:
2678 // inst_a
2679 // inst_b
2680 // %2 = ld ...
2681 // DBG_VALUE %2, "x", ...
2682 // %3 = ld ...
2683
2684 // The algorithm works in two phases: First RescheduleOps() populates the
2685 // RegisterMap with registers that were moved as keys, there is no value
2686 // inserted. In the next phase, every MachineInstr in a basic block is
2687 // iterated over. If it is a valid DBG_VALUE or DBG_VALUE_LIST and it uses one
2688 // or more registers in the RegisterMap, the RegisterMap and InstrMap are
2689 // populated with the MachineInstr. If the DBG_VALUE or DBG_VALUE_LIST
2690 // describes debug information for a variable that already exists in the
2691 // DbgValueSinkCandidates, the MachineInstr in the DbgValueSinkCandidates must
2692 // be set to undef. If the current MachineInstr is a load that was moved,
2693 // undef the corresponding DBG_VALUE or DBG_VALUE_LIST and clone it to below
2694 // the load.
2695
2696 // To illustrate the above algorithm visually let's take this example.
2697
2698 // Before the Pre Register Allocation Load Store Pass:
2699 // %2 = ld ...
2700 // DBG_VALUE %2, A, .... # X
2701 // DBG_VALUE 0, A, ... # Y
2702 // %3 = ld ...
2703 // DBG_VALUE %3, A, ..., # Z
2704 // %4 = ld ...
2705
2706 // After Pre Register Allocation Load Store Pass:
2707 // DBG_VALUE %2, A, .... # X
2708 // DBG_VALUE 0, A, ... # Y
2709 // DBG_VALUE %3, A, ..., # Z
2710 // %2 = ld ...
2711 // %3 = ld ...
2712 // %4 = ld ...
2713
2714 // The algorithm below does the following:
2715
2716 // In the beginning, the RegisterMap will have been populated with the virtual
2717 // registers %2, and %3, the DbgValueSinkCandidates and the InstrMap will be
2718 // empty. DbgValueSinkCandidates = {}, RegisterMap = {2 -> {}, 3 -> {}},
2719 // InstrMap {}
2720 // -> DBG_VALUE %2, A, .... # X
2721 // DBG_VALUE 0, A, ... # Y
2722 // DBG_VALUE %3, A, ..., # Z
2723 // %2 = ld ...
2724 // %3 = ld ...
2725 // %4 = ld ...
2726
2727 // After the first DBG_VALUE (denoted with an X) is processed, the
2728 // DbgValueSinkCandidates and InstrMap will be populated and the RegisterMap
2729 // entry for %2 will be populated as well. DbgValueSinkCandidates = {A -> X},
2730 // RegisterMap = {2 -> {X}, 3 -> {}}, InstrMap {X -> 2}
2731 // DBG_VALUE %2, A, .... # X
2732 // -> DBG_VALUE 0, A, ... # Y
2733 // DBG_VALUE %3, A, ..., # Z
2734 // %2 = ld ...
2735 // %3 = ld ...
2736 // %4 = ld ...
2737
2738 // After the DBG_VALUE Y is processed, the DbgValueSinkCandidates is updated
2739 // to now hold Y for A and the RegisterMap is also updated to remove X from
2740 // %2, this is because both X and Y describe the same debug variable A. X is
2741 // also updated to have a $noreg as the first operand.
2742 // DbgValueSinkCandidates = {A -> {Y}}, RegisterMap = {2 -> {}, 3 -> {}},
2743 // InstrMap = {X-> 2}
2744 // DBG_VALUE $noreg, A, .... # X
2745 // DBG_VALUE 0, A, ... # Y
2746 // -> DBG_VALUE %3, A, ..., # Z
2747 // %2 = ld ...
2748 // %3 = ld ...
2749 // %4 = ld ...
2750
2751 // After DBG_VALUE Z is processed, the DbgValueSinkCandidates is updated to
2752 // hold Z fr A, the RegisterMap is updated to hold Z for %3, and the InstrMap
2753 // is updated to have Z mapped to %3. This is again because Z describes the
2754 // debug variable A, Y is not updated to have $noreg as first operand because
2755 // its first operand is an immediate, not a register.
2756 // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
2757 // InstrMap = {X -> 2, Z -> 3}
2758 // DBG_VALUE $noreg, A, .... # X
2759 // DBG_VALUE 0, A, ... # Y
2760 // DBG_VALUE %3, A, ..., # Z
2761 // -> %2 = ld ...
2762 // %3 = ld ...
2763 // %4 = ld ...
2764
2765 // Nothing happens here since the RegisterMap for %2 contains no value.
2766 // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
2767 // InstrMap = {X -> 2, Z -> 3}
2768 // DBG_VALUE $noreg, A, .... # X
2769 // DBG_VALUE 0, A, ... # Y
2770 // DBG_VALUE %3, A, ..., # Z
2771 // %2 = ld ...
2772 // -> %3 = ld ...
2773 // %4 = ld ...
2774
2775 // Since the RegisterMap contains Z as a value for %3, the MachineInstr
2776 // pointer Z is copied to come after the load for %3 and the old Z's first
2777 // operand is changed to $noreg the Basic Block iterator is moved to after the
2778 // DBG_VALUE Z's new position.
2779 // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
2780 // InstrMap = {X -> 2, Z -> 3}
2781 // DBG_VALUE $noreg, A, .... # X
2782 // DBG_VALUE 0, A, ... # Y
2783 // DBG_VALUE $noreg, A, ..., # Old Z
2784 // %2 = ld ...
2785 // %3 = ld ...
2786 // DBG_VALUE %3, A, ..., # Z
2787 // -> %4 = ld ...
2788
2789 // Nothing happens for %4 and the algorithm exits having processed the entire
2790 // Basic Block.
2791 // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
2792 // InstrMap = {X -> 2, Z -> 3}
2793 // DBG_VALUE $noreg, A, .... # X
2794 // DBG_VALUE 0, A, ... # Y
2795 // DBG_VALUE $noreg, A, ..., # Old Z
2796 // %2 = ld ...
2797 // %3 = ld ...
2798 // DBG_VALUE %3, A, ..., # Z
2799 // %4 = ld ...
2800
2801 // This map is used to track the relationship between
2802 // a Debug Variable and the DBG_VALUE MachineInstr pointer that describes the
2803 // debug information for that Debug Variable.
2804 SmallDenseMap<DebugVariable, MachineInstr *, 8> DbgValueSinkCandidates;
2805 // This map is used to track the relationship between a DBG_VALUE or
2806 // DBG_VALUE_LIST MachineInstr pointer and Registers that it uses.
2807 SmallDenseMap<MachineInstr *, SmallVector<Register>, 8> InstrMap;
2808 for (MBBI = MBB->begin(), E = MBB->end(); MBBI != E; ++MBBI) {
2809 MachineInstr &MI = *MBBI;
2810
2811 auto PopulateRegisterAndInstrMapForDebugInstr = [&](Register Reg) {
2812 auto RegIt = RegisterMap.find(Reg);
2813 if (RegIt == RegisterMap.end())
2814 return;
2815 auto &InstrVec = RegIt->getSecond();
2816 InstrVec.push_back(&MI);
2817 InstrMap[&MI].push_back(Reg);
2818 };
2819
2820 if (MI.isDebugValue()) {
2821 assert(MI.getDebugVariable() &&
2822 "DBG_VALUE or DBG_VALUE_LIST must contain a DILocalVariable");
2823
2825 // If the first operand is a register and it exists in the RegisterMap, we
2826 // know this is a DBG_VALUE that uses the result of a load that was moved,
2827 // and is therefore a candidate to also be moved, add it to the
2828 // RegisterMap and InstrMap.
2829 forEachDbgRegOperand(&MI, [&](MachineOperand &Op) {
2830 PopulateRegisterAndInstrMapForDebugInstr(Op.getReg());
2831 });
2832
2833 // If the current DBG_VALUE describes the same variable as one of the
2834 // in-flight DBG_VALUEs, remove the candidate from the list and set it to
2835 // undef. Moving one DBG_VALUE past another would result in the variable's
2836 // value going back in time when stepping through the block in the
2837 // debugger.
2838 auto InstrIt = DbgValueSinkCandidates.find(DbgVar);
2839 if (InstrIt != DbgValueSinkCandidates.end()) {
2840 auto *Instr = InstrIt->getSecond();
2841 auto RegIt = InstrMap.find(Instr);
2842 if (RegIt != InstrMap.end()) {
2843 const auto &RegVec = RegIt->getSecond();
2844 // For every Register in the RegVec, remove the MachineInstr in the
2845 // RegisterMap that describes the DbgVar.
2846 for (auto &Reg : RegVec) {
2847 auto RegIt = RegisterMap.find(Reg);
2848 if (RegIt == RegisterMap.end())
2849 continue;
2850 auto &InstrVec = RegIt->getSecond();
2851 auto IsDbgVar = [&](MachineInstr *I) -> bool {
2853 return Var == DbgVar;
2854 };
2855
2856 llvm::erase_if(InstrVec, IsDbgVar);
2857 }
2859 [&](MachineOperand &Op) { Op.setReg(0); });
2860 }
2861 }
2862 DbgValueSinkCandidates[DbgVar] = &MI;
2863 } else {
2864 // If the first operand of a load matches with a DBG_VALUE in RegisterMap,
2865 // then move that DBG_VALUE to below the load.
2866 auto Opc = MI.getOpcode();
2867 if (!isLoadSingle(Opc))
2868 continue;
2869 auto Reg = MI.getOperand(0).getReg();
2870 auto RegIt = RegisterMap.find(Reg);
2871 if (RegIt == RegisterMap.end())
2872 continue;
2873 auto &DbgInstrVec = RegIt->getSecond();
2874 if (!DbgInstrVec.size())
2875 continue;
2876 for (auto *DbgInstr : DbgInstrVec) {
2877 MachineBasicBlock::iterator InsertPos = std::next(MBBI);
2878 auto *ClonedMI = MI.getMF()->CloneMachineInstr(DbgInstr);
2879 MBB->insert(InsertPos, ClonedMI);
2880 MBBI++;
2881 // Erase the entry into the DbgValueSinkCandidates for the DBG_VALUE
2882 // that was moved.
2883 auto DbgVar = createDebugVariableFromMachineInstr(DbgInstr);
2884 // Erase DbgVar from DbgValueSinkCandidates if still present. If the
2885 // instruction is a DBG_VALUE_LIST, it may have already been erased from
2886 // DbgValueSinkCandidates.
2887 DbgValueSinkCandidates.erase(DbgVar);
2888 // Zero out original dbg instr
2889 forEachDbgRegOperand(DbgInstr,
2890 [&](MachineOperand &Op) { Op.setReg(0); });
2891 // Update RegisterMap with ClonedMI because it might have to be moved
2892 // again.
2893 if (DbgInstr->isDebugValueList())
2894 updateRegisterMapForDbgValueListAfterMove(RegisterMap, ClonedMI,
2895 DbgInstr);
2896 }
2897 }
2898 }
2899 return RetVal;
2900}
2901
2902// Get the Base register operand index from the memory access MachineInst if we
2903// should attempt to distribute postinc on it. Return -1 if not of a valid
2904// instruction type. If it returns an index, it is assumed that instruction is a
2905// r+i indexing mode, and getBaseOperandIndex() + 1 is the Offset index.
2907 switch (MI.getOpcode()) {
2908 case ARM::MVE_VLDRBS16:
2909 case ARM::MVE_VLDRBS32:
2910 case ARM::MVE_VLDRBU16:
2911 case ARM::MVE_VLDRBU32:
2912 case ARM::MVE_VLDRHS32:
2913 case ARM::MVE_VLDRHU32:
2914 case ARM::MVE_VLDRBU8:
2915 case ARM::MVE_VLDRHU16:
2916 case ARM::MVE_VLDRWU32:
2917 case ARM::MVE_VSTRB16:
2918 case ARM::MVE_VSTRB32:
2919 case ARM::MVE_VSTRH32:
2920 case ARM::MVE_VSTRBU8:
2921 case ARM::MVE_VSTRHU16:
2922 case ARM::MVE_VSTRWU32:
2923 case ARM::t2LDRHi8:
2924 case ARM::t2LDRHi12:
2925 case ARM::t2LDRSHi8:
2926 case ARM::t2LDRSHi12:
2927 case ARM::t2LDRBi8:
2928 case ARM::t2LDRBi12:
2929 case ARM::t2LDRSBi8:
2930 case ARM::t2LDRSBi12:
2931 case ARM::t2STRBi8:
2932 case ARM::t2STRBi12:
2933 case ARM::t2STRHi8:
2934 case ARM::t2STRHi12:
2935 return 1;
2936 case ARM::MVE_VLDRBS16_post:
2937 case ARM::MVE_VLDRBS32_post:
2938 case ARM::MVE_VLDRBU16_post:
2939 case ARM::MVE_VLDRBU32_post:
2940 case ARM::MVE_VLDRHS32_post:
2941 case ARM::MVE_VLDRHU32_post:
2942 case ARM::MVE_VLDRBU8_post:
2943 case ARM::MVE_VLDRHU16_post:
2944 case ARM::MVE_VLDRWU32_post:
2945 case ARM::MVE_VSTRB16_post:
2946 case ARM::MVE_VSTRB32_post:
2947 case ARM::MVE_VSTRH32_post:
2948 case ARM::MVE_VSTRBU8_post:
2949 case ARM::MVE_VSTRHU16_post:
2950 case ARM::MVE_VSTRWU32_post:
2951 case ARM::MVE_VLDRBS16_pre:
2952 case ARM::MVE_VLDRBS32_pre:
2953 case ARM::MVE_VLDRBU16_pre:
2954 case ARM::MVE_VLDRBU32_pre:
2955 case ARM::MVE_VLDRHS32_pre:
2956 case ARM::MVE_VLDRHU32_pre:
2957 case ARM::MVE_VLDRBU8_pre:
2958 case ARM::MVE_VLDRHU16_pre:
2959 case ARM::MVE_VLDRWU32_pre:
2960 case ARM::MVE_VSTRB16_pre:
2961 case ARM::MVE_VSTRB32_pre:
2962 case ARM::MVE_VSTRH32_pre:
2963 case ARM::MVE_VSTRBU8_pre:
2964 case ARM::MVE_VSTRHU16_pre:
2965 case ARM::MVE_VSTRWU32_pre:
2966 return 2;
2967 }
2968 return -1;
2969}
2970
2972 switch (MI.getOpcode()) {
2973 case ARM::MVE_VLDRBS16_post:
2974 case ARM::MVE_VLDRBS32_post:
2975 case ARM::MVE_VLDRBU16_post:
2976 case ARM::MVE_VLDRBU32_post:
2977 case ARM::MVE_VLDRHS32_post:
2978 case ARM::MVE_VLDRHU32_post:
2979 case ARM::MVE_VLDRBU8_post:
2980 case ARM::MVE_VLDRHU16_post:
2981 case ARM::MVE_VLDRWU32_post:
2982 case ARM::MVE_VSTRB16_post:
2983 case ARM::MVE_VSTRB32_post:
2984 case ARM::MVE_VSTRH32_post:
2985 case ARM::MVE_VSTRBU8_post:
2986 case ARM::MVE_VSTRHU16_post:
2987 case ARM::MVE_VSTRWU32_post:
2988 return true;
2989 }
2990 return false;
2991}
2992
2994 switch (MI.getOpcode()) {
2995 case ARM::MVE_VLDRBS16_pre:
2996 case ARM::MVE_VLDRBS32_pre:
2997 case ARM::MVE_VLDRBU16_pre:
2998 case ARM::MVE_VLDRBU32_pre:
2999 case ARM::MVE_VLDRHS32_pre:
3000 case ARM::MVE_VLDRHU32_pre:
3001 case ARM::MVE_VLDRBU8_pre:
3002 case ARM::MVE_VLDRHU16_pre:
3003 case ARM::MVE_VLDRWU32_pre:
3004 case ARM::MVE_VSTRB16_pre:
3005 case ARM::MVE_VSTRB32_pre:
3006 case ARM::MVE_VSTRH32_pre:
3007 case ARM::MVE_VSTRBU8_pre:
3008 case ARM::MVE_VSTRHU16_pre:
3009 case ARM::MVE_VSTRWU32_pre:
3010 return true;
3011 }
3012 return false;
3013}
3014
3015// Given a memory access Opcode, check that the give Imm would be a valid Offset
3016// for this instruction (same as isLegalAddressImm), Or if the instruction
3017// could be easily converted to one where that was valid. For example converting
3018// t2LDRi12 to t2LDRi8 for negative offsets. Works in conjunction with
3019// AdjustBaseAndOffset below.
3020static bool isLegalOrConvertibleAddressImm(unsigned Opcode, int Imm,
3021 const TargetInstrInfo *TII,
3022 int &CodesizeEstimate) {
3023 if (isLegalAddressImm(Opcode, Imm, TII))
3024 return true;
3025
3026 // We can convert AddrModeT2_i12 to AddrModeT2_i8neg.
3027 const MCInstrDesc &Desc = TII->get(Opcode);
3028 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
3029 switch (AddrMode) {
3031 CodesizeEstimate += 1;
3032 return Imm < 0 && -Imm < ((1 << 8) * 1);
3033 }
3034 return false;
3035}
3036
3037// Given an MI adjust its address BaseReg to use NewBaseReg and address offset
3038// by -Offset. This can either happen in-place or be a replacement as MI is
3039// converted to another instruction type.
3041 int Offset, const TargetInstrInfo *TII,
3042 const TargetRegisterInfo *TRI) {
3043 // Set the Base reg
3044 unsigned BaseOp = getBaseOperandIndex(*MI);
3045 MI->getOperand(BaseOp).setReg(NewBaseReg);
3046 // and constrain the reg class to that required by the instruction.
3047 MachineFunction *MF = MI->getMF();
3049 const MCInstrDesc &MCID = TII->get(MI->getOpcode());
3050 const TargetRegisterClass *TRC = TII->getRegClass(MCID, BaseOp);
3051 MRI.constrainRegClass(NewBaseReg, TRC);
3052
3053 int OldOffset = MI->getOperand(BaseOp + 1).getImm();
3054 if (isLegalAddressImm(MI->getOpcode(), OldOffset - Offset, TII))
3055 MI->getOperand(BaseOp + 1).setImm(OldOffset - Offset);
3056 else {
3057 unsigned ConvOpcode;
3058 switch (MI->getOpcode()) {
3059 case ARM::t2LDRHi12:
3060 ConvOpcode = ARM::t2LDRHi8;
3061 break;
3062 case ARM::t2LDRSHi12:
3063 ConvOpcode = ARM::t2LDRSHi8;
3064 break;
3065 case ARM::t2LDRBi12:
3066 ConvOpcode = ARM::t2LDRBi8;
3067 break;
3068 case ARM::t2LDRSBi12:
3069 ConvOpcode = ARM::t2LDRSBi8;
3070 break;
3071 case ARM::t2STRHi12:
3072 ConvOpcode = ARM::t2STRHi8;
3073 break;
3074 case ARM::t2STRBi12:
3075 ConvOpcode = ARM::t2STRBi8;
3076 break;
3077 default:
3078 llvm_unreachable("Unhandled convertible opcode");
3079 }
3080 assert(isLegalAddressImm(ConvOpcode, OldOffset - Offset, TII) &&
3081 "Illegal Address Immediate after convert!");
3082
3083 const MCInstrDesc &MCID = TII->get(ConvOpcode);
3084 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3085 .add(MI->getOperand(0))
3086 .add(MI->getOperand(1))
3087 .addImm(OldOffset - Offset)
3088 .add(MI->getOperand(3))
3089 .add(MI->getOperand(4))
3090 .cloneMemRefs(*MI);
3091 MI->eraseFromParent();
3092 }
3093}
3094
3096 Register NewReg,
3097 const TargetInstrInfo *TII,
3098 const TargetRegisterInfo *TRI) {
3099 MachineFunction *MF = MI->getMF();
3101
3102 unsigned NewOpcode = getPostIndexedLoadStoreOpcode(
3103 MI->getOpcode(), Offset > 0 ? ARM_AM::add : ARM_AM::sub);
3104
3105 const MCInstrDesc &MCID = TII->get(NewOpcode);
3106 // Constrain the def register class
3107 const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0);
3108 MRI.constrainRegClass(NewReg, TRC);
3109 // And do the same for the base operand
3110 TRC = TII->getRegClass(MCID, 2);
3111 MRI.constrainRegClass(MI->getOperand(1).getReg(), TRC);
3112
3113 unsigned AddrMode = (MCID.TSFlags & ARMII::AddrModeMask);
3114 switch (AddrMode) {
3118 // Any MVE load/store
3119 return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3120 .addReg(NewReg, RegState::Define)
3121 .add(MI->getOperand(0))
3122 .add(MI->getOperand(1))
3123 .addImm(Offset)
3124 .add(MI->getOperand(3))
3125 .add(MI->getOperand(4))
3126 .add(MI->getOperand(5))
3127 .cloneMemRefs(*MI);
3129 if (MI->mayLoad()) {
3130 return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3131 .add(MI->getOperand(0))
3132 .addReg(NewReg, RegState::Define)
3133 .add(MI->getOperand(1))
3134 .addImm(Offset)
3135 .add(MI->getOperand(3))
3136 .add(MI->getOperand(4))
3137 .cloneMemRefs(*MI);
3138 } else {
3139 return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3140 .addReg(NewReg, RegState::Define)
3141 .add(MI->getOperand(0))
3142 .add(MI->getOperand(1))
3143 .addImm(Offset)
3144 .add(MI->getOperand(3))
3145 .add(MI->getOperand(4))
3146 .cloneMemRefs(*MI);
3147 }
3148 default:
3149 llvm_unreachable("Unhandled createPostIncLoadStore");
3150 }
3151}
3152
3153// Given a Base Register, optimise the load/store uses to attempt to create more
3154// post-inc accesses and less register moves. We do this by taking zero offset
3155// loads/stores with an add, and convert them to a postinc load/store of the
3156// same type. Any subsequent accesses will be adjusted to use and account for
3157// the post-inc value.
3158// For example:
3159// LDR #0 LDR_POSTINC #16
3160// LDR #4 LDR #-12
3161// LDR #8 LDR #-8
3162// LDR #12 LDR #-4
3163// ADD #16
3164//
3165// At the same time if we do not find an increment but do find an existing
3166// pre/post inc instruction, we can still adjust the offsets of subsequent
3167// instructions to save the register move that would otherwise be needed for the
3168// in-place increment.
3169bool ARMPreAllocLoadStoreOpt::DistributeIncrements(Register Base) {
3170 // We are looking for:
3171 // One zero offset load/store that can become postinc
3172 MachineInstr *BaseAccess = nullptr;
3173 MachineInstr *PrePostInc = nullptr;
3174 // An increment that can be folded in
3175 MachineInstr *Increment = nullptr;
3176 // Other accesses after BaseAccess that will need to be updated to use the
3177 // postinc value.
3178 SmallPtrSet<MachineInstr *, 8> OtherAccesses;
3179 for (auto &Use : MRI->use_nodbg_instructions(Base)) {
3180 if (!Increment && getAddSubImmediate(Use) != 0) {
3181 Increment = &Use;
3182 continue;
3183 }
3184
3185 int BaseOp = getBaseOperandIndex(Use);
3186 if (BaseOp == -1)
3187 return false;
3188
3189 if (!Use.getOperand(BaseOp).isReg() ||
3190 Use.getOperand(BaseOp).getReg() != Base)
3191 return false;
3192 if (isPreIndex(Use) || isPostIndex(Use))
3193 PrePostInc = &Use;
3194 else if (Use.getOperand(BaseOp + 1).getImm() == 0)
3195 BaseAccess = &Use;
3196 else
3197 OtherAccesses.insert(&Use);
3198 }
3199
3200 int IncrementOffset;
3201 Register NewBaseReg;
3202 if (BaseAccess && Increment) {
3203 if (PrePostInc || BaseAccess->getParent() != Increment->getParent())
3204 return false;
3205 Register PredReg;
3206 if (Increment->definesRegister(ARM::CPSR, /*TRI=*/nullptr) ||
3208 return false;
3209
3210 LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on VirtualReg "
3211 << Base.virtRegIndex() << "\n");
3212
3213 // Make sure that Increment has no uses before BaseAccess that are not PHI
3214 // uses.
3215 for (MachineInstr &Use :
3216 MRI->use_nodbg_instructions(Increment->getOperand(0).getReg())) {
3217 if (&Use == BaseAccess || (Use.getOpcode() != TargetOpcode::PHI &&
3218 !DT->dominates(BaseAccess, &Use))) {
3219 LLVM_DEBUG(dbgs() << " BaseAccess doesn't dominate use of increment\n");
3220 return false;
3221 }
3222 }
3223
3224 // Make sure that Increment can be folded into Base
3225 IncrementOffset = getAddSubImmediate(*Increment);
3226 unsigned NewPostIncOpcode = getPostIndexedLoadStoreOpcode(
3227 BaseAccess->getOpcode(), IncrementOffset > 0 ? ARM_AM::add : ARM_AM::sub);
3228 if (!isLegalAddressImm(NewPostIncOpcode, IncrementOffset, TII)) {
3229 LLVM_DEBUG(dbgs() << " Illegal addressing mode immediate on postinc\n");
3230 return false;
3231 }
3232 }
3233 else if (PrePostInc) {
3234 // If we already have a pre/post index load/store then set BaseAccess,
3235 // IncrementOffset and NewBaseReg to the values it already produces,
3236 // allowing us to update and subsequent uses of BaseOp reg with the
3237 // incremented value.
3238 if (Increment)
3239 return false;
3240
3241 LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on already "
3242 << "indexed VirtualReg " << Base.virtRegIndex() << "\n");
3243 int BaseOp = getBaseOperandIndex(*PrePostInc);
3244 IncrementOffset = PrePostInc->getOperand(BaseOp+1).getImm();
3245 BaseAccess = PrePostInc;
3246 NewBaseReg = PrePostInc->getOperand(0).getReg();
3247 }
3248 else
3249 return false;
3250
3251 // And make sure that the negative value of increment can be added to all
3252 // other offsets after the BaseAccess. We rely on either
3253 // dominates(BaseAccess, OtherAccess) or dominates(OtherAccess, BaseAccess)
3254 // to keep things simple.
3255 // This also adds a simple codesize metric, to detect if an instruction (like
3256 // t2LDRBi12) which can often be shrunk to a thumb1 instruction (tLDRBi)
3257 // cannot because it is converted to something else (t2LDRBi8). We start this
3258 // at -1 for the gain from removing the increment.
3259 SmallPtrSet<MachineInstr *, 4> SuccessorAccesses;
3260 int CodesizeEstimate = -1;
3261 for (auto *Use : OtherAccesses) {
3262 if (DT->dominates(BaseAccess, Use)) {
3263 SuccessorAccesses.insert(Use);
3264 unsigned BaseOp = getBaseOperandIndex(*Use);
3265 if (!isLegalOrConvertibleAddressImm(Use->getOpcode(),
3266 Use->getOperand(BaseOp + 1).getImm() -
3267 IncrementOffset,
3268 TII, CodesizeEstimate)) {
3269 LLVM_DEBUG(dbgs() << " Illegal addressing mode immediate on use\n");
3270 return false;
3271 }
3272 } else if (!DT->dominates(Use, BaseAccess)) {
3273 LLVM_DEBUG(
3274 dbgs() << " Unknown dominance relation between Base and Use\n");
3275 return false;
3276 }
3277 }
3278 if (STI->hasMinSize() && CodesizeEstimate > 0) {
3279 LLVM_DEBUG(dbgs() << " Expected to grow instructions under minsize\n");
3280 return false;
3281 }
3282
3283 if (!PrePostInc) {
3284 // Replace BaseAccess with a post inc
3285 LLVM_DEBUG(dbgs() << "Changing: "; BaseAccess->dump());
3286 LLVM_DEBUG(dbgs() << " And : "; Increment->dump());
3287 NewBaseReg = Increment->getOperand(0).getReg();
3288 MachineInstr *BaseAccessPost =
3289 createPostIncLoadStore(BaseAccess, IncrementOffset, NewBaseReg, TII, TRI);
3290 BaseAccess->eraseFromParent();
3291 Increment->eraseFromParent();
3292 (void)BaseAccessPost;
3293 LLVM_DEBUG(dbgs() << " To : "; BaseAccessPost->dump());
3294 }
3295
3296 for (auto *Use : SuccessorAccesses) {
3297 LLVM_DEBUG(dbgs() << "Changing: "; Use->dump());
3298 AdjustBaseAndOffset(Use, NewBaseReg, IncrementOffset, TII, TRI);
3299 LLVM_DEBUG(dbgs() << " To : "; Use->dump());
3300 }
3301
3302 // Remove the kill flag from all uses of NewBaseReg, in case any old uses
3303 // remain.
3304 for (MachineOperand &Op : MRI->use_nodbg_operands(NewBaseReg))
3305 Op.setIsKill(false);
3306 return true;
3307}
3308
3309bool ARMPreAllocLoadStoreOpt::DistributeIncrements() {
3310 bool Changed = false;
3311 SmallSetVector<Register, 4> Visited;
3312 for (auto &MBB : *MF) {
3313 for (auto &MI : MBB) {
3314 int BaseOp = getBaseOperandIndex(MI);
3315 if (BaseOp == -1 || !MI.getOperand(BaseOp).isReg())
3316 continue;
3317
3318 Register Base = MI.getOperand(BaseOp).getReg();
3319 if (!Base.isVirtual())
3320 continue;
3321
3322 Visited.insert(Base);
3323 }
3324 }
3325
3326 for (auto Base : Visited)
3327 Changed |= DistributeIncrements(Base);
3328
3329 return Changed;
3330}
3331
3332/// Returns an instance of the load / store optimization pass.
3334 if (PreAlloc)
3335 return new ARMPreAllocLoadStoreOptLegacy();
3336 return new ARMLoadStoreOptLegacy();
3337}
3338
3342 ARMLoadStoreOpt Impl;
3343 bool Changed = Impl.runOnMachineFunction(
3345 if (!Changed)
3346 return PreservedAnalyses::all();
3350 return PA;
3351}
3352
3356 ARMPreAllocLoadStoreOpt Impl;
3357 AliasAnalysis *AA =
3359 .getManager()
3360 .getResult<AAManager>(MF.getFunction());
3362 bool Changed = Impl.runOnMachineFunction(MF, AA, DT);
3363 if (!Changed)
3364 return PreservedAnalyses::all();
3367 return PA;
3368}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo & TII
uint64_t Imm
static bool isLoadSingle(unsigned Opc)
static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc, ARM_AM::AddrOpc Mode)
static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base, MachineBasicBlock::iterator I, MachineBasicBlock::iterator E, SmallPtrSetImpl< MachineInstr * > &MemOps, SmallSet< unsigned, 4 > &MemRegs, const TargetRegisterInfo *TRI, AliasAnalysis *AA)
static bool ContainsReg(ArrayRef< std::pair< unsigned, bool > > Regs, unsigned Reg)
static bool isPreIndex(MachineInstr &MI)
static void forEachDbgRegOperand(MachineInstr *MI, std::function< void(MachineOperand &)> Fn)
static bool isPostIndex(MachineInstr &MI)
static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode)
static unsigned getLSMultipleTransferSize(const MachineInstr *MI)
static bool isLegalOrConvertibleAddressImm(unsigned Opcode, int Imm, const TargetInstrInfo *TII, int &CodesizeEstimate)
static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode)
static bool isT1i32Load(unsigned Opc)
static bool isMemoryOp(const MachineInstr &MI)
Returns true if instruction is a memory operation that this pass is capable of operating on.
static void AdjustBaseAndOffset(MachineInstr *MI, Register NewBaseReg, int Offset, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
arm ldst static false bool definesCPSR(const MachineInstr &MI)
static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc, ARM_AM::AddrOpc Mode)
static MachineInstr * createPostIncLoadStore(MachineInstr *MI, int Offset, Register NewReg, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool isi32Store(unsigned Opc)
static MachineBasicBlock::iterator findIncDecAfter(MachineBasicBlock::iterator MBBI, Register Reg, ARMCC::CondCodes Pred, Register PredReg, int &Offset, const TargetRegisterInfo *TRI)
Searches for a increment or decrement of Reg after MBBI.
static MachineBasicBlock::iterator findIncDecBefore(MachineBasicBlock::iterator MBBI, Register Reg, ARMCC::CondCodes Pred, Register PredReg, int &Offset)
Searches for an increment or decrement of Reg before MBBI.
static const MachineOperand & getLoadStoreBaseOp(const MachineInstr &MI)
static void updateRegisterMapForDbgValueListAfterMove(SmallDenseMap< Register, SmallVector< MachineInstr * >, 8 > &RegisterMap, MachineInstr *DbgValueListInstr, MachineInstr *InstrToReplace)
static void InsertLDR_STR(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, int Offset, bool isDef, unsigned NewOpc, unsigned Reg, bool RegDeadKill, bool RegUndef, unsigned BaseReg, bool BaseKill, bool BaseUndef, ARMCC::CondCodes Pred, unsigned PredReg, const TargetInstrInfo *TII, MachineInstr *MI)
static int getMemoryOpOffset(const MachineInstr &MI)
static int isIncrementOrDecrement(const MachineInstr &MI, Register Reg, ARMCC::CondCodes Pred, Register PredReg)
Check if the given instruction increments or decrements a register and return the amount it is increm...
static bool isT2i32Store(unsigned Opc)
static bool mayCombineMisaligned(const TargetSubtargetInfo &STI, const MachineInstr &MI)
Return true for loads/stores that can be combined to a double/multi operation without increasing the ...
static int getBaseOperandIndex(MachineInstr &MI)
static bool isT2i32Load(unsigned Opc)
static bool isi32Load(unsigned Opc)
static unsigned getImmScale(unsigned Opc)
static bool isT1i32Store(unsigned Opc)
#define ARM_PREALLOC_LOAD_STORE_OPT_NAME
#define ARM_LOAD_STORE_OPT_NAME
static unsigned getUpdatingLSMultipleOpcode(unsigned Opc, ARM_AM::AMSubMode Mode)
static const MachineOperand & getLoadStoreRegOp(const MachineInstr &MI)
static bool isValidLSDoubleOffset(int Offset)
static DebugVariable createDebugVariableFromMachineInstr(MachineInstr *MI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
A set of register units.
if(!TBB||Cond.size()< 1) return false
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
Basic Register Allocator
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
Value * RHS
Value * LHS
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static void updateLRRestored(MachineFunction &MF)
Update the IsRestored flag on LR if it is spilled, based on the return instructions.
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const ARMBaseInstrInfo * getInstrInfo() const override
bool isThumb2() const
const ARMTargetLowering * getTargetLowering() const override
const ARMBaseRegisterInfo * getRegisterInfo() const override
const ARMOptions & getCLOpts() const
bool hasMinSize() const
bool isCortexM3() const
Align getDualLoadStoreAlignment() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
A debug info location.
Definition DebugLoc.h:126
Identifies a unique instance of a variable.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
A set of register units used to track register liveness.
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
void addReg(MCRegister Reg)
Adds register units covered by physical register Reg.
LLVM_ABI void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
LLVM_ABI void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
Describe properties that are true of each instruction in the target description file.
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
@ LQR_Dead
Register is known to be fully dead.
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineInstrBuilder & cloneMergedMemRefs(ArrayRef< const MachineInstr * > OtherMIs) const
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr kills the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
bool isAtomic() const
Returns true if this operation has an atomic ordering requirement of unordered or higher,...
LLVM_ABI Align getAlign() const
Return the minimum known alignment in bytes of the actual memory reference.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
int64_t getImm() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
void setRegAllocationHint(Register VReg, unsigned Type, Register PrefReg)
setRegAllocationHint - Specify a register allocation hint for the specified virtual register.
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition Allocator.h:398
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Align getTransientStackAlign() const
getTransientStackAlignment - This method returns the number of bytes to which the stack pointer must ...
TargetInstrInfo - Interface to description of machine instruction set.
virtual bool isLegalAddImmediate(int64_t) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetFrameLowering * getFrameLowering() const
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned char getAM3Offset(unsigned AM3Opc)
unsigned getAM2Opc(AddrOpc Opc, unsigned Imm12, ShiftOpc SO, unsigned IdxMode=0)
AddrOpc getAM5Op(unsigned AM5Opc)
unsigned getAM3Opc(AddrOpc Opc, unsigned char Offset, unsigned IdxMode=0)
getAM3Opc - This function encodes the addrmode3 opc field.
unsigned char getAM5Offset(unsigned AM5Opc)
AddrOpc getAM3Op(unsigned AM3Opc)
constexpr MCPhysReg SP
@ ARM
Windows AXP64.
Definition MCAsmInfo.h:50
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
BBIterator iterator
Definition BasicBlock.h:87
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
static bool isARMLowRegister(MCRegister Reg)
isARMLowRegister - Returns true if the register is a low register (r0-r7).
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1769
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool isLegalAddressImm(unsigned Opcode, int Imm, const TargetInstrInfo *TII)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr RegState getDeadRegState(bool B)
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
Op::Description Desc
unsigned M1(unsigned Val)
Definition VE.h:394
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
@ Off
Use window algorithm after SMS algorithm fails.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr RegState getDefRegState(bool B)
FunctionPass * createARMLoadStoreOptLegacyPass(bool PreAlloc=false)
Returns an instance of the load / store optimization pass.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
ARMCC::CondCodes getInstrPredicate(const MachineInstr &MI, Register &PredReg)
getInstrPredicate - If instruction is predicated, returns its predicate condition,...
DWARFExpression::Operation Op
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI void eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1828
static MachineOperand t1CondCodeOp(bool isDead=false)
Get the operand corresponding to the conditional code result for Thumb1.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static MachineOperand condCodeOp(unsigned CCReg=0)
Get the operand corresponding to the conditional code result.
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
int getAddSubImmediate(MachineInstr &MI)
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
constexpr RegState getUndefRegState(bool B)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39