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/Target/TargetInstrInfo.h"
80 #include "llvm/Target/TargetRegisterInfo.h"
81 #include "llvm/Target/TargetSubtargetInfo.h"
85 #define DEBUG_TYPE "peephole-opt"
87 // Optimize Extensions
89 Aggressive("aggressive-ext-opt", cl::Hidden,
90 cl::desc("Aggressive extension optimization"));
93 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
94 cl::desc("Disable the peephole optimizer"));
97 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
98 cl::desc("Disable advanced copy optimization"));
100 STATISTIC(NumReuse, "Number of extension results reused");
101 STATISTIC(NumCmps, "Number of compares eliminated");
102 STATISTIC(NumImmFold, "Number of move immediate folded");
103 STATISTIC(NumLoadFold, "Number of loads folded");
104 STATISTIC(NumSelects, "Number of selects optimized");
105 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
106 STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
109 class PeepholeOptimizer : public MachineFunctionPass {
110 const TargetInstrInfo *TII;
111 const TargetRegisterInfo *TRI;
112 MachineRegisterInfo *MRI;
113 MachineDominatorTree *DT; // Machine dominator tree
116 static char ID; // Pass identification
117 PeepholeOptimizer() : MachineFunctionPass(ID) {
118 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
121 bool runOnMachineFunction(MachineFunction &MF) override;
123 void getAnalysisUsage(AnalysisUsage &AU) const override {
124 AU.setPreservesCFG();
125 MachineFunctionPass::getAnalysisUsage(AU);
127 AU.addRequired<MachineDominatorTree>();
128 AU.addPreserved<MachineDominatorTree>();
133 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
134 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
135 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
136 bool optimizeSelect(MachineInstr *MI,
137 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
138 bool optimizeCondBranch(MachineInstr *MI);
139 bool optimizeCopyOrBitcast(MachineInstr *MI);
140 bool optimizeCoalescableCopy(MachineInstr *MI);
141 bool optimizeUncoalescableCopy(MachineInstr *MI,
142 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
143 bool findNextSource(unsigned &Reg, unsigned &SubReg);
144 bool isMoveImmediate(MachineInstr *MI,
145 SmallSet<unsigned, 4> &ImmDefRegs,
146 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
147 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
148 SmallSet<unsigned, 4> &ImmDefRegs,
149 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
150 bool isLoadFoldable(MachineInstr *MI,
151 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
153 /// \brief Check whether \p MI is understood by the register coalescer
154 /// but may require some rewriting.
155 bool isCoalescableCopy(const MachineInstr &MI) {
156 // SubregToRegs are not interesting, because they are already register
157 // coalescer friendly.
158 return MI.isCopy() || (!DisableAdvCopyOpt &&
159 (MI.isRegSequence() || MI.isInsertSubreg() ||
160 MI.isExtractSubreg()));
163 /// \brief Check whether \p MI is a copy like instruction that is
164 /// not recognized by the register coalescer.
165 bool isUncoalescableCopy(const MachineInstr &MI) {
166 return MI.isBitcast() ||
167 (!DisableAdvCopyOpt &&
168 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
169 MI.isExtractSubregLike()));
173 /// \brief Helper class to track the possible sources of a value defined by
174 /// a (chain of) copy related instructions.
175 /// Given a definition (instruction and definition index), this class
176 /// follows the use-def chain to find successive suitable sources.
177 /// The given source can be used to rewrite the definition into
180 /// For instance, let us consider the following snippet:
182 /// v2 = INSERT_SUBREG v1, v0, sub0
183 /// def = COPY v2.sub0
185 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
186 /// suitable sources:
188 /// Then, def can be rewritten into def = COPY v0.
191 /// The current point into the use-def chain.
192 const MachineInstr *Def;
193 /// The index of the definition in Def.
195 /// The sub register index of the definition.
197 /// The register where the value can be found.
199 /// Specifiy whether or not the value tracking looks through
200 /// complex instructions. When this is false, the value tracker
201 /// bails on everything that is not a copy or a bitcast.
203 /// Note: This could have been implemented as a specialized version of
204 /// the ValueTracker class but that would have complicated the code of
205 /// the users of this class.
206 bool UseAdvancedTracking;
207 /// MachineRegisterInfo used to perform tracking.
208 const MachineRegisterInfo &MRI;
209 /// Optional TargetInstrInfo used to perform some complex
211 const TargetInstrInfo *TII;
213 /// \brief Dispatcher to the right underlying implementation of
215 bool getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg);
216 /// \brief Specialized version of getNextSource for Copy instructions.
217 bool getNextSourceFromCopy(unsigned &SrcReg, unsigned &SrcSubReg);
218 /// \brief Specialized version of getNextSource for Bitcast instructions.
219 bool getNextSourceFromBitcast(unsigned &SrcReg, unsigned &SrcSubReg);
220 /// \brief Specialized version of getNextSource for RegSequence
222 bool getNextSourceFromRegSequence(unsigned &SrcReg, unsigned &SrcSubReg);
223 /// \brief Specialized version of getNextSource for InsertSubreg
225 bool getNextSourceFromInsertSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
226 /// \brief Specialized version of getNextSource for ExtractSubreg
228 bool getNextSourceFromExtractSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
229 /// \brief Specialized version of getNextSource for SubregToReg
231 bool getNextSourceFromSubregToReg(unsigned &SrcReg, unsigned &SrcSubReg);
234 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
235 /// \p DefSubReg represents the sub register index the value tracker will
236 /// track. It does not need to match the sub register index used in the
237 /// definition of \p Reg.
238 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
239 /// through complex instructions. By default (false), it handles only copy
240 /// and bitcast instructions.
241 /// If \p Reg is a physical register, a value tracker constructed with
242 /// this constructor will not find any alternative source.
243 /// Indeed, when \p Reg is a physical register that constructor does not
244 /// know which definition of \p Reg it should track.
245 /// Use the next constructor to track a physical register.
246 ValueTracker(unsigned Reg, unsigned DefSubReg,
247 const MachineRegisterInfo &MRI,
248 bool UseAdvancedTracking = false,
249 const TargetInstrInfo *TII = nullptr)
250 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
251 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
252 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
253 Def = MRI.getVRegDef(Reg);
254 DefIdx = MRI.def_begin(Reg).getOperandNo();
258 /// \brief Create a ValueTracker instance for the value defined by
259 /// the pair \p MI, \p DefIdx.
260 /// Unlike the other constructor, the value tracker produced by this one
261 /// may be able to find a new source when the definition is a physical
263 /// This could be useful to rewrite target specific instructions into
264 /// generic copy instructions.
265 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
266 const MachineRegisterInfo &MRI,
267 bool UseAdvancedTracking = false,
268 const TargetInstrInfo *TII = nullptr)
269 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
270 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
271 assert(DefIdx < Def->getDesc().getNumDefs() &&
272 Def->getOperand(DefIdx).isReg() && "Invalid definition");
273 Reg = Def->getOperand(DefIdx).getReg();
276 /// \brief Following the use-def chain, get the next available source
277 /// for the tracked value.
278 /// When the returned value is not nullptr, \p SrcReg gives the register
279 /// that contain the tracked value.
280 /// \note The sub register index returned in \p SrcSubReg must be used
281 /// on \p SrcReg to access the actual value.
282 /// \return Unless the returned value is nullptr (i.e., no source found),
283 /// \p SrcReg gives the register of the next source used in the returned
284 /// instruction and \p SrcSubReg the sub-register index to be used on that
285 /// source to get the tracked value. When nullptr is returned, no
286 /// alternative source has been found.
287 const MachineInstr *getNextSource(unsigned &SrcReg, unsigned &SrcSubReg);
289 /// \brief Get the last register where the initial value can be found.
290 /// Initially this is the register of the definition.
291 /// Then, after each successful call to getNextSource, this is the
292 /// register of the last source.
293 unsigned getReg() const { return Reg; }
297 char PeepholeOptimizer::ID = 0;
298 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
299 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
300 "Peephole Optimizations", false, false)
301 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
302 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
303 "Peephole Optimizations", false, false)
305 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
306 /// a single register and writes a single register and it does not modify the
307 /// source, and if the source value is preserved as a sub-register of the
308 /// result, then replace all reachable uses of the source with the subreg of the
311 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
312 /// the code. Since this code does not currently share EXTRACTs, just ignore all
314 bool PeepholeOptimizer::
315 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
316 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
317 unsigned SrcReg, DstReg, SubIdx;
318 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
321 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
322 TargetRegisterInfo::isPhysicalRegister(SrcReg))
325 if (MRI->hasOneNonDBGUse(SrcReg))
329 // Ensure DstReg can get a register class that actually supports
330 // sub-registers. Don't change the class until we commit.
331 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
332 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
336 // The ext instr may be operating on a sub-register of SrcReg as well.
337 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
339 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
340 // SrcReg:SubIdx should be replaced.
342 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
344 // The source has other uses. See if we can replace the other uses with use of
345 // the result of the extension.
346 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
347 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
348 ReachedBBs.insert(UI.getParent());
350 // Uses that are in the same BB of uses of the result of the instruction.
351 SmallVector<MachineOperand*, 8> Uses;
353 // Uses that the result of the instruction can reach.
354 SmallVector<MachineOperand*, 8> ExtendedUses;
356 bool ExtendLife = true;
357 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
358 MachineInstr *UseMI = UseMO.getParent();
362 if (UseMI->isPHI()) {
367 // Only accept uses of SrcReg:SubIdx.
368 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
371 // It's an error to translate this:
373 // %reg1025 = <sext> %reg1024
375 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
379 // %reg1025 = <sext> %reg1024
381 // %reg1027 = COPY %reg1025:4
382 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
384 // The problem here is that SUBREG_TO_REG is there to assert that an
385 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
386 // the COPY here, it will give us the value after the <sext>, not the
387 // original value of %reg1024 before <sext>.
388 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
391 MachineBasicBlock *UseMBB = UseMI->getParent();
393 // Local uses that come after the extension.
394 if (!LocalMIs.count(UseMI))
395 Uses.push_back(&UseMO);
396 } else if (ReachedBBs.count(UseMBB)) {
397 // Non-local uses where the result of the extension is used. Always
398 // replace these unless it's a PHI.
399 Uses.push_back(&UseMO);
400 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
401 // We may want to extend the live range of the extension result in order
402 // to replace these uses.
403 ExtendedUses.push_back(&UseMO);
405 // Both will be live out of the def MBB anyway. Don't extend live range of
406 // the extension result.
412 if (ExtendLife && !ExtendedUses.empty())
413 // Extend the liveness of the extension result.
414 std::copy(ExtendedUses.begin(), ExtendedUses.end(),
415 std::back_inserter(Uses));
417 // Now replace all uses.
418 bool Changed = false;
420 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
422 // Look for PHI uses of the extended result, we don't want to extend the
423 // liveness of a PHI input. It breaks all kinds of assumptions down
424 // stream. A PHI use is expected to be the kill of its source values.
425 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
427 PHIBBs.insert(UI.getParent());
429 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
430 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
431 MachineOperand *UseMO = Uses[i];
432 MachineInstr *UseMI = UseMO->getParent();
433 MachineBasicBlock *UseMBB = UseMI->getParent();
434 if (PHIBBs.count(UseMBB))
437 // About to add uses of DstReg, clear DstReg's kill flags.
439 MRI->clearKillFlags(DstReg);
440 MRI->constrainRegClass(DstReg, DstRC);
443 unsigned NewVR = MRI->createVirtualRegister(RC);
444 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
445 TII->get(TargetOpcode::COPY), NewVR)
446 .addReg(DstReg, 0, SubIdx);
447 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
449 Copy->getOperand(0).setSubReg(SubIdx);
450 Copy->getOperand(0).setIsUndef();
452 UseMO->setReg(NewVR);
461 /// optimizeCmpInstr - If the instruction is a compare and the previous
462 /// instruction it's comparing against all ready sets (or could be modified to
463 /// set) the same flag as the compare, then we can remove the comparison and use
464 /// the flag from the previous instruction.
465 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
466 MachineBasicBlock *MBB) {
467 // If this instruction is a comparison against zero and isn't comparing a
468 // physical register, we can try to optimize it.
469 unsigned SrcReg, SrcReg2;
470 int CmpMask, CmpValue;
471 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
472 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
473 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
476 // Attempt to optimize the comparison instruction.
477 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
485 /// Optimize a select instruction.
486 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
487 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
489 unsigned FalseOp = 0;
490 bool Optimizable = false;
491 SmallVector<MachineOperand, 4> Cond;
492 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
496 if (!TII->optimizeSelect(MI, LocalMIs))
498 MI->eraseFromParent();
503 /// \brief Check if a simpler conditional branch can be
505 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
506 return TII->optimizeCondBranch(MI);
509 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
510 /// share the same register file.
511 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
512 const TargetRegisterClass *DefRC,
514 const TargetRegisterClass *SrcRC,
515 unsigned SrcSubReg) {
516 // Same register class.
520 // Both operands are sub registers. Check if they share a register class.
521 unsigned SrcIdx, DefIdx;
522 if (SrcSubReg && DefSubReg)
523 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
524 SrcIdx, DefIdx) != nullptr;
525 // At most one of the register is a sub register, make it Src to avoid
526 // duplicating the test.
528 std::swap(DefSubReg, SrcSubReg);
529 std::swap(DefRC, SrcRC);
532 // One of the register is a sub register, check if we can get a superclass.
534 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
536 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
539 /// \brief Try to find the next source that share the same register file
540 /// for the value defined by \p Reg and \p SubReg.
541 /// When true is returned, \p Reg and \p SubReg are updated with the
542 /// register number and sub-register index of the new source.
543 /// \return False if no alternative sources are available. True otherwise.
544 bool PeepholeOptimizer::findNextSource(unsigned &Reg, unsigned &SubReg) {
545 // Do not try to find a new source for a physical register.
546 // So far we do not have any motivating example for doing that.
547 // Thus, instead of maintaining untested code, we will revisit that if
548 // that changes at some point.
549 if (TargetRegisterInfo::isPhysicalRegister(Reg))
552 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
553 unsigned DefSubReg = SubReg;
557 bool ShouldRewrite = false;
559 // Follow the chain of copies until we reach the top of the use-def chain
560 // or find a more suitable source.
561 ValueTracker ValTracker(Reg, DefSubReg, *MRI, !DisableAdvCopyOpt, TII);
563 unsigned CopySrcReg, CopySrcSubReg;
564 if (!ValTracker.getNextSource(CopySrcReg, CopySrcSubReg))
567 SrcSubReg = CopySrcSubReg;
569 // Do not extend the live-ranges of physical registers as they add
570 // constraints to the register allocator.
571 // Moreover, if we want to extend the live-range of a physical register,
572 // unlike SSA virtual register, we will have to check that they are not
573 // redefine before the related use.
574 if (TargetRegisterInfo::isPhysicalRegister(Src))
577 const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
579 // If this source does not incur a cross register bank copy, use it.
580 ShouldRewrite = shareSameRegisterFile(*TRI, DefRC, DefSubReg, SrcRC,
582 } while (!ShouldRewrite);
584 // If we did not find a more suitable source, there is nothing to optimize.
585 if (!ShouldRewrite || Src == Reg)
594 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
597 /// The copy-like instruction.
598 MachineInstr &CopyLike;
599 /// The index of the source being rewritten.
600 unsigned CurrentSrcIdx;
603 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
605 virtual ~CopyRewriter() {}
607 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
608 /// the related value that it affects (TrackReg, TrackSubReg).
609 /// A source is considered rewritable if its register class and the
610 /// register class of the related TrackReg may not be register
611 /// coalescer friendly. In other words, given a copy-like instruction
612 /// not all the arguments may be returned at rewritable source, since
613 /// some arguments are none to be register coalescer friendly.
615 /// Each call of this method moves the current source to the next
616 /// rewritable source.
617 /// For instance, let CopyLike be the instruction to rewrite.
618 /// CopyLike has one definition and one source:
619 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
621 /// The first call will give the first rewritable source, i.e.,
622 /// the only source this instruction has:
623 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
624 /// This source defines the whole definition, i.e.,
625 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
627 /// The second and subsequent calls will return false, has there is only one
628 /// rewritable source.
630 /// \return True if a rewritable source has been found, false otherwise.
631 /// The output arguments are valid if and only if true is returned.
632 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
634 unsigned &TrackSubReg) {
635 // If CurrentSrcIdx == 1, this means this function has already been
636 // called once. CopyLike has one defintiion and one argument, thus,
637 // there is nothing else to rewrite.
638 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
640 // This is the first call to getNextRewritableSource.
641 // Move the CurrentSrcIdx to remember that we made that call.
643 // The rewritable source is the argument.
644 const MachineOperand &MOSrc = CopyLike.getOperand(1);
645 SrcReg = MOSrc.getReg();
646 SrcSubReg = MOSrc.getSubReg();
647 // What we track are the alternative sources of the definition.
648 const MachineOperand &MODef = CopyLike.getOperand(0);
649 TrackReg = MODef.getReg();
650 TrackSubReg = MODef.getSubReg();
654 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
656 /// \return True if the rewritting was possible, false otherwise.
657 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
658 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
660 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
661 MOSrc.setReg(NewReg);
662 MOSrc.setSubReg(NewSubReg);
667 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
668 class InsertSubregRewriter : public CopyRewriter {
670 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
671 assert(MI.isInsertSubreg() && "Invalid instruction");
674 /// \brief See CopyRewriter::getNextRewritableSource.
675 /// Here CopyLike has the following form:
676 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
677 /// Src1 has the same register class has dst, hence, there is
678 /// nothing to rewrite.
679 /// Src2.src2SubIdx, may not be register coalescer friendly.
680 /// Therefore, the first call to this method returns:
681 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
682 /// (TrackReg, TrackSubReg) = (dst, subIdx).
684 /// Subsequence calls will return false.
685 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
687 unsigned &TrackSubReg) override {
688 // If we already get the only source we can rewrite, return false.
689 if (CurrentSrcIdx == 2)
691 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
693 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
694 SrcReg = MOInsertedReg.getReg();
695 SrcSubReg = MOInsertedReg.getSubReg();
696 const MachineOperand &MODef = CopyLike.getOperand(0);
698 // We want to track something that is compatible with the
699 // partial definition.
700 TrackReg = MODef.getReg();
701 if (MODef.getSubReg())
702 // Bails if we have to compose sub-register indices.
704 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
707 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
708 if (CurrentSrcIdx != 2)
710 // We are rewriting the inserted reg.
711 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
713 MO.setSubReg(NewSubReg);
718 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
719 class ExtractSubregRewriter : public CopyRewriter {
720 const TargetInstrInfo &TII;
723 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
724 : CopyRewriter(MI), TII(TII) {
725 assert(MI.isExtractSubreg() && "Invalid instruction");
728 /// \brief See CopyRewriter::getNextRewritableSource.
729 /// Here CopyLike has the following form:
730 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
731 /// There is only one rewritable source: Src.subIdx,
732 /// which defines dst.dstSubIdx.
733 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
735 unsigned &TrackSubReg) override {
736 // If we already get the only source we can rewrite, return false.
737 if (CurrentSrcIdx == 1)
739 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
741 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
742 SrcReg = MOExtractedReg.getReg();
743 // If we have to compose sub-register indices, bails out.
744 if (MOExtractedReg.getSubReg())
747 SrcSubReg = CopyLike.getOperand(2).getImm();
749 // We want to track something that is compatible with the definition.
750 const MachineOperand &MODef = CopyLike.getOperand(0);
751 TrackReg = MODef.getReg();
752 TrackSubReg = MODef.getSubReg();
756 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
757 // The only source we can rewrite is the input register.
758 if (CurrentSrcIdx != 1)
761 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
763 // If we find a source that does not require to extract something,
764 // rewrite the operation with a copy.
766 // Move the current index to an invalid position.
767 // We do not want another call to this method to be able
770 // Rewrite the operation as a COPY.
771 // Get rid of the sub-register index.
772 CopyLike.RemoveOperand(2);
773 // Morph the operation into a COPY.
774 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
777 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
782 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
783 class RegSequenceRewriter : public CopyRewriter {
785 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
786 assert(MI.isRegSequence() && "Invalid instruction");
789 /// \brief See CopyRewriter::getNextRewritableSource.
790 /// Here CopyLike has the following form:
791 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
792 /// Each call will return a different source, walking all the available
795 /// The first call returns:
796 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
797 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
799 /// The second call returns:
800 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
801 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
803 /// And so on, until all the sources have been traversed, then
804 /// it returns false.
805 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
807 unsigned &TrackSubReg) override {
808 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
810 // If this is the first call, move to the first argument.
811 if (CurrentSrcIdx == 0) {
814 // Otherwise, move to the next argument and check that it is valid.
816 if (CurrentSrcIdx >= CopyLike.getNumOperands())
819 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
820 SrcReg = MOInsertedReg.getReg();
821 // If we have to compose sub-register indices, bails out.
822 if ((SrcSubReg = MOInsertedReg.getSubReg()))
825 // We want to track something that is compatible with the related
826 // partial definition.
827 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
829 const MachineOperand &MODef = CopyLike.getOperand(0);
830 TrackReg = MODef.getReg();
831 // If we have to compose sub-registers, bails.
832 return MODef.getSubReg() == 0;
835 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
836 // We cannot rewrite out of bound operands.
837 // Moreover, rewritable sources are at odd positions.
838 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
841 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
843 MO.setSubReg(NewSubReg);
849 /// \brief Get the appropriated CopyRewriter for \p MI.
850 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
851 /// if no rewriter works for \p MI.
852 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
853 const TargetInstrInfo &TII) {
854 switch (MI.getOpcode()) {
857 case TargetOpcode::COPY:
858 return new CopyRewriter(MI);
859 case TargetOpcode::INSERT_SUBREG:
860 return new InsertSubregRewriter(MI);
861 case TargetOpcode::EXTRACT_SUBREG:
862 return new ExtractSubregRewriter(MI, TII);
863 case TargetOpcode::REG_SEQUENCE:
864 return new RegSequenceRewriter(MI);
866 llvm_unreachable(nullptr);
869 /// \brief Optimize generic copy instructions to avoid cross
870 /// register bank copy. The optimization looks through a chain of
871 /// copies and tries to find a source that has a compatible register
873 /// Two register classes are considered to be compatible if they share
874 /// the same register bank.
875 /// New copies issued by this optimization are register allocator
876 /// friendly. This optimization does not remove any copy as it may
877 /// overconstraint the register allocator, but replaces some operands
879 /// \pre isCoalescableCopy(*MI) is true.
880 /// \return True, when \p MI has been rewritten. False otherwise.
881 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
882 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
883 assert(MI->getDesc().getNumDefs() == 1 &&
884 "Coalescer can understand multiple defs?!");
885 const MachineOperand &MODef = MI->getOperand(0);
886 // Do not rewrite physical definitions.
887 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
890 bool Changed = false;
891 // Get the right rewriter for the current copy.
892 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII));
893 // If none exists, bails out.
896 // Rewrite each rewritable source.
897 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
898 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
900 unsigned NewSrc = TrackReg;
901 unsigned NewSubReg = TrackSubReg;
902 // Try to find a more suitable source.
903 // If we failed to do so, or get the actual source,
904 // move to the next source.
905 if (!findNextSource(NewSrc, NewSubReg) || SrcReg == NewSrc)
908 if (CpyRewriter->RewriteCurrentSource(NewSrc, NewSubReg)) {
909 // We may have extended the live-range of NewSrc, account for that.
910 MRI->clearKillFlags(NewSrc);
914 // TODO: We could have a clean-up method to tidy the instruction.
915 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
917 // Currently we haven't seen motivating example for that and we
918 // want to avoid untested code.
919 NumRewrittenCopies += Changed == true;
923 /// \brief Optimize copy-like instructions to create
924 /// register coalescer friendly instruction.
925 /// The optimization tries to kill-off the \p MI by looking
926 /// through a chain of copies to find a source that has a compatible
928 /// If such a source is found, it replace \p MI by a generic COPY
930 /// \pre isUncoalescableCopy(*MI) is true.
931 /// \return True, when \p MI has been optimized. In that case, \p MI has
932 /// been removed from its parent.
933 /// All COPY instructions created, are inserted in \p LocalMIs.
934 bool PeepholeOptimizer::optimizeUncoalescableCopy(
935 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
936 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
938 // Check if we can rewrite all the values defined by this instruction.
940 std::pair<TargetInstrInfo::RegSubRegPair, TargetInstrInfo::RegSubRegPair>,
942 for (const MachineOperand &MODef : MI->defs()) {
944 // We can ignore those.
947 // If a physical register is here, this is probably for a good reason.
948 // Do not rewrite that.
949 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
952 // If we do not know how to rewrite this definition, there is no point
953 // in trying to kill this instruction.
954 TargetInstrInfo::RegSubRegPair Def(MODef.getReg(), MODef.getSubReg());
955 TargetInstrInfo::RegSubRegPair Src = Def;
956 if (!findNextSource(Src.Reg, Src.SubReg))
958 RewritePairs.push_back(std::make_pair(Def, Src));
960 // The change is possible for all defs, do it.
961 for (const auto &PairDefSrc : RewritePairs) {
962 const auto &Def = PairDefSrc.first;
963 const auto &Src = PairDefSrc.second;
964 // Rewrite the "copy" in a way the register coalescer understands.
965 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
966 "We do not rewrite physical registers");
967 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
968 unsigned NewVR = MRI->createVirtualRegister(DefRC);
969 MachineInstr *NewCopy = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
970 TII->get(TargetOpcode::COPY),
971 NewVR).addReg(Src.Reg, 0, Src.SubReg);
972 NewCopy->getOperand(0).setSubReg(Def.SubReg);
974 NewCopy->getOperand(0).setIsUndef();
975 LocalMIs.insert(NewCopy);
976 MRI->replaceRegWith(Def.Reg, NewVR);
977 MRI->clearKillFlags(NewVR);
978 // We extended the lifetime of Src.
979 // Clear the kill flags to account for that.
980 MRI->clearKillFlags(Src.Reg);
983 MI->eraseFromParent();
984 ++NumUncoalescableCopies;
988 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
989 /// instruction. We only fold loads to virtual registers and the virtual
990 /// register defined has a single use.
991 bool PeepholeOptimizer::isLoadFoldable(
993 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
994 if (!MI->canFoldAsLoad() || !MI->mayLoad())
996 const MCInstrDesc &MCID = MI->getDesc();
997 if (MCID.getNumDefs() != 1)
1000 unsigned Reg = MI->getOperand(0).getReg();
1001 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1002 // loads. It should be checked when processing uses of the load, since
1003 // uses can be removed during peephole.
1004 if (!MI->getOperand(0).getSubReg() &&
1005 TargetRegisterInfo::isVirtualRegister(Reg) &&
1006 MRI->hasOneNonDBGUse(Reg)) {
1007 FoldAsLoadDefCandidates.insert(Reg);
1013 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1014 SmallSet<unsigned, 4> &ImmDefRegs,
1015 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1016 const MCInstrDesc &MCID = MI->getDesc();
1017 if (!MI->isMoveImmediate())
1019 if (MCID.getNumDefs() != 1)
1021 unsigned Reg = MI->getOperand(0).getReg();
1022 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1023 ImmDefMIs.insert(std::make_pair(Reg, MI));
1024 ImmDefRegs.insert(Reg);
1031 /// foldImmediate - Try folding register operands that are defined by move
1032 /// immediate instructions, i.e. a trivial constant folding optimization, if
1033 /// and only if the def and use are in the same BB.
1034 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1035 SmallSet<unsigned, 4> &ImmDefRegs,
1036 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1037 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1038 MachineOperand &MO = MI->getOperand(i);
1039 if (!MO.isReg() || MO.isDef())
1041 unsigned Reg = MO.getReg();
1042 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1044 if (ImmDefRegs.count(Reg) == 0)
1046 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1047 assert(II != ImmDefMIs.end());
1048 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1056 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1057 if (skipOptnoneFunction(*MF.getFunction()))
1060 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1061 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1063 if (DisablePeephole)
1066 TII = MF.getSubtarget().getInstrInfo();
1067 TRI = MF.getSubtarget().getRegisterInfo();
1068 MRI = &MF.getRegInfo();
1069 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1071 bool Changed = false;
1073 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1074 MachineBasicBlock *MBB = &*I;
1076 bool SeenMoveImm = false;
1078 // During this forward scan, at some point it needs to answer the question
1079 // "given a pointer to an MI in the current BB, is it located before or
1080 // after the current instruction".
1081 // To perform this, the following set keeps track of the MIs already seen
1082 // during the scan, if a MI is not in the set, it is assumed to be located
1083 // after. Newly created MIs have to be inserted in the set as well.
1084 SmallPtrSet<MachineInstr*, 16> LocalMIs;
1085 SmallSet<unsigned, 4> ImmDefRegs;
1086 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1087 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1089 for (MachineBasicBlock::iterator
1090 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1091 MachineInstr *MI = &*MII;
1092 // We may be erasing MI below, increment MII now.
1094 LocalMIs.insert(MI);
1096 // Skip debug values. They should not affect this peephole optimization.
1097 if (MI->isDebugValue())
1100 // If there exists an instruction which belongs to the following
1101 // categories, we will discard the load candidates.
1102 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1103 MI->isKill() || MI->isInlineAsm() ||
1104 MI->hasUnmodeledSideEffects()) {
1105 FoldAsLoadDefCandidates.clear();
1108 if (MI->mayStore() || MI->isCall())
1109 FoldAsLoadDefCandidates.clear();
1111 if ((isUncoalescableCopy(*MI) &&
1112 optimizeUncoalescableCopy(MI, LocalMIs)) ||
1113 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1114 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
1121 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1126 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1127 // MI is just rewritten.
1132 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1135 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1136 // optimizeExtInstr might have created new instructions after MI
1137 // and before the already incremented MII. Adjust MII so that the
1138 // next iteration sees the new instructions.
1142 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1145 // Check whether MI is a load candidate for folding into a later
1146 // instruction. If MI is not a candidate, check whether we can fold an
1147 // earlier load into MI.
1148 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1149 !FoldAsLoadDefCandidates.empty()) {
1150 const MCInstrDesc &MIDesc = MI->getDesc();
1151 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1153 const MachineOperand &MOp = MI->getOperand(i);
1156 unsigned FoldAsLoadDefReg = MOp.getReg();
1157 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1158 // We need to fold load after optimizeCmpInstr, since
1159 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1160 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1161 // we need it for markUsesInDebugValueAsUndef().
1162 unsigned FoldedReg = FoldAsLoadDefReg;
1163 MachineInstr *DefMI = nullptr;
1164 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1168 // Update LocalMIs since we replaced MI with FoldMI and deleted
1170 DEBUG(dbgs() << "Replacing: " << *MI);
1171 DEBUG(dbgs() << " With: " << *FoldMI);
1173 LocalMIs.erase(DefMI);
1174 LocalMIs.insert(FoldMI);
1175 MI->eraseFromParent();
1176 DefMI->eraseFromParent();
1177 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1178 FoldAsLoadDefCandidates.erase(FoldedReg);
1180 // MI is replaced with FoldMI.
1193 bool ValueTracker::getNextSourceFromCopy(unsigned &SrcReg,
1194 unsigned &SrcSubReg) {
1195 assert(Def->isCopy() && "Invalid definition");
1196 // Copy instruction are supposed to be: Def = Src.
1197 // If someone breaks this assumption, bad things will happen everywhere.
1198 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1200 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1201 // If we look for a different subreg, it means we want a subreg of src.
1202 // Bails as we do not support composing subreg yet.
1204 // Otherwise, we want the whole source.
1205 const MachineOperand &Src = Def->getOperand(1);
1206 SrcReg = Src.getReg();
1207 SrcSubReg = Src.getSubReg();
1211 bool ValueTracker::getNextSourceFromBitcast(unsigned &SrcReg,
1212 unsigned &SrcSubReg) {
1213 assert(Def->isBitcast() && "Invalid definition");
1215 // Bail if there are effects that a plain copy will not expose.
1216 if (Def->hasUnmodeledSideEffects())
1219 // Bitcasts with more than one def are not supported.
1220 if (Def->getDesc().getNumDefs() != 1)
1222 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1223 // If we look for a different subreg, it means we want a subreg of the src.
1224 // Bails as we do not support composing subreg yet.
1227 unsigned SrcIdx = Def->getNumOperands();
1228 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1230 const MachineOperand &MO = Def->getOperand(OpIdx);
1231 if (!MO.isReg() || !MO.getReg())
1233 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1234 if (SrcIdx != EndOpIdx)
1235 // Multiple sources?
1239 const MachineOperand &Src = Def->getOperand(SrcIdx);
1240 SrcReg = Src.getReg();
1241 SrcSubReg = Src.getSubReg();
1245 bool ValueTracker::getNextSourceFromRegSequence(unsigned &SrcReg,
1246 unsigned &SrcSubReg) {
1247 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1248 "Invalid definition");
1250 if (Def->getOperand(DefIdx).getSubReg())
1251 // If we are composing subreg, bails out.
1252 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1253 // This should almost never happen as the SSA property is tracked at
1254 // the register level (as opposed to the subreg level).
1258 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1259 // Def. Thus, it must not be generated.
1260 // However, some code could theoretically generates a single
1261 // Def.sub0 (i.e, not defining the other subregs) and we would
1263 // If we can ascertain (or force) that this never happens, we could
1264 // turn that into an assertion.
1268 // We could handle the REG_SEQUENCE here, but we do not want to
1269 // duplicate the code from the generic TII.
1272 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1273 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1276 // We are looking at:
1277 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1278 // Check if one of the operand defines the subreg we are interested in.
1279 for (auto &RegSeqInput : RegSeqInputRegs) {
1280 if (RegSeqInput.SubIdx == DefSubReg) {
1281 if (RegSeqInput.SubReg)
1282 // Bails if we have to compose sub registers.
1285 SrcReg = RegSeqInput.Reg;
1286 SrcSubReg = RegSeqInput.SubReg;
1291 // If the subreg we are tracking is super-defined by another subreg,
1292 // we could follow this value. However, this would require to compose
1293 // the subreg and we do not do that for now.
1297 bool ValueTracker::getNextSourceFromInsertSubreg(unsigned &SrcReg,
1298 unsigned &SrcSubReg) {
1299 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1300 "Invalid definition");
1302 if (Def->getOperand(DefIdx).getSubReg())
1303 // If we are composing subreg, bails out.
1304 // Same remark as getNextSourceFromRegSequence.
1305 // I.e., this may be turned into an assert.
1309 // We could handle the REG_SEQUENCE here, but we do not want to
1310 // duplicate the code from the generic TII.
1313 TargetInstrInfo::RegSubRegPair BaseReg;
1314 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1315 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1318 // We are looking at:
1319 // Def = INSERT_SUBREG v0, v1, sub1
1320 // There are two cases:
1321 // 1. DefSubReg == sub1, get v1.
1322 // 2. DefSubReg != sub1, the value may be available through v0.
1324 // #1 Check if the inserted register matches the required sub index.
1325 if (InsertedReg.SubIdx == DefSubReg) {
1326 SrcReg = InsertedReg.Reg;
1327 SrcSubReg = InsertedReg.SubReg;
1330 // #2 Otherwise, if the sub register we are looking for is not partial
1331 // defined by the inserted element, we can look through the main
1333 const MachineOperand &MODef = Def->getOperand(DefIdx);
1334 // If the result register (Def) and the base register (v0) do not
1335 // have the same register class or if we have to compose
1336 // subregisters, bails out.
1337 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1341 // Get the TRI and check if the inserted sub-register overlaps with the
1342 // sub-register we are tracking.
1343 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1345 (TRI->getSubRegIndexLaneMask(DefSubReg) &
1346 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1348 // At this point, the value is available in v0 via the same subreg
1350 SrcReg = BaseReg.Reg;
1351 SrcSubReg = DefSubReg;
1355 bool ValueTracker::getNextSourceFromExtractSubreg(unsigned &SrcReg,
1356 unsigned &SrcSubReg) {
1357 assert((Def->isExtractSubreg() ||
1358 Def->isExtractSubregLike()) && "Invalid definition");
1359 // We are looking at:
1360 // Def = EXTRACT_SUBREG v0, sub0
1362 // Bails if we have to compose sub registers.
1363 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1368 // We could handle the EXTRACT_SUBREG here, but we do not want to
1369 // duplicate the code from the generic TII.
1372 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1373 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1376 // Bails if we have to compose sub registers.
1377 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1378 if (ExtractSubregInputReg.SubReg)
1380 // Otherwise, the value is available in the v0.sub0.
1381 SrcReg = ExtractSubregInputReg.Reg;
1382 SrcSubReg = ExtractSubregInputReg.SubIdx;
1386 bool ValueTracker::getNextSourceFromSubregToReg(unsigned &SrcReg,
1387 unsigned &SrcSubReg) {
1388 assert(Def->isSubregToReg() && "Invalid definition");
1389 // We are looking at:
1390 // Def = SUBREG_TO_REG Imm, v0, sub0
1392 // Bails if we have to compose sub registers.
1393 // If DefSubReg != sub0, we would have to check that all the bits
1394 // we track are included in sub0 and if yes, we would have to
1395 // determine the right subreg in v0.
1396 if (DefSubReg != Def->getOperand(3).getImm())
1398 // Bails if we have to compose sub registers.
1399 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1400 if (Def->getOperand(2).getSubReg())
1403 SrcReg = Def->getOperand(2).getReg();
1404 SrcSubReg = Def->getOperand(3).getImm();
1408 bool ValueTracker::getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg) {
1409 assert(Def && "This method needs a valid definition");
1412 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1413 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1415 return getNextSourceFromCopy(SrcReg, SrcSubReg);
1416 if (Def->isBitcast())
1417 return getNextSourceFromBitcast(SrcReg, SrcSubReg);
1418 // All the remaining cases involve "complex" instructions.
1419 // Bails if we did not ask for the advanced tracking.
1420 if (!UseAdvancedTracking)
1422 if (Def->isRegSequence() || Def->isRegSequenceLike())
1423 return getNextSourceFromRegSequence(SrcReg, SrcSubReg);
1424 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
1425 return getNextSourceFromInsertSubreg(SrcReg, SrcSubReg);
1426 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1427 return getNextSourceFromExtractSubreg(SrcReg, SrcSubReg);
1428 if (Def->isSubregToReg())
1429 return getNextSourceFromSubregToReg(SrcReg, SrcSubReg);
1433 const MachineInstr *ValueTracker::getNextSource(unsigned &SrcReg,
1434 unsigned &SrcSubReg) {
1435 // If we reach a point where we cannot move up in the use-def chain,
1436 // there is nothing we can get.
1440 const MachineInstr *PrevDef = nullptr;
1441 // Try to find the next source.
1442 if (getNextSourceImpl(SrcReg, SrcSubReg)) {
1443 // Update definition, definition index, and subregister for the
1444 // next call of getNextSource.
1445 // Update the current register.
1447 // Update the return value before moving up in the use-def chain.
1449 // If we can still move up in the use-def chain, move to the next
1451 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
1452 Def = MRI.getVRegDef(Reg);
1453 DefIdx = MRI.def_begin(Reg).getOperandNo();
1454 DefSubReg = SrcSubReg;
1458 // If we end up here, this means we will not be able to find another source
1459 // for the next iteration.
1460 // Make sure any new call to getNextSource bails out early by cutting the