1 //===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Perform peephole optimizations on the machine code:
12 // - Optimize Extensions
14 // Optimization of sign / zero extension instructions. It may be extended to
15 // handle other instructions with similar properties.
17 // On some targets, some instructions, e.g. X86 sign / zero extension, may
18 // leave the source value in the lower part of the result. This optimization
19 // will replace some uses of the pre-extension value with uses of the
20 // sub-register of the results.
22 // - Optimize Comparisons
24 // Optimization of comparison instructions. For instance, in this code:
30 // If the "sub" instruction all ready sets (or could be modified to set) the
31 // same flag that the "cmp" instruction sets and that "bz" uses, then we can
32 // eliminate the "cmp" instruction.
34 // Another instance, in this code:
36 // sub r1, r3 | sub r1, imm
37 // cmp r3, r1 or cmp r1, r3 | cmp r1, imm
40 // If the branch instruction can use flag from "sub", then we can replace
41 // "sub" with "subs" and eliminate the "cmp" instruction.
45 // Loads that can be folded into a later instruction. A load is foldable
46 // if it loads to virtual registers and the virtual register defined has
49 // - Optimize Copies and Bitcast (more generally, target specific copies):
51 // Rewrite copies and bitcasts to avoid cross register bank copies
53 // E.g., Consider the following example, where capital and lower
54 // letters denote different register file:
55 // b = copy A <-- cross-bank copy
56 // C = copy b <-- cross-bank copy
58 // b = copy A <-- cross-bank copy
59 // C = copy A <-- same-bank copy
62 // b = bitcast A <-- cross-bank copy
63 // C = bitcast b <-- cross-bank copy
65 // b = bitcast A <-- cross-bank copy
66 // C = copy A <-- same-bank copy
67 //===----------------------------------------------------------------------===//
69 #include "llvm/CodeGen/Passes.h"
70 #include "llvm/ADT/DenseMap.h"
71 #include "llvm/ADT/SmallPtrSet.h"
72 #include "llvm/ADT/SmallSet.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/CodeGen/MachineDominators.h"
75 #include "llvm/CodeGen/MachineInstrBuilder.h"
76 #include "llvm/CodeGen/MachineRegisterInfo.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Target/TargetInstrInfo.h"
81 #include "llvm/Target/TargetRegisterInfo.h"
82 #include "llvm/Target/TargetSubtargetInfo.h"
86 #define DEBUG_TYPE "peephole-opt"
88 // Optimize Extensions
90 Aggressive("aggressive-ext-opt", cl::Hidden,
91 cl::desc("Aggressive extension optimization"));
94 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
95 cl::desc("Disable the peephole optimizer"));
98 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
99 cl::desc("Disable advanced copy optimization"));
101 // Limit the number of PHI instructions to process
102 // in PeepholeOptimizer::getNextSource.
103 static cl::opt<unsigned> RewritePHILimit(
104 "rewrite-phi-limit", cl::Hidden, cl::init(10),
105 cl::desc("Limit the length of PHI chains to lookup"));
107 STATISTIC(NumReuse, "Number of extension results reused");
108 STATISTIC(NumCmps, "Number of compares eliminated");
109 STATISTIC(NumImmFold, "Number of move immediate folded");
110 STATISTIC(NumLoadFold, "Number of loads folded");
111 STATISTIC(NumSelects, "Number of selects optimized");
112 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
113 STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
116 class ValueTrackerResult;
118 class PeepholeOptimizer : public MachineFunctionPass {
119 const TargetInstrInfo *TII;
120 const TargetRegisterInfo *TRI;
121 MachineRegisterInfo *MRI;
122 MachineDominatorTree *DT; // Machine dominator tree
125 static char ID; // Pass identification
126 PeepholeOptimizer() : MachineFunctionPass(ID) {
127 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
130 bool runOnMachineFunction(MachineFunction &MF) override;
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
133 AU.setPreservesCFG();
134 MachineFunctionPass::getAnalysisUsage(AU);
136 AU.addRequired<MachineDominatorTree>();
137 AU.addPreserved<MachineDominatorTree>();
141 /// \brief Track Def -> Use info used for rewriting copies.
142 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
146 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
147 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
148 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
149 bool optimizeSelect(MachineInstr *MI,
150 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
151 bool optimizeCondBranch(MachineInstr *MI);
152 bool optimizeCoalescableCopy(MachineInstr *MI);
153 bool optimizeUncoalescableCopy(MachineInstr *MI,
154 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
155 bool findNextSource(unsigned Reg, unsigned SubReg,
156 RewriteMapTy &RewriteMap);
157 bool isMoveImmediate(MachineInstr *MI,
158 SmallSet<unsigned, 4> &ImmDefRegs,
159 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
160 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
161 SmallSet<unsigned, 4> &ImmDefRegs,
162 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
164 /// \brief If copy instruction \p MI is a virtual register copy, track it in
165 /// the set \p CopiedFromRegs and \p CopyMIs. If this virtual register was
166 /// previously seen as a copy, replace the uses of this copy with the
167 /// previously seen copy's destination register.
168 bool foldRedundantCopy(MachineInstr *MI,
169 SmallSet<unsigned, 4> &CopiedFromRegs,
170 DenseMap<unsigned, MachineInstr*> &CopyMIs);
172 bool isLoadFoldable(MachineInstr *MI,
173 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
175 /// \brief Check whether \p MI is understood by the register coalescer
176 /// but may require some rewriting.
177 bool isCoalescableCopy(const MachineInstr &MI) {
178 // SubregToRegs are not interesting, because they are already register
179 // coalescer friendly.
180 return MI.isCopy() || (!DisableAdvCopyOpt &&
181 (MI.isRegSequence() || MI.isInsertSubreg() ||
182 MI.isExtractSubreg()));
185 /// \brief Check whether \p MI is a copy like instruction that is
186 /// not recognized by the register coalescer.
187 bool isUncoalescableCopy(const MachineInstr &MI) {
188 return MI.isBitcast() ||
189 (!DisableAdvCopyOpt &&
190 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
191 MI.isExtractSubregLike()));
195 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
196 /// returned sources for a given search and the instructions where the sources
197 /// were tracked from.
198 class ValueTrackerResult {
200 /// Track all sources found by one ValueTracker query.
201 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
203 /// Instruction using the sources in 'RegSrcs'.
204 const MachineInstr *Inst;
207 ValueTrackerResult() : Inst(nullptr) {}
208 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
209 addSource(Reg, SubReg);
212 bool isValid() const { return getNumSources() > 0; }
214 void setInst(const MachineInstr *I) { Inst = I; }
215 const MachineInstr *getInst() const { return Inst; }
222 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
223 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
226 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
227 assert(Idx < getNumSources() && "Reg pair source out of index");
228 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
231 int getNumSources() const { return RegSrcs.size(); }
233 unsigned getSrcReg(int Idx) const {
234 assert(Idx < getNumSources() && "Reg source out of index");
235 return RegSrcs[Idx].Reg;
238 unsigned getSrcSubReg(int Idx) const {
239 assert(Idx < getNumSources() && "SubReg source out of index");
240 return RegSrcs[Idx].SubReg;
243 bool operator==(const ValueTrackerResult &Other) {
244 if (Other.getInst() != getInst())
247 if (Other.getNumSources() != getNumSources())
250 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
251 if (Other.getSrcReg(i) != getSrcReg(i) ||
252 Other.getSrcSubReg(i) != getSrcSubReg(i))
258 /// \brief Helper class to track the possible sources of a value defined by
259 /// a (chain of) copy related instructions.
260 /// Given a definition (instruction and definition index), this class
261 /// follows the use-def chain to find successive suitable sources.
262 /// The given source can be used to rewrite the definition into
265 /// For instance, let us consider the following snippet:
267 /// v2 = INSERT_SUBREG v1, v0, sub0
268 /// def = COPY v2.sub0
270 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
271 /// suitable sources:
273 /// Then, def can be rewritten into def = COPY v0.
276 /// The current point into the use-def chain.
277 const MachineInstr *Def;
278 /// The index of the definition in Def.
280 /// The sub register index of the definition.
282 /// The register where the value can be found.
284 /// Specifiy whether or not the value tracking looks through
285 /// complex instructions. When this is false, the value tracker
286 /// bails on everything that is not a copy or a bitcast.
288 /// Note: This could have been implemented as a specialized version of
289 /// the ValueTracker class but that would have complicated the code of
290 /// the users of this class.
291 bool UseAdvancedTracking;
292 /// MachineRegisterInfo used to perform tracking.
293 const MachineRegisterInfo &MRI;
294 /// Optional TargetInstrInfo used to perform some complex
296 const TargetInstrInfo *TII;
298 /// \brief Dispatcher to the right underlying implementation of
300 ValueTrackerResult getNextSourceImpl();
301 /// \brief Specialized version of getNextSource for Copy instructions.
302 ValueTrackerResult getNextSourceFromCopy();
303 /// \brief Specialized version of getNextSource for Bitcast instructions.
304 ValueTrackerResult getNextSourceFromBitcast();
305 /// \brief Specialized version of getNextSource for RegSequence
307 ValueTrackerResult getNextSourceFromRegSequence();
308 /// \brief Specialized version of getNextSource for InsertSubreg
310 ValueTrackerResult getNextSourceFromInsertSubreg();
311 /// \brief Specialized version of getNextSource for ExtractSubreg
313 ValueTrackerResult getNextSourceFromExtractSubreg();
314 /// \brief Specialized version of getNextSource for SubregToReg
316 ValueTrackerResult getNextSourceFromSubregToReg();
317 /// \brief Specialized version of getNextSource for PHI instructions.
318 ValueTrackerResult getNextSourceFromPHI();
321 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
322 /// \p DefSubReg represents the sub register index the value tracker will
323 /// track. It does not need to match the sub register index used in the
324 /// definition of \p Reg.
325 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
326 /// through complex instructions. By default (false), it handles only copy
327 /// and bitcast instructions.
328 /// If \p Reg is a physical register, a value tracker constructed with
329 /// this constructor will not find any alternative source.
330 /// Indeed, when \p Reg is a physical register that constructor does not
331 /// know which definition of \p Reg it should track.
332 /// Use the next constructor to track a physical register.
333 ValueTracker(unsigned Reg, unsigned DefSubReg,
334 const MachineRegisterInfo &MRI,
335 bool UseAdvancedTracking = false,
336 const TargetInstrInfo *TII = nullptr)
337 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
338 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
339 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
340 Def = MRI.getVRegDef(Reg);
341 DefIdx = MRI.def_begin(Reg).getOperandNo();
345 /// \brief Create a ValueTracker instance for the value defined by
346 /// the pair \p MI, \p DefIdx.
347 /// Unlike the other constructor, the value tracker produced by this one
348 /// may be able to find a new source when the definition is a physical
350 /// This could be useful to rewrite target specific instructions into
351 /// generic copy instructions.
352 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
353 const MachineRegisterInfo &MRI,
354 bool UseAdvancedTracking = false,
355 const TargetInstrInfo *TII = nullptr)
356 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
357 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
358 assert(DefIdx < Def->getDesc().getNumDefs() &&
359 Def->getOperand(DefIdx).isReg() && "Invalid definition");
360 Reg = Def->getOperand(DefIdx).getReg();
363 /// \brief Following the use-def chain, get the next available source
364 /// for the tracked value.
365 /// \return A ValueTrackerResult containing a set of registers
366 /// and sub registers with tracked values. A ValueTrackerResult with
367 /// an empty set of registers means no source was found.
368 ValueTrackerResult getNextSource();
370 /// \brief Get the last register where the initial value can be found.
371 /// Initially this is the register of the definition.
372 /// Then, after each successful call to getNextSource, this is the
373 /// register of the last source.
374 unsigned getReg() const { return Reg; }
378 char PeepholeOptimizer::ID = 0;
379 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
380 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
381 "Peephole Optimizations", false, false)
382 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
383 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
384 "Peephole Optimizations", false, false)
386 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
387 /// a single register and writes a single register and it does not modify the
388 /// source, and if the source value is preserved as a sub-register of the
389 /// result, then replace all reachable uses of the source with the subreg of the
392 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
393 /// the code. Since this code does not currently share EXTRACTs, just ignore all
395 bool PeepholeOptimizer::
396 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
397 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
398 unsigned SrcReg, DstReg, SubIdx;
399 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
402 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
403 TargetRegisterInfo::isPhysicalRegister(SrcReg))
406 if (MRI->hasOneNonDBGUse(SrcReg))
410 // Ensure DstReg can get a register class that actually supports
411 // sub-registers. Don't change the class until we commit.
412 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
413 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
417 // The ext instr may be operating on a sub-register of SrcReg as well.
418 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
420 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
421 // SrcReg:SubIdx should be replaced.
423 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
425 // The source has other uses. See if we can replace the other uses with use of
426 // the result of the extension.
427 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
428 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
429 ReachedBBs.insert(UI.getParent());
431 // Uses that are in the same BB of uses of the result of the instruction.
432 SmallVector<MachineOperand*, 8> Uses;
434 // Uses that the result of the instruction can reach.
435 SmallVector<MachineOperand*, 8> ExtendedUses;
437 bool ExtendLife = true;
438 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
439 MachineInstr *UseMI = UseMO.getParent();
443 if (UseMI->isPHI()) {
448 // Only accept uses of SrcReg:SubIdx.
449 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
452 // It's an error to translate this:
454 // %reg1025 = <sext> %reg1024
456 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
460 // %reg1025 = <sext> %reg1024
462 // %reg1027 = COPY %reg1025:4
463 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
465 // The problem here is that SUBREG_TO_REG is there to assert that an
466 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
467 // the COPY here, it will give us the value after the <sext>, not the
468 // original value of %reg1024 before <sext>.
469 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
472 MachineBasicBlock *UseMBB = UseMI->getParent();
474 // Local uses that come after the extension.
475 if (!LocalMIs.count(UseMI))
476 Uses.push_back(&UseMO);
477 } else if (ReachedBBs.count(UseMBB)) {
478 // Non-local uses where the result of the extension is used. Always
479 // replace these unless it's a PHI.
480 Uses.push_back(&UseMO);
481 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
482 // We may want to extend the live range of the extension result in order
483 // to replace these uses.
484 ExtendedUses.push_back(&UseMO);
486 // Both will be live out of the def MBB anyway. Don't extend live range of
487 // the extension result.
493 if (ExtendLife && !ExtendedUses.empty())
494 // Extend the liveness of the extension result.
495 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
497 // Now replace all uses.
498 bool Changed = false;
500 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
502 // Look for PHI uses of the extended result, we don't want to extend the
503 // liveness of a PHI input. It breaks all kinds of assumptions down
504 // stream. A PHI use is expected to be the kill of its source values.
505 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
507 PHIBBs.insert(UI.getParent());
509 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
510 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
511 MachineOperand *UseMO = Uses[i];
512 MachineInstr *UseMI = UseMO->getParent();
513 MachineBasicBlock *UseMBB = UseMI->getParent();
514 if (PHIBBs.count(UseMBB))
517 // About to add uses of DstReg, clear DstReg's kill flags.
519 MRI->clearKillFlags(DstReg);
520 MRI->constrainRegClass(DstReg, DstRC);
523 unsigned NewVR = MRI->createVirtualRegister(RC);
524 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
525 TII->get(TargetOpcode::COPY), NewVR)
526 .addReg(DstReg, 0, SubIdx);
527 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
529 Copy->getOperand(0).setSubReg(SubIdx);
530 Copy->getOperand(0).setIsUndef();
532 UseMO->setReg(NewVR);
541 /// optimizeCmpInstr - If the instruction is a compare and the previous
542 /// instruction it's comparing against all ready sets (or could be modified to
543 /// set) the same flag as the compare, then we can remove the comparison and use
544 /// the flag from the previous instruction.
545 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
546 MachineBasicBlock *MBB) {
547 // If this instruction is a comparison against zero and isn't comparing a
548 // physical register, we can try to optimize it.
549 unsigned SrcReg, SrcReg2;
550 int CmpMask, CmpValue;
551 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
552 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
553 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
556 // Attempt to optimize the comparison instruction.
557 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
565 /// Optimize a select instruction.
566 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
567 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
569 unsigned FalseOp = 0;
570 bool Optimizable = false;
571 SmallVector<MachineOperand, 4> Cond;
572 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
576 if (!TII->optimizeSelect(MI, LocalMIs))
578 MI->eraseFromParent();
583 /// \brief Check if a simpler conditional branch can be
585 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
586 return TII->optimizeCondBranch(MI);
589 /// \brief Try to find the next source that share the same register file
590 /// for the value defined by \p Reg and \p SubReg.
591 /// When true is returned, the \p RewriteMap can be used by the client to
592 /// retrieve all Def -> Use along the way up to the next source. Any found
593 /// Use that is not itself a key for another entry, is the next source to
594 /// use. During the search for the next source, multiple sources can be found
595 /// given multiple incoming sources of a PHI instruction. In this case, we
596 /// look in each PHI source for the next source; all found next sources must
597 /// share the same register file as \p Reg and \p SubReg. The client should
598 /// then be capable to rewrite all intermediate PHIs to get the next source.
599 /// \return False if no alternative sources are available. True otherwise.
600 bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
601 RewriteMapTy &RewriteMap) {
602 // Do not try to find a new source for a physical register.
603 // So far we do not have any motivating example for doing that.
604 // Thus, instead of maintaining untested code, we will revisit that if
605 // that changes at some point.
606 if (TargetRegisterInfo::isPhysicalRegister(Reg))
608 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
610 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
611 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
612 SrcToLook.push_back(CurSrcPair);
614 unsigned PHICount = 0;
615 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
616 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
617 // As explained above, do not handle physical registers
618 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
622 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
623 !DisableAdvCopyOpt, TII);
624 ValueTrackerResult Res;
625 bool ShouldRewrite = false;
628 // Follow the chain of copies until we reach the top of the use-def chain
629 // or find a more suitable source.
630 Res = ValTracker.getNextSource();
634 // Insert the Def -> Use entry for the recently found source.
635 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
636 if (CurSrcRes.isValid()) {
637 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
638 // An existent entry with multiple sources is a PHI cycle we must avoid.
639 // Otherwise it's an entry with a valid next source we already found.
640 if (CurSrcRes.getNumSources() > 1) {
641 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
646 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
648 // ValueTrackerResult usually have one source unless it's the result from
649 // a PHI instruction. Add the found PHI edges to be looked up further.
650 unsigned NumSrcs = Res.getNumSources();
653 for (unsigned i = 0; i < NumSrcs; ++i)
654 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
655 Res.getSrcReg(i), Res.getSrcSubReg(i)));
659 CurSrcPair.Reg = Res.getSrcReg(0);
660 CurSrcPair.SubReg = Res.getSrcSubReg(0);
661 // Do not extend the live-ranges of physical registers as they add
662 // constraints to the register allocator. Moreover, if we want to extend
663 // the live-range of a physical register, unlike SSA virtual register,
664 // we will have to check that they aren't redefine before the related use.
665 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
668 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
669 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
671 } while (!ShouldRewrite);
673 // Continue looking for new sources...
677 // Do not continue searching for a new source if the there's at least
678 // one use-def which cannot be rewritten.
683 if (PHICount >= RewritePHILimit) {
684 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
688 // If we did not find a more suitable source, there is nothing to optimize.
689 return CurSrcPair.Reg != Reg;
692 /// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
693 /// guaranteed to have the same register class. This is necessary whenever we
694 /// successfully traverse a PHI instruction and find suitable sources coming
695 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
696 /// suitable to be used in a new COPY instruction.
697 static MachineInstr *
698 insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
699 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
700 MachineInstr *OrigPHI) {
701 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
703 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
704 unsigned NewVR = MRI->createVirtualRegister(NewRC);
705 MachineBasicBlock *MBB = OrigPHI->getParent();
706 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
707 TII->get(TargetOpcode::PHI), NewVR);
709 unsigned MBBOpIdx = 2;
710 for (auto RegPair : SrcRegs) {
711 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
712 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
713 // Since we're extended the lifetime of RegPair.Reg, clear the
714 // kill flags to account for that and make RegPair.Reg reaches
716 MRI->clearKillFlags(RegPair.Reg);
724 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
727 /// The copy-like instruction.
728 MachineInstr &CopyLike;
729 /// The index of the source being rewritten.
730 unsigned CurrentSrcIdx;
733 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
735 virtual ~CopyRewriter() {}
737 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
738 /// the related value that it affects (TrackReg, TrackSubReg).
739 /// A source is considered rewritable if its register class and the
740 /// register class of the related TrackReg may not be register
741 /// coalescer friendly. In other words, given a copy-like instruction
742 /// not all the arguments may be returned at rewritable source, since
743 /// some arguments are none to be register coalescer friendly.
745 /// Each call of this method moves the current source to the next
746 /// rewritable source.
747 /// For instance, let CopyLike be the instruction to rewrite.
748 /// CopyLike has one definition and one source:
749 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
751 /// The first call will give the first rewritable source, i.e.,
752 /// the only source this instruction has:
753 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
754 /// This source defines the whole definition, i.e.,
755 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
757 /// The second and subsequent calls will return false, as there is only one
758 /// rewritable source.
760 /// \return True if a rewritable source has been found, false otherwise.
761 /// The output arguments are valid if and only if true is returned.
762 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
764 unsigned &TrackSubReg) {
765 // If CurrentSrcIdx == 1, this means this function has already been called
766 // once. CopyLike has one definition and one argument, thus, there is
767 // nothing else to rewrite.
768 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
770 // This is the first call to getNextRewritableSource.
771 // Move the CurrentSrcIdx to remember that we made that call.
773 // The rewritable source is the argument.
774 const MachineOperand &MOSrc = CopyLike.getOperand(1);
775 SrcReg = MOSrc.getReg();
776 SrcSubReg = MOSrc.getSubReg();
777 // What we track are the alternative sources of the definition.
778 const MachineOperand &MODef = CopyLike.getOperand(0);
779 TrackReg = MODef.getReg();
780 TrackSubReg = MODef.getSubReg();
784 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
786 /// \return True if the rewriting was possible, false otherwise.
787 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
788 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
790 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
791 MOSrc.setReg(NewReg);
792 MOSrc.setSubReg(NewSubReg);
796 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
797 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
798 /// multiple sources for a given \p Def are found along the way, we found a
799 /// PHI instructions that needs to be rewritten.
800 /// TODO: HandleMultipleSources should be removed once we test PHI handling
801 /// with coalescable copies.
802 TargetInstrInfo::RegSubRegPair
803 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
804 TargetInstrInfo::RegSubRegPair Def,
805 PeepholeOptimizer::RewriteMapTy &RewriteMap,
806 bool HandleMultipleSources = true) {
808 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
810 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
811 // If there are no entries on the map, LookupSrc is the new source.
815 // There's only one source for this definition, keep searching...
816 unsigned NumSrcs = Res.getNumSources();
818 LookupSrc.Reg = Res.getSrcReg(0);
819 LookupSrc.SubReg = Res.getSrcSubReg(0);
823 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
824 if (!HandleMultipleSources)
827 // Multiple sources, recurse into each source to find a new source
828 // for it. Then, rewrite the PHI accordingly to its new edges.
829 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
830 for (unsigned i = 0; i < NumSrcs; ++i) {
831 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
832 Res.getSrcSubReg(i));
833 NewPHISrcs.push_back(
834 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
837 // Build the new PHI node and return its def register as the new source.
838 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
839 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
840 DEBUG(dbgs() << "-- getNewSource\n");
841 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
842 DEBUG(dbgs() << " With: " << *NewPHI);
843 const MachineOperand &MODef = NewPHI->getOperand(0);
844 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
848 return TargetInstrInfo::RegSubRegPair(0, 0);
851 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
852 /// and create a new COPY instruction. More info about RewriteMap in
853 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
854 /// Uncoalescable copies, since they are copy like instructions that aren't
855 /// recognized by the register allocator.
856 virtual MachineInstr *
857 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
858 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
863 /// \brief Helper class to rewrite uncoalescable copy like instructions
864 /// into new COPY (coalescable friendly) instructions.
865 class UncoalescableRewriter : public CopyRewriter {
867 const TargetInstrInfo &TII;
868 MachineRegisterInfo &MRI;
869 /// The number of defs in the bitcast
873 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
874 MachineRegisterInfo &MRI)
875 : CopyRewriter(MI), TII(TII), MRI(MRI) {
876 NumDefs = MI.getDesc().getNumDefs();
879 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
880 /// All such sources need to be considered rewritable in order to
881 /// rewrite a uncoalescable copy-like instruction. This method return
882 /// each definition that must be checked if rewritable.
884 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
886 unsigned &TrackSubReg) override {
887 // Find the next non-dead definition and continue from there.
888 if (CurrentSrcIdx == NumDefs)
891 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
893 if (CurrentSrcIdx == NumDefs)
897 // What we track are the alternative sources of the definition.
898 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
899 TrackReg = MODef.getReg();
900 TrackSubReg = MODef.getSubReg();
906 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
907 /// and create a new COPY instruction. More info about RewriteMap in
908 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
909 /// Uncoalescable copies, since they are copy like instructions that aren't
910 /// recognized by the register allocator.
912 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
913 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
914 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
915 "We do not rewrite physical registers");
917 // Find the new source to use in the COPY rewrite.
918 TargetInstrInfo::RegSubRegPair NewSrc =
919 getNewSource(&MRI, &TII, Def, RewriteMap);
922 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
923 unsigned NewVR = MRI.createVirtualRegister(DefRC);
925 MachineInstr *NewCopy =
926 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
927 TII.get(TargetOpcode::COPY), NewVR)
928 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
930 NewCopy->getOperand(0).setSubReg(Def.SubReg);
932 NewCopy->getOperand(0).setIsUndef();
934 DEBUG(dbgs() << "-- RewriteSource\n");
935 DEBUG(dbgs() << " Replacing: " << CopyLike);
936 DEBUG(dbgs() << " With: " << *NewCopy);
937 MRI.replaceRegWith(Def.Reg, NewVR);
938 MRI.clearKillFlags(NewVR);
940 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
942 MRI.clearKillFlags(NewSrc.Reg);
948 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
949 class InsertSubregRewriter : public CopyRewriter {
951 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
952 assert(MI.isInsertSubreg() && "Invalid instruction");
955 /// \brief See CopyRewriter::getNextRewritableSource.
956 /// Here CopyLike has the following form:
957 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
958 /// Src1 has the same register class has dst, hence, there is
959 /// nothing to rewrite.
960 /// Src2.src2SubIdx, may not be register coalescer friendly.
961 /// Therefore, the first call to this method returns:
962 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
963 /// (TrackReg, TrackSubReg) = (dst, subIdx).
965 /// Subsequence calls will return false.
966 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
968 unsigned &TrackSubReg) override {
969 // If we already get the only source we can rewrite, return false.
970 if (CurrentSrcIdx == 2)
972 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
974 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
975 SrcReg = MOInsertedReg.getReg();
976 SrcSubReg = MOInsertedReg.getSubReg();
977 const MachineOperand &MODef = CopyLike.getOperand(0);
979 // We want to track something that is compatible with the
980 // partial definition.
981 TrackReg = MODef.getReg();
982 if (MODef.getSubReg())
983 // Bail if we have to compose sub-register indices.
985 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
988 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
989 if (CurrentSrcIdx != 2)
991 // We are rewriting the inserted reg.
992 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
994 MO.setSubReg(NewSubReg);
999 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1000 class ExtractSubregRewriter : public CopyRewriter {
1001 const TargetInstrInfo &TII;
1004 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1005 : CopyRewriter(MI), TII(TII) {
1006 assert(MI.isExtractSubreg() && "Invalid instruction");
1009 /// \brief See CopyRewriter::getNextRewritableSource.
1010 /// Here CopyLike has the following form:
1011 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1012 /// There is only one rewritable source: Src.subIdx,
1013 /// which defines dst.dstSubIdx.
1014 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1016 unsigned &TrackSubReg) override {
1017 // If we already get the only source we can rewrite, return false.
1018 if (CurrentSrcIdx == 1)
1020 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1022 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1023 SrcReg = MOExtractedReg.getReg();
1024 // If we have to compose sub-register indices, bail out.
1025 if (MOExtractedReg.getSubReg())
1028 SrcSubReg = CopyLike.getOperand(2).getImm();
1030 // We want to track something that is compatible with the definition.
1031 const MachineOperand &MODef = CopyLike.getOperand(0);
1032 TrackReg = MODef.getReg();
1033 TrackSubReg = MODef.getSubReg();
1037 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1038 // The only source we can rewrite is the input register.
1039 if (CurrentSrcIdx != 1)
1042 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1044 // If we find a source that does not require to extract something,
1045 // rewrite the operation with a copy.
1047 // Move the current index to an invalid position.
1048 // We do not want another call to this method to be able
1049 // to do any change.
1051 // Rewrite the operation as a COPY.
1052 // Get rid of the sub-register index.
1053 CopyLike.RemoveOperand(2);
1054 // Morph the operation into a COPY.
1055 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1058 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1063 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
1064 class RegSequenceRewriter : public CopyRewriter {
1066 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1067 assert(MI.isRegSequence() && "Invalid instruction");
1070 /// \brief See CopyRewriter::getNextRewritableSource.
1071 /// Here CopyLike has the following form:
1072 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1073 /// Each call will return a different source, walking all the available
1076 /// The first call returns:
1077 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1078 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1080 /// The second call returns:
1081 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1082 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1084 /// And so on, until all the sources have been traversed, then
1085 /// it returns false.
1086 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1088 unsigned &TrackSubReg) override {
1089 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1091 // If this is the first call, move to the first argument.
1092 if (CurrentSrcIdx == 0) {
1095 // Otherwise, move to the next argument and check that it is valid.
1097 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1100 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1101 SrcReg = MOInsertedReg.getReg();
1102 // If we have to compose sub-register indices, bail out.
1103 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1106 // We want to track something that is compatible with the related
1107 // partial definition.
1108 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1110 const MachineOperand &MODef = CopyLike.getOperand(0);
1111 TrackReg = MODef.getReg();
1112 // If we have to compose sub-registers, bail.
1113 return MODef.getSubReg() == 0;
1116 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1117 // We cannot rewrite out of bound operands.
1118 // Moreover, rewritable sources are at odd positions.
1119 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1122 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1124 MO.setSubReg(NewSubReg);
1130 /// \brief Get the appropriated CopyRewriter for \p MI.
1131 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1132 /// if no rewriter works for \p MI.
1133 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
1134 const TargetInstrInfo &TII,
1135 MachineRegisterInfo &MRI) {
1136 // Handle uncoalescable copy-like instructions.
1137 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1138 MI.isExtractSubregLike()))
1139 return new UncoalescableRewriter(MI, TII, MRI);
1141 switch (MI.getOpcode()) {
1144 case TargetOpcode::COPY:
1145 return new CopyRewriter(MI);
1146 case TargetOpcode::INSERT_SUBREG:
1147 return new InsertSubregRewriter(MI);
1148 case TargetOpcode::EXTRACT_SUBREG:
1149 return new ExtractSubregRewriter(MI, TII);
1150 case TargetOpcode::REG_SEQUENCE:
1151 return new RegSequenceRewriter(MI);
1153 llvm_unreachable(nullptr);
1156 /// \brief Optimize generic copy instructions to avoid cross
1157 /// register bank copy. The optimization looks through a chain of
1158 /// copies and tries to find a source that has a compatible register
1160 /// Two register classes are considered to be compatible if they share
1161 /// the same register bank.
1162 /// New copies issued by this optimization are register allocator
1163 /// friendly. This optimization does not remove any copy as it may
1164 /// overconstrain the register allocator, but replaces some operands
1166 /// \pre isCoalescableCopy(*MI) is true.
1167 /// \return True, when \p MI has been rewritten. False otherwise.
1168 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1169 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1170 assert(MI->getDesc().getNumDefs() == 1 &&
1171 "Coalescer can understand multiple defs?!");
1172 const MachineOperand &MODef = MI->getOperand(0);
1173 // Do not rewrite physical definitions.
1174 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1177 bool Changed = false;
1178 // Get the right rewriter for the current copy.
1179 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1180 // If none exists, bail out.
1183 // Rewrite each rewritable source.
1184 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1185 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1187 // Keep track of PHI nodes and its incoming edges when looking for sources.
1188 RewriteMapTy RewriteMap;
1189 // Try to find a more suitable source. If we failed to do so, or get the
1190 // actual source, move to the next source.
1191 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
1194 // Get the new source to rewrite. TODO: Only enable handling of multiple
1195 // sources (PHIs) once we have a motivating example and testcases for it.
1196 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1197 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1198 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1199 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1203 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1204 // We may have extended the live-range of NewSrc, account for that.
1205 MRI->clearKillFlags(NewSrc.Reg);
1209 // TODO: We could have a clean-up method to tidy the instruction.
1210 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1212 // Currently we haven't seen motivating example for that and we
1213 // want to avoid untested code.
1214 NumRewrittenCopies += Changed;
1218 /// \brief Optimize copy-like instructions to create
1219 /// register coalescer friendly instruction.
1220 /// The optimization tries to kill-off the \p MI by looking
1221 /// through a chain of copies to find a source that has a compatible
1223 /// If such a source is found, it replace \p MI by a generic COPY
1225 /// \pre isUncoalescableCopy(*MI) is true.
1226 /// \return True, when \p MI has been optimized. In that case, \p MI has
1227 /// been removed from its parent.
1228 /// All COPY instructions created, are inserted in \p LocalMIs.
1229 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1230 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1231 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1233 // Check if we can rewrite all the values defined by this instruction.
1234 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
1235 // Get the right rewriter for the current copy.
1236 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1237 // If none exists, bail out.
1241 // Rewrite each rewritable source by generating new COPYs. This works
1242 // differently from optimizeCoalescableCopy since it first makes sure that all
1243 // definitions can be rewritten.
1244 RewriteMapTy RewriteMap;
1245 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1246 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1248 // If a physical register is here, this is probably for a good reason.
1249 // Do not rewrite that.
1250 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
1253 // If we do not know how to rewrite this definition, there is no point
1254 // in trying to kill this instruction.
1255 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1256 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
1259 RewritePairs.push_back(Def);
1262 // The change is possible for all defs, do it.
1263 for (const auto &Def : RewritePairs) {
1264 // Rewrite the "copy" in a way the register coalescer understands.
1265 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
1266 assert(NewCopy && "Should be able to always generate a new copy");
1267 LocalMIs.insert(NewCopy);
1271 MI->eraseFromParent();
1272 ++NumUncoalescableCopies;
1276 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
1277 /// instruction. We only fold loads to virtual registers and the virtual
1278 /// register defined has a single use.
1279 bool PeepholeOptimizer::isLoadFoldable(
1281 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1282 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1284 const MCInstrDesc &MCID = MI->getDesc();
1285 if (MCID.getNumDefs() != 1)
1288 unsigned Reg = MI->getOperand(0).getReg();
1289 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1290 // loads. It should be checked when processing uses of the load, since
1291 // uses can be removed during peephole.
1292 if (!MI->getOperand(0).getSubReg() &&
1293 TargetRegisterInfo::isVirtualRegister(Reg) &&
1294 MRI->hasOneNonDBGUse(Reg)) {
1295 FoldAsLoadDefCandidates.insert(Reg);
1301 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1302 SmallSet<unsigned, 4> &ImmDefRegs,
1303 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1304 const MCInstrDesc &MCID = MI->getDesc();
1305 if (!MI->isMoveImmediate())
1307 if (MCID.getNumDefs() != 1)
1309 unsigned Reg = MI->getOperand(0).getReg();
1310 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1311 ImmDefMIs.insert(std::make_pair(Reg, MI));
1312 ImmDefRegs.insert(Reg);
1319 /// foldImmediate - Try folding register operands that are defined by move
1320 /// immediate instructions, i.e. a trivial constant folding optimization, if
1321 /// and only if the def and use are in the same BB.
1322 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1323 SmallSet<unsigned, 4> &ImmDefRegs,
1324 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1325 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1326 MachineOperand &MO = MI->getOperand(i);
1327 if (!MO.isReg() || MO.isDef())
1329 unsigned Reg = MO.getReg();
1330 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1332 if (ImmDefRegs.count(Reg) == 0)
1334 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1335 assert(II != ImmDefMIs.end());
1336 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1344 // FIXME: This is very simple and misses some cases which should be handled when
1345 // motivating examples are found.
1347 // The copy rewriting logic should look at uses as well as defs and be able to
1348 // eliminate copies across blocks.
1350 // Later copies that are subregister extracts will also not be eliminated since
1351 // only the first copy is considered.
1354 // %vreg1 = COPY %vreg0
1355 // %vreg2 = COPY %vreg0:sub1
1357 // Should replace %vreg2 uses with %vreg1:sub1
1358 bool PeepholeOptimizer::foldRedundantCopy(
1360 SmallSet<unsigned, 4> &CopySrcRegs,
1361 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1362 assert(MI->isCopy());
1364 unsigned SrcReg = MI->getOperand(1).getReg();
1365 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1368 unsigned DstReg = MI->getOperand(0).getReg();
1369 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1372 if (CopySrcRegs.insert(SrcReg).second) {
1373 // First copy of this reg seen.
1374 CopyMIs.insert(std::make_pair(SrcReg, MI));
1378 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1380 unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1381 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1383 // Can't replace different subregister extracts.
1384 if (SrcSubReg != PrevSrcSubReg)
1387 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1389 // Only replace if the copy register class is the same.
1391 // TODO: If we have multiple copies to different register classes, we may want
1392 // to track multiple copies of the same source register.
1393 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1396 MRI->replaceRegWith(DstReg, PrevDstReg);
1398 // Lifetime of the previous copy has been extended.
1399 MRI->clearKillFlags(PrevDstReg);
1403 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1404 if (skipOptnoneFunction(*MF.getFunction()))
1407 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1408 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1410 if (DisablePeephole)
1413 TII = MF.getSubtarget().getInstrInfo();
1414 TRI = MF.getSubtarget().getRegisterInfo();
1415 MRI = &MF.getRegInfo();
1416 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1418 bool Changed = false;
1420 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1421 MachineBasicBlock *MBB = &*I;
1423 bool SeenMoveImm = false;
1425 // During this forward scan, at some point it needs to answer the question
1426 // "given a pointer to an MI in the current BB, is it located before or
1427 // after the current instruction".
1428 // To perform this, the following set keeps track of the MIs already seen
1429 // during the scan, if a MI is not in the set, it is assumed to be located
1430 // after. Newly created MIs have to be inserted in the set as well.
1431 SmallPtrSet<MachineInstr*, 16> LocalMIs;
1432 SmallSet<unsigned, 4> ImmDefRegs;
1433 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1434 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1436 // Set of virtual registers that are copied from.
1437 SmallSet<unsigned, 4> CopySrcRegs;
1438 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1440 for (MachineBasicBlock::iterator
1441 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1442 MachineInstr *MI = &*MII;
1443 // We may be erasing MI below, increment MII now.
1445 LocalMIs.insert(MI);
1447 // Skip debug values. They should not affect this peephole optimization.
1448 if (MI->isDebugValue())
1451 // If we run into an instruction we can't fold across, discard
1452 // the load candidates.
1453 if (MI->isLoadFoldBarrier())
1454 FoldAsLoadDefCandidates.clear();
1456 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1457 MI->isKill() || MI->isInlineAsm() ||
1458 MI->hasUnmodeledSideEffects())
1461 if ((isUncoalescableCopy(*MI) &&
1462 optimizeUncoalescableCopy(MI, LocalMIs)) ||
1463 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1464 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
1471 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1476 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1477 // MI is just rewritten.
1482 if (MI->isCopy() && foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs)) {
1484 MI->eraseFromParent();
1489 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1492 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1493 // optimizeExtInstr might have created new instructions after MI
1494 // and before the already incremented MII. Adjust MII so that the
1495 // next iteration sees the new instructions.
1499 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1502 // Check whether MI is a load candidate for folding into a later
1503 // instruction. If MI is not a candidate, check whether we can fold an
1504 // earlier load into MI.
1505 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1506 !FoldAsLoadDefCandidates.empty()) {
1507 const MCInstrDesc &MIDesc = MI->getDesc();
1508 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1510 const MachineOperand &MOp = MI->getOperand(i);
1513 unsigned FoldAsLoadDefReg = MOp.getReg();
1514 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1515 // We need to fold load after optimizeCmpInstr, since
1516 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1517 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1518 // we need it for markUsesInDebugValueAsUndef().
1519 unsigned FoldedReg = FoldAsLoadDefReg;
1520 MachineInstr *DefMI = nullptr;
1521 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1525 // Update LocalMIs since we replaced MI with FoldMI and deleted
1527 DEBUG(dbgs() << "Replacing: " << *MI);
1528 DEBUG(dbgs() << " With: " << *FoldMI);
1530 LocalMIs.erase(DefMI);
1531 LocalMIs.insert(FoldMI);
1532 MI->eraseFromParent();
1533 DefMI->eraseFromParent();
1534 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1535 FoldAsLoadDefCandidates.erase(FoldedReg);
1537 // MI is replaced with FoldMI.
1550 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1551 assert(Def->isCopy() && "Invalid definition");
1552 // Copy instruction are supposed to be: Def = Src.
1553 // If someone breaks this assumption, bad things will happen everywhere.
1554 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1556 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1557 // If we look for a different subreg, it means we want a subreg of src.
1558 // Bails as we do not support composing subregs yet.
1559 return ValueTrackerResult();
1560 // Otherwise, we want the whole source.
1561 const MachineOperand &Src = Def->getOperand(1);
1562 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1565 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1566 assert(Def->isBitcast() && "Invalid definition");
1568 // Bail if there are effects that a plain copy will not expose.
1569 if (Def->hasUnmodeledSideEffects())
1570 return ValueTrackerResult();
1572 // Bitcasts with more than one def are not supported.
1573 if (Def->getDesc().getNumDefs() != 1)
1574 return ValueTrackerResult();
1575 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1576 // If we look for a different subreg, it means we want a subreg of the src.
1577 // Bails as we do not support composing subregs yet.
1578 return ValueTrackerResult();
1580 unsigned SrcIdx = Def->getNumOperands();
1581 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1583 const MachineOperand &MO = Def->getOperand(OpIdx);
1584 if (!MO.isReg() || !MO.getReg())
1586 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1587 if (SrcIdx != EndOpIdx)
1588 // Multiple sources?
1589 return ValueTrackerResult();
1592 const MachineOperand &Src = Def->getOperand(SrcIdx);
1593 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1596 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1597 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1598 "Invalid definition");
1600 if (Def->getOperand(DefIdx).getSubReg())
1601 // If we are composing subregs, bail out.
1602 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1603 // This should almost never happen as the SSA property is tracked at
1604 // the register level (as opposed to the subreg level).
1608 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1609 // Def. Thus, it must not be generated.
1610 // However, some code could theoretically generates a single
1611 // Def.sub0 (i.e, not defining the other subregs) and we would
1613 // If we can ascertain (or force) that this never happens, we could
1614 // turn that into an assertion.
1615 return ValueTrackerResult();
1618 // We could handle the REG_SEQUENCE here, but we do not want to
1619 // duplicate the code from the generic TII.
1620 return ValueTrackerResult();
1622 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1623 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1624 return ValueTrackerResult();
1626 // We are looking at:
1627 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1628 // Check if one of the operand defines the subreg we are interested in.
1629 for (auto &RegSeqInput : RegSeqInputRegs) {
1630 if (RegSeqInput.SubIdx == DefSubReg) {
1631 if (RegSeqInput.SubReg)
1632 // Bail if we have to compose sub registers.
1633 return ValueTrackerResult();
1635 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1639 // If the subreg we are tracking is super-defined by another subreg,
1640 // we could follow this value. However, this would require to compose
1641 // the subreg and we do not do that for now.
1642 return ValueTrackerResult();
1645 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1646 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1647 "Invalid definition");
1649 if (Def->getOperand(DefIdx).getSubReg())
1650 // If we are composing subreg, bail out.
1651 // Same remark as getNextSourceFromRegSequence.
1652 // I.e., this may be turned into an assert.
1653 return ValueTrackerResult();
1656 // We could handle the REG_SEQUENCE here, but we do not want to
1657 // duplicate the code from the generic TII.
1658 return ValueTrackerResult();
1660 TargetInstrInfo::RegSubRegPair BaseReg;
1661 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1662 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1663 return ValueTrackerResult();
1665 // We are looking at:
1666 // Def = INSERT_SUBREG v0, v1, sub1
1667 // There are two cases:
1668 // 1. DefSubReg == sub1, get v1.
1669 // 2. DefSubReg != sub1, the value may be available through v0.
1671 // #1 Check if the inserted register matches the required sub index.
1672 if (InsertedReg.SubIdx == DefSubReg) {
1673 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1675 // #2 Otherwise, if the sub register we are looking for is not partial
1676 // defined by the inserted element, we can look through the main
1678 const MachineOperand &MODef = Def->getOperand(DefIdx);
1679 // If the result register (Def) and the base register (v0) do not
1680 // have the same register class or if we have to compose
1681 // subregisters, bail out.
1682 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1684 return ValueTrackerResult();
1686 // Get the TRI and check if the inserted sub-register overlaps with the
1687 // sub-register we are tracking.
1688 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1690 (TRI->getSubRegIndexLaneMask(DefSubReg) &
1691 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1692 return ValueTrackerResult();
1693 // At this point, the value is available in v0 via the same subreg
1695 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1698 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1699 assert((Def->isExtractSubreg() ||
1700 Def->isExtractSubregLike()) && "Invalid definition");
1701 // We are looking at:
1702 // Def = EXTRACT_SUBREG v0, sub0
1704 // Bail if we have to compose sub registers.
1705 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1707 return ValueTrackerResult();
1710 // We could handle the EXTRACT_SUBREG here, but we do not want to
1711 // duplicate the code from the generic TII.
1712 return ValueTrackerResult();
1714 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1715 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1716 return ValueTrackerResult();
1718 // Bail if we have to compose sub registers.
1719 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1720 if (ExtractSubregInputReg.SubReg)
1721 return ValueTrackerResult();
1722 // Otherwise, the value is available in the v0.sub0.
1723 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
1726 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
1727 assert(Def->isSubregToReg() && "Invalid definition");
1728 // We are looking at:
1729 // Def = SUBREG_TO_REG Imm, v0, sub0
1731 // Bail if we have to compose sub registers.
1732 // If DefSubReg != sub0, we would have to check that all the bits
1733 // we track are included in sub0 and if yes, we would have to
1734 // determine the right subreg in v0.
1735 if (DefSubReg != Def->getOperand(3).getImm())
1736 return ValueTrackerResult();
1737 // Bail if we have to compose sub registers.
1738 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1739 if (Def->getOperand(2).getSubReg())
1740 return ValueTrackerResult();
1742 return ValueTrackerResult(Def->getOperand(2).getReg(),
1743 Def->getOperand(3).getImm());
1746 /// \brief Explore each PHI incoming operand and return its sources
1747 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1748 assert(Def->isPHI() && "Invalid definition");
1749 ValueTrackerResult Res;
1751 // If we look for a different subreg, bail as we do not support composing
1753 if (Def->getOperand(0).getSubReg() != DefSubReg)
1754 return ValueTrackerResult();
1756 // Return all register sources for PHI instructions.
1757 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1758 auto &MO = Def->getOperand(i);
1759 assert(MO.isReg() && "Invalid PHI instruction");
1760 Res.addSource(MO.getReg(), MO.getSubReg());
1766 ValueTrackerResult ValueTracker::getNextSourceImpl() {
1767 assert(Def && "This method needs a valid definition");
1770 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1771 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1773 return getNextSourceFromCopy();
1774 if (Def->isBitcast())
1775 return getNextSourceFromBitcast();
1776 // All the remaining cases involve "complex" instructions.
1777 // Bail if we did not ask for the advanced tracking.
1778 if (!UseAdvancedTracking)
1779 return ValueTrackerResult();
1780 if (Def->isRegSequence() || Def->isRegSequenceLike())
1781 return getNextSourceFromRegSequence();
1782 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
1783 return getNextSourceFromInsertSubreg();
1784 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1785 return getNextSourceFromExtractSubreg();
1786 if (Def->isSubregToReg())
1787 return getNextSourceFromSubregToReg();
1789 return getNextSourceFromPHI();
1790 return ValueTrackerResult();
1793 ValueTrackerResult ValueTracker::getNextSource() {
1794 // If we reach a point where we cannot move up in the use-def chain,
1795 // there is nothing we can get.
1797 return ValueTrackerResult();
1799 ValueTrackerResult Res = getNextSourceImpl();
1800 if (Res.isValid()) {
1801 // Update definition, definition index, and subregister for the
1802 // next call of getNextSource.
1803 // Update the current register.
1804 bool OneRegSrc = Res.getNumSources() == 1;
1806 Reg = Res.getSrcReg(0);
1807 // Update the result before moving up in the use-def chain
1808 // with the instruction containing the last found sources.
1811 // If we can still move up in the use-def chain, move to the next
1813 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
1814 Def = MRI.getVRegDef(Reg);
1815 DefIdx = MRI.def_begin(Reg).getOperandNo();
1816 DefSubReg = Res.getSrcSubReg(0);
1820 // If we end up here, this means we will not be able to find another source
1821 // for the next iteration. Make sure any new call to getNextSource bails out
1822 // early by cutting the use-def chain.