[PeepholeOptimizer] Take advantage of the isExtractSubreg property in the
[oota-llvm.git] / lib / CodeGen / PeepholeOptimizer.cpp
1 //===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Perform peephole optimizations on the machine code:
11 //
12 // - Optimize Extensions
13 //
14 //     Optimization of sign / zero extension instructions. It may be extended to
15 //     handle other instructions with similar properties.
16 //
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.
21 //
22 // - Optimize Comparisons
23 //
24 //     Optimization of comparison instructions. For instance, in this code:
25 //
26 //       sub r1, 1
27 //       cmp r1, 0
28 //       bz  L1
29 //
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.
33 //
34 //     Another instance, in this code:
35 //
36 //       sub r1, r3 | sub r1, imm
37 //       cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38 //       bge L1
39 //
40 //     If the branch instruction can use flag from "sub", then we can replace
41 //     "sub" with "subs" and eliminate the "cmp" instruction.
42 //
43 // - Optimize Loads:
44 //
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 
47 //     a single use.
48 //
49 // - Optimize Copies and Bitcast (more generally, target specific copies):
50 //
51 //     Rewrite copies and bitcasts to avoid cross register bank copies
52 //     when possible.
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
57 //   =>
58 //     b = copy A <-- cross-bank copy
59 //     C = copy A <-- same-bank copy
60 //
61 //     E.g., for bitcast:
62 //     b = bitcast A <-- cross-bank copy
63 //     C = bitcast b <-- cross-bank copy
64 //   =>
65 //     b = bitcast A <-- cross-bank copy
66 //     C = copy A    <-- same-bank copy
67 //===----------------------------------------------------------------------===//
68
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"
82 #include <utility>
83 using namespace llvm;
84
85 #define DEBUG_TYPE "peephole-opt"
86
87 // Optimize Extensions
88 static cl::opt<bool>
89 Aggressive("aggressive-ext-opt", cl::Hidden,
90            cl::desc("Aggressive extension optimization"));
91
92 static cl::opt<bool>
93 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
94                 cl::desc("Disable the peephole optimizer"));
95
96 static cl::opt<bool>
97 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(true),
98                   cl::desc("Disable advanced copy optimization"));
99
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");
107
108 namespace {
109   class PeepholeOptimizer : public MachineFunctionPass {
110     const TargetMachine   *TM;
111     const TargetInstrInfo *TII;
112     MachineRegisterInfo   *MRI;
113     MachineDominatorTree  *DT;  // Machine dominator tree
114
115   public:
116     static char ID; // Pass identification
117     PeepholeOptimizer() : MachineFunctionPass(ID) {
118       initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
119     }
120
121     bool runOnMachineFunction(MachineFunction &MF) override;
122
123     void getAnalysisUsage(AnalysisUsage &AU) const override {
124       AU.setPreservesCFG();
125       MachineFunctionPass::getAnalysisUsage(AU);
126       if (Aggressive) {
127         AU.addRequired<MachineDominatorTree>();
128         AU.addPreserved<MachineDominatorTree>();
129       }
130     }
131
132   private:
133     bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
134     bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
135                           SmallPtrSetImpl<MachineInstr*> &LocalMIs);
136     bool optimizeSelect(MachineInstr *MI);
137     bool optimizeCopyOrBitcast(MachineInstr *MI);
138     bool optimizeCoalescableCopy(MachineInstr *MI);
139     bool optimizeUncoalescableCopy(MachineInstr *MI,
140                                    SmallPtrSetImpl<MachineInstr *> &LocalMIs);
141     bool findNextSource(unsigned &Reg, unsigned &SubReg);
142     bool isMoveImmediate(MachineInstr *MI,
143                          SmallSet<unsigned, 4> &ImmDefRegs,
144                          DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
145     bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
146                        SmallSet<unsigned, 4> &ImmDefRegs,
147                        DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
148     bool isLoadFoldable(MachineInstr *MI,
149                         SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
150
151     /// \brief Check whether \p MI is understood by the register coalescer
152     /// but may require some rewriting.
153     bool isCoalescableCopy(const MachineInstr &MI) {
154       // SubregToRegs are not interesting, because they are already register
155       // coalescer friendly.
156       return MI.isCopy() || (!DisableAdvCopyOpt &&
157                              (MI.isRegSequence() || MI.isInsertSubreg() ||
158                               MI.isExtractSubreg()));
159     }
160
161     /// \brief Check whether \p MI is a copy like instruction that is
162     /// not recognized by the register coalescer.
163     bool isUncoalescableCopy(const MachineInstr &MI) {
164       return MI.isBitcast() || (!DisableAdvCopyOpt &&
165                                 (MI.isRegSequenceLike() ||
166                                  MI.isExtractSubregLike()));
167     }
168   };
169
170   /// \brief Helper class to track the possible sources of a value defined by
171   /// a (chain of) copy related instructions.
172   /// Given a definition (instruction and definition index), this class
173   /// follows the use-def chain to find successive suitable sources.
174   /// The given source can be used to rewrite the definition into
175   /// def = COPY src.
176   ///
177   /// For instance, let us consider the following snippet:
178   /// v0 =
179   /// v2 = INSERT_SUBREG v1, v0, sub0
180   /// def = COPY v2.sub0
181   ///
182   /// Using a ValueTracker for def = COPY v2.sub0 will give the following
183   /// suitable sources:
184   /// v2.sub0 and v0.
185   /// Then, def can be rewritten into def = COPY v0.
186   class ValueTracker {
187   private:
188     /// The current point into the use-def chain.
189     const MachineInstr *Def;
190     /// The index of the definition in Def.
191     unsigned DefIdx;
192     /// The sub register index of the definition.
193     unsigned DefSubReg;
194     /// The register where the value can be found.
195     unsigned Reg;
196     /// Specifiy whether or not the value tracking looks through
197     /// complex instructions. When this is false, the value tracker
198     /// bails on everything that is not a copy or a bitcast.
199     ///
200     /// Note: This could have been implemented as a specialized version of
201     /// the ValueTracker class but that would have complicated the code of
202     /// the users of this class.
203     bool UseAdvancedTracking;
204     /// MachineRegisterInfo used to perform tracking.
205     const MachineRegisterInfo &MRI;
206     /// Optional TargetInstrInfo used to perform some complex
207     /// tracking.
208     const TargetInstrInfo *TII;
209
210     /// \brief Dispatcher to the right underlying implementation of
211     /// getNextSource.
212     bool getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg);
213     /// \brief Specialized version of getNextSource for Copy instructions.
214     bool getNextSourceFromCopy(unsigned &SrcReg, unsigned &SrcSubReg);
215     /// \brief Specialized version of getNextSource for Bitcast instructions.
216     bool getNextSourceFromBitcast(unsigned &SrcReg, unsigned &SrcSubReg);
217     /// \brief Specialized version of getNextSource for RegSequence
218     /// instructions.
219     bool getNextSourceFromRegSequence(unsigned &SrcReg, unsigned &SrcSubReg);
220     /// \brief Specialized version of getNextSource for InsertSubreg
221     /// instructions.
222     bool getNextSourceFromInsertSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
223     /// \brief Specialized version of getNextSource for ExtractSubreg
224     /// instructions.
225     bool getNextSourceFromExtractSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
226     /// \brief Specialized version of getNextSource for SubregToReg
227     /// instructions.
228     bool getNextSourceFromSubregToReg(unsigned &SrcReg, unsigned &SrcSubReg);
229
230   public:
231     /// \brief Create a ValueTracker instance for the value defined by \p Reg.
232     /// \p DefSubReg represents the sub register index the value tracker will
233     /// track. It does not need to match the sub register index used in the
234     /// definition of \p Reg.
235     /// \p UseAdvancedTracking specifies whether or not the value tracker looks
236     /// through complex instructions. By default (false), it handles only copy
237     /// and bitcast instructions.
238     /// If \p Reg is a physical register, a value tracker constructed with
239     /// this constructor will not find any alternative source.
240     /// Indeed, when \p Reg is a physical register that constructor does not
241     /// know which definition of \p Reg it should track.
242     /// Use the next constructor to track a physical register.
243     ValueTracker(unsigned Reg, unsigned DefSubReg,
244                  const MachineRegisterInfo &MRI,
245                  bool UseAdvancedTracking = false,
246                  const TargetInstrInfo *TII = nullptr)
247         : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
248           UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
249       if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
250         Def = MRI.getVRegDef(Reg);
251         DefIdx = MRI.def_begin(Reg).getOperandNo();
252       }
253     }
254
255     /// \brief Create a ValueTracker instance for the value defined by
256     /// the pair \p MI, \p DefIdx.
257     /// Unlike the other constructor, the value tracker produced by this one
258     /// may be able to find a new source when the definition is a physical
259     /// register.
260     /// This could be useful to rewrite target specific instructions into
261     /// generic copy instructions.
262     ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
263                  const MachineRegisterInfo &MRI,
264                  bool UseAdvancedTracking = false,
265                  const TargetInstrInfo *TII = nullptr)
266         : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
267           UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
268       assert(DefIdx < Def->getDesc().getNumDefs() &&
269              Def->getOperand(DefIdx).isReg() && "Invalid definition");
270       Reg = Def->getOperand(DefIdx).getReg();
271     }
272
273     /// \brief Following the use-def chain, get the next available source
274     /// for the tracked value.
275     /// When the returned value is not nullptr, \p SrcReg gives the register
276     /// that contain the tracked value.
277     /// \note The sub register index returned in \p SrcSubReg must be used
278     /// on \p SrcReg to access the actual value.
279     /// \return Unless the returned value is nullptr (i.e., no source found),
280     /// \p SrcReg gives the register of the next source used in the returned
281     /// instruction and \p SrcSubReg the sub-register index to be used on that
282     /// source to get the tracked value. When nullptr is returned, no
283     /// alternative source has been found.
284     const MachineInstr *getNextSource(unsigned &SrcReg, unsigned &SrcSubReg);
285
286     /// \brief Get the last register where the initial value can be found.
287     /// Initially this is the register of the definition.
288     /// Then, after each successful call to getNextSource, this is the
289     /// register of the last source.
290     unsigned getReg() const { return Reg; }
291   };
292 }
293
294 char PeepholeOptimizer::ID = 0;
295 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
296 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
297                 "Peephole Optimizations", false, false)
298 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
299 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
300                 "Peephole Optimizations", false, false)
301
302 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
303 /// a single register and writes a single register and it does not modify the
304 /// source, and if the source value is preserved as a sub-register of the
305 /// result, then replace all reachable uses of the source with the subreg of the
306 /// result.
307 ///
308 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
309 /// the code. Since this code does not currently share EXTRACTs, just ignore all
310 /// debug uses.
311 bool PeepholeOptimizer::
312 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
313                  SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
314   unsigned SrcReg, DstReg, SubIdx;
315   if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
316     return false;
317
318   if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
319       TargetRegisterInfo::isPhysicalRegister(SrcReg))
320     return false;
321
322   if (MRI->hasOneNonDBGUse(SrcReg))
323     // No other uses.
324     return false;
325
326   // Ensure DstReg can get a register class that actually supports
327   // sub-registers. Don't change the class until we commit.
328   const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
329   DstRC = TM->getSubtargetImpl()->getRegisterInfo()->getSubClassWithSubReg(
330       DstRC, SubIdx);
331   if (!DstRC)
332     return false;
333
334   // The ext instr may be operating on a sub-register of SrcReg as well.
335   // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
336   // register.
337   // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
338   // SrcReg:SubIdx should be replaced.
339   bool UseSrcSubIdx =
340       TM->getSubtargetImpl()->getRegisterInfo()->getSubClassWithSubReg(
341           MRI->getRegClass(SrcReg), SubIdx) != nullptr;
342
343   // The source has other uses. See if we can replace the other uses with use of
344   // the result of the extension.
345   SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
346   for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
347     ReachedBBs.insert(UI.getParent());
348
349   // Uses that are in the same BB of uses of the result of the instruction.
350   SmallVector<MachineOperand*, 8> Uses;
351
352   // Uses that the result of the instruction can reach.
353   SmallVector<MachineOperand*, 8> ExtendedUses;
354
355   bool ExtendLife = true;
356   for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
357     MachineInstr *UseMI = UseMO.getParent();
358     if (UseMI == MI)
359       continue;
360
361     if (UseMI->isPHI()) {
362       ExtendLife = false;
363       continue;
364     }
365
366     // Only accept uses of SrcReg:SubIdx.
367     if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
368       continue;
369
370     // It's an error to translate this:
371     //
372     //    %reg1025 = <sext> %reg1024
373     //     ...
374     //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
375     //
376     // into this:
377     //
378     //    %reg1025 = <sext> %reg1024
379     //     ...
380     //    %reg1027 = COPY %reg1025:4
381     //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
382     //
383     // The problem here is that SUBREG_TO_REG is there to assert that an
384     // implicit zext occurs. It doesn't insert a zext instruction. If we allow
385     // the COPY here, it will give us the value after the <sext>, not the
386     // original value of %reg1024 before <sext>.
387     if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
388       continue;
389
390     MachineBasicBlock *UseMBB = UseMI->getParent();
391     if (UseMBB == MBB) {
392       // Local uses that come after the extension.
393       if (!LocalMIs.count(UseMI))
394         Uses.push_back(&UseMO);
395     } else if (ReachedBBs.count(UseMBB)) {
396       // Non-local uses where the result of the extension is used. Always
397       // replace these unless it's a PHI.
398       Uses.push_back(&UseMO);
399     } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
400       // We may want to extend the live range of the extension result in order
401       // to replace these uses.
402       ExtendedUses.push_back(&UseMO);
403     } else {
404       // Both will be live out of the def MBB anyway. Don't extend live range of
405       // the extension result.
406       ExtendLife = false;
407       break;
408     }
409   }
410
411   if (ExtendLife && !ExtendedUses.empty())
412     // Extend the liveness of the extension result.
413     std::copy(ExtendedUses.begin(), ExtendedUses.end(),
414               std::back_inserter(Uses));
415
416   // Now replace all uses.
417   bool Changed = false;
418   if (!Uses.empty()) {
419     SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
420
421     // Look for PHI uses of the extended result, we don't want to extend the
422     // liveness of a PHI input. It breaks all kinds of assumptions down
423     // stream. A PHI use is expected to be the kill of its source values.
424     for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
425       if (UI.isPHI())
426         PHIBBs.insert(UI.getParent());
427
428     const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
429     for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
430       MachineOperand *UseMO = Uses[i];
431       MachineInstr *UseMI = UseMO->getParent();
432       MachineBasicBlock *UseMBB = UseMI->getParent();
433       if (PHIBBs.count(UseMBB))
434         continue;
435
436       // About to add uses of DstReg, clear DstReg's kill flags.
437       if (!Changed) {
438         MRI->clearKillFlags(DstReg);
439         MRI->constrainRegClass(DstReg, DstRC);
440       }
441
442       unsigned NewVR = MRI->createVirtualRegister(RC);
443       MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
444                                    TII->get(TargetOpcode::COPY), NewVR)
445         .addReg(DstReg, 0, SubIdx);
446       // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
447       if (UseSrcSubIdx) {
448         Copy->getOperand(0).setSubReg(SubIdx);
449         Copy->getOperand(0).setIsUndef();
450       }
451       UseMO->setReg(NewVR);
452       ++NumReuse;
453       Changed = true;
454     }
455   }
456
457   return Changed;
458 }
459
460 /// optimizeCmpInstr - If the instruction is a compare and the previous
461 /// instruction it's comparing against all ready sets (or could be modified to
462 /// set) the same flag as the compare, then we can remove the comparison and use
463 /// the flag from the previous instruction.
464 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
465                                          MachineBasicBlock *MBB) {
466   // If this instruction is a comparison against zero and isn't comparing a
467   // physical register, we can try to optimize it.
468   unsigned SrcReg, SrcReg2;
469   int CmpMask, CmpValue;
470   if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
471       TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
472       (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
473     return false;
474
475   // Attempt to optimize the comparison instruction.
476   if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
477     ++NumCmps;
478     return true;
479   }
480
481   return false;
482 }
483
484 /// Optimize a select instruction.
485 bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI) {
486   unsigned TrueOp = 0;
487   unsigned FalseOp = 0;
488   bool Optimizable = false;
489   SmallVector<MachineOperand, 4> Cond;
490   if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
491     return false;
492   if (!Optimizable)
493     return false;
494   if (!TII->optimizeSelect(MI))
495     return false;
496   MI->eraseFromParent();
497   ++NumSelects;
498   return true;
499 }
500
501 /// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
502 /// share the same register file.
503 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
504                                   const TargetRegisterClass *DefRC,
505                                   unsigned DefSubReg,
506                                   const TargetRegisterClass *SrcRC,
507                                   unsigned SrcSubReg) {
508   // Same register class.
509   if (DefRC == SrcRC)
510     return true;
511
512   // Both operands are sub registers. Check if they share a register class.
513   unsigned SrcIdx, DefIdx;
514   if (SrcSubReg && DefSubReg)
515     return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
516                                       SrcIdx, DefIdx) != nullptr;
517   // At most one of the register is a sub register, make it Src to avoid
518   // duplicating the test.
519   if (!SrcSubReg) {
520     std::swap(DefSubReg, SrcSubReg);
521     std::swap(DefRC, SrcRC);
522   }
523
524   // One of the register is a sub register, check if we can get a superclass.
525   if (SrcSubReg)
526     return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
527   // Plain copy.
528   return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
529 }
530
531 /// \brief Try to find the next source that share the same register file
532 /// for the value defined by \p Reg and \p SubReg.
533 /// When true is returned, \p Reg and \p SubReg are updated with the
534 /// register number and sub-register index of the new source.
535 /// \return False if no alternative sources are available. True otherwise.
536 bool PeepholeOptimizer::findNextSource(unsigned &Reg, unsigned &SubReg) {
537   // Do not try to find a new source for a physical register.
538   // So far we do not have any motivating example for doing that.
539   // Thus, instead of maintaining untested code, we will revisit that if
540   // that changes at some point.
541   if (TargetRegisterInfo::isPhysicalRegister(Reg))
542     return false;
543
544   const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
545   unsigned DefSubReg = SubReg;
546
547   unsigned Src;
548   unsigned SrcSubReg;
549   bool ShouldRewrite = false;
550   const TargetRegisterInfo &TRI = *TM->getSubtargetImpl()->getRegisterInfo();
551
552   // Follow the chain of copies until we reach the top of the use-def chain
553   // or find a more suitable source.
554   ValueTracker ValTracker(Reg, DefSubReg, *MRI, !DisableAdvCopyOpt, TII);
555   do {
556     unsigned CopySrcReg, CopySrcSubReg;
557     if (!ValTracker.getNextSource(CopySrcReg, CopySrcSubReg))
558       break;
559     Src = CopySrcReg;
560     SrcSubReg = CopySrcSubReg;
561
562     // Do not extend the live-ranges of physical registers as they add
563     // constraints to the register allocator.
564     // Moreover, if we want to extend the live-range of a physical register,
565     // unlike SSA virtual register, we will have to check that they are not
566     // redefine before the related use.
567     if (TargetRegisterInfo::isPhysicalRegister(Src))
568       break;
569
570     const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
571
572     // If this source does not incur a cross register bank copy, use it.
573     ShouldRewrite = shareSameRegisterFile(TRI, DefRC, DefSubReg, SrcRC,
574                                           SrcSubReg);
575   } while (!ShouldRewrite);
576
577   // If we did not find a more suitable source, there is nothing to optimize.
578   if (!ShouldRewrite || Src == Reg)
579     return false;
580
581   Reg = Src;
582   SubReg = SrcSubReg;
583   return true;
584 }
585
586 namespace {
587 /// \brief Helper class to rewrite the arguments of a copy-like instruction.
588 class CopyRewriter {
589 protected:
590   /// The copy-like instruction.
591   MachineInstr &CopyLike;
592   /// The index of the source being rewritten.
593   unsigned CurrentSrcIdx;
594
595 public:
596   CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
597
598   virtual ~CopyRewriter() {}
599
600   /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
601   /// the related value that it affects (TrackReg, TrackSubReg).
602   /// A source is considered rewritable if its register class and the
603   /// register class of the related TrackReg may not be register
604   /// coalescer friendly. In other words, given a copy-like instruction
605   /// not all the arguments may be returned at rewritable source, since
606   /// some arguments are none to be register coalescer friendly.
607   ///
608   /// Each call of this method moves the current source to the next
609   /// rewritable source.
610   /// For instance, let CopyLike be the instruction to rewrite.
611   /// CopyLike has one definition and one source:
612   /// dst.dstSubIdx = CopyLike src.srcSubIdx.
613   ///
614   /// The first call will give the first rewritable source, i.e.,
615   /// the only source this instruction has:
616   /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
617   /// This source defines the whole definition, i.e.,
618   /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
619   ///
620   /// The second and subsequent calls will return false, has there is only one
621   /// rewritable source.
622   ///
623   /// \return True if a rewritable source has been found, false otherwise.
624   /// The output arguments are valid if and only if true is returned.
625   virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
626                                        unsigned &TrackReg,
627                                        unsigned &TrackSubReg) {
628     // If CurrentSrcIdx == 1, this means this function has already been
629     // called once. CopyLike has one defintiion and one argument, thus,
630     // there is nothing else to rewrite.
631     if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
632       return false;
633     // This is the first call to getNextRewritableSource.
634     // Move the CurrentSrcIdx to remember that we made that call.
635     CurrentSrcIdx = 1;
636     // The rewritable source is the argument.
637     const MachineOperand &MOSrc = CopyLike.getOperand(1);
638     SrcReg = MOSrc.getReg();
639     SrcSubReg = MOSrc.getSubReg();
640     // What we track are the alternative sources of the definition.
641     const MachineOperand &MODef = CopyLike.getOperand(0);
642     TrackReg = MODef.getReg();
643     TrackSubReg = MODef.getSubReg();
644     return true;
645   }
646
647   /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
648   /// if possible.
649   /// \return True if the rewritting was possible, false otherwise.
650   virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
651     if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
652       return false;
653     MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
654     MOSrc.setReg(NewReg);
655     MOSrc.setSubReg(NewSubReg);
656     return true;
657   }
658 };
659
660 /// \brief Specialized rewriter for INSERT_SUBREG instruction.
661 class InsertSubregRewriter : public CopyRewriter {
662 public:
663   InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
664     assert(MI.isInsertSubreg() && "Invalid instruction");
665   }
666
667   /// \brief See CopyRewriter::getNextRewritableSource.
668   /// Here CopyLike has the following form:
669   /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
670   /// Src1 has the same register class has dst, hence, there is
671   /// nothing to rewrite.
672   /// Src2.src2SubIdx, may not be register coalescer friendly.
673   /// Therefore, the first call to this method returns:
674   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
675   /// (TrackReg, TrackSubReg) = (dst, subIdx).
676   ///
677   /// Subsequence calls will return false.
678   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
679                                unsigned &TrackReg,
680                                unsigned &TrackSubReg) override {
681     // If we already get the only source we can rewrite, return false.
682     if (CurrentSrcIdx == 2)
683       return false;
684     // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
685     CurrentSrcIdx = 2;
686     const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
687     SrcReg = MOInsertedReg.getReg();
688     SrcSubReg = MOInsertedReg.getSubReg();
689     const MachineOperand &MODef = CopyLike.getOperand(0);
690
691     // We want to track something that is compatible with the
692     // partial definition.
693     TrackReg = MODef.getReg();
694     if (MODef.getSubReg())
695       // Bails if we have to compose sub-register indices.
696       return false;
697     TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
698     return true;
699   }
700   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
701     if (CurrentSrcIdx != 2)
702       return false;
703     // We are rewriting the inserted reg.
704     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
705     MO.setReg(NewReg);
706     MO.setSubReg(NewSubReg);
707     return true;
708   }
709 };
710
711 /// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
712 class ExtractSubregRewriter : public CopyRewriter {
713   const TargetInstrInfo &TII;
714
715 public:
716   ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
717       : CopyRewriter(MI), TII(TII) {
718     assert(MI.isExtractSubreg() && "Invalid instruction");
719   }
720
721   /// \brief See CopyRewriter::getNextRewritableSource.
722   /// Here CopyLike has the following form:
723   /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
724   /// There is only one rewritable source: Src.subIdx,
725   /// which defines dst.dstSubIdx.
726   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
727                                unsigned &TrackReg,
728                                unsigned &TrackSubReg) override {
729     // If we already get the only source we can rewrite, return false.
730     if (CurrentSrcIdx == 1)
731       return false;
732     // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
733     CurrentSrcIdx = 1;
734     const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
735     SrcReg = MOExtractedReg.getReg();
736     // If we have to compose sub-register indices, bails out.
737     if (MOExtractedReg.getSubReg())
738       return false;
739
740     SrcSubReg = CopyLike.getOperand(2).getImm();
741
742     // We want to track something that is compatible with the definition.
743     const MachineOperand &MODef = CopyLike.getOperand(0);
744     TrackReg = MODef.getReg();
745     TrackSubReg = MODef.getSubReg();
746     return true;
747   }
748
749   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
750     // The only source we can rewrite is the input register.
751     if (CurrentSrcIdx != 1)
752       return false;
753
754     CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
755
756     // If we find a source that does not require to extract something,
757     // rewrite the operation with a copy.
758     if (!NewSubReg) {
759       // Move the current index to an invalid position.
760       // We do not want another call to this method to be able
761       // to do any change.
762       CurrentSrcIdx = -1;
763       // Rewrite the operation as a COPY.
764       // Get rid of the sub-register index.
765       CopyLike.RemoveOperand(2);
766       // Morph the operation into a COPY.
767       CopyLike.setDesc(TII.get(TargetOpcode::COPY));
768       return true;
769     }
770     CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
771     return true;
772   }
773 };
774
775 /// \brief Specialized rewriter for REG_SEQUENCE instruction.
776 class RegSequenceRewriter : public CopyRewriter {
777 public:
778   RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
779     assert(MI.isRegSequence() && "Invalid instruction");
780   }
781
782   /// \brief See CopyRewriter::getNextRewritableSource.
783   /// Here CopyLike has the following form:
784   /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
785   /// Each call will return a different source, walking all the available
786   /// source.
787   ///
788   /// The first call returns:
789   /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
790   /// (TrackReg, TrackSubReg) = (dst, subIdx1).
791   ///
792   /// The second call returns:
793   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
794   /// (TrackReg, TrackSubReg) = (dst, subIdx2).
795   ///
796   /// And so on, until all the sources have been traversed, then
797   /// it returns false.
798   bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
799                                unsigned &TrackReg,
800                                unsigned &TrackSubReg) override {
801     // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
802
803     // If this is the first call, move to the first argument.
804     if (CurrentSrcIdx == 0) {
805       CurrentSrcIdx = 1;
806     } else {
807       // Otherwise, move to the next argument and check that it is valid.
808       CurrentSrcIdx += 2;
809       if (CurrentSrcIdx >= CopyLike.getNumOperands())
810         return false;
811     }
812     const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
813     SrcReg = MOInsertedReg.getReg();
814     // If we have to compose sub-register indices, bails out.
815     if ((SrcSubReg = MOInsertedReg.getSubReg()))
816       return false;
817
818     // We want to track something that is compatible with the related
819     // partial definition.
820     TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
821
822     const MachineOperand &MODef = CopyLike.getOperand(0);
823     TrackReg = MODef.getReg();
824     // If we have to compose sub-registers, bails.
825     return MODef.getSubReg() == 0;
826   }
827
828   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
829     // We cannot rewrite out of bound operands.
830     // Moreover, rewritable sources are at odd positions.
831     if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
832       return false;
833
834     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
835     MO.setReg(NewReg);
836     MO.setSubReg(NewSubReg);
837     return true;
838   }
839 };
840 } // End namespace.
841
842 /// \brief Get the appropriated CopyRewriter for \p MI.
843 /// \return A pointer to a dynamically allocated CopyRewriter or nullptr
844 /// if no rewriter works for \p MI.
845 static CopyRewriter *getCopyRewriter(MachineInstr &MI,
846                                      const TargetInstrInfo &TII) {
847   switch (MI.getOpcode()) {
848   default:
849     return nullptr;
850   case TargetOpcode::COPY:
851     return new CopyRewriter(MI);
852   case TargetOpcode::INSERT_SUBREG:
853     return new InsertSubregRewriter(MI);
854   case TargetOpcode::EXTRACT_SUBREG:
855     return new ExtractSubregRewriter(MI, TII);
856   case TargetOpcode::REG_SEQUENCE:
857     return new RegSequenceRewriter(MI);
858   }
859   llvm_unreachable(nullptr);
860 }
861
862 /// \brief Optimize generic copy instructions to avoid cross
863 /// register bank copy. The optimization looks through a chain of
864 /// copies and tries to find a source that has a compatible register
865 /// class.
866 /// Two register classes are considered to be compatible if they share
867 /// the same register bank.
868 /// New copies issued by this optimization are register allocator
869 /// friendly. This optimization does not remove any copy as it may
870 /// overconstraint the register allocator, but replaces some operands
871 /// when possible.
872 /// \pre isCoalescableCopy(*MI) is true.
873 /// \return True, when \p MI has been rewritten. False otherwise.
874 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
875   assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
876   assert(MI->getDesc().getNumDefs() == 1 &&
877          "Coalescer can understand multiple defs?!");
878   const MachineOperand &MODef = MI->getOperand(0);
879   // Do not rewrite physical definitions.
880   if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
881     return false;
882
883   bool Changed = false;
884   // Get the right rewriter for the current copy.
885   std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII));
886   // If none exists, bails out.
887   if (!CpyRewriter)
888     return false;
889   // Rewrite each rewritable source.
890   unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
891   while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
892                                               TrackSubReg)) {
893     unsigned NewSrc = TrackReg;
894     unsigned NewSubReg = TrackSubReg;
895     // Try to find a more suitable source.
896     // If we failed to do so, or get the actual source,
897     // move to the next source.
898     if (!findNextSource(NewSrc, NewSubReg) || SrcReg == NewSrc)
899       continue;
900     // Rewrite source.
901     Changed |= CpyRewriter->RewriteCurrentSource(NewSrc, NewSubReg);
902   }
903   // TODO: We could have a clean-up method to tidy the instruction.
904   // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
905   // => v0 = COPY v1
906   // Currently we haven't seen motivating example for that and we
907   // want to avoid untested code.
908   NumRewrittenCopies += Changed == true;
909   return Changed;
910 }
911
912 /// \brief Optimize copy-like instructions to create
913 /// register coalescer friendly instruction.
914 /// The optimization tries to kill-off the \p MI by looking
915 /// through a chain of copies to find a source that has a compatible
916 /// register class.
917 /// If such a source is found, it replace \p MI by a generic COPY
918 /// operation.
919 /// \pre isUncoalescableCopy(*MI) is true.
920 /// \return True, when \p MI has been optimized. In that case, \p MI has
921 /// been removed from its parent.
922 /// All COPY instructions created, are inserted in \p LocalMIs.
923 bool PeepholeOptimizer::optimizeUncoalescableCopy(
924     MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
925   assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
926
927   // Check if we can rewrite all the values defined by this instruction.
928   SmallVector<
929       std::pair<TargetInstrInfo::RegSubRegPair, TargetInstrInfo::RegSubRegPair>,
930       4> RewritePairs;
931   for (const MachineOperand &MODef : MI->defs()) {
932     if (MODef.isDead())
933       // We can ignore those.
934       continue;
935
936     // If a physical register is here, this is probably for a good reason.
937     // Do not rewrite that.
938     if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
939       return false;
940
941     // If we do not know how to rewrite this definition, there is no point
942     // in trying to kill this instruction.
943     TargetInstrInfo::RegSubRegPair Def(MODef.getReg(), MODef.getSubReg());
944     TargetInstrInfo::RegSubRegPair Src = Def;
945     if (!findNextSource(Src.Reg, Src.SubReg))
946       return false;
947     RewritePairs.push_back(std::make_pair(Def, Src));
948   }
949   // The change is possible for all defs, do it.
950   for (const auto &PairDefSrc : RewritePairs) {
951     const auto &Def = PairDefSrc.first;
952     const auto &Src = PairDefSrc.second;
953     // Rewrite the "copy" in a way the register coalescer understands.
954     assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
955            "We do not rewrite physical registers");
956     const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
957     unsigned NewVR = MRI->createVirtualRegister(DefRC);
958     MachineInstr *NewCopy = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
959                                     TII->get(TargetOpcode::COPY),
960                                     NewVR).addReg(Src.Reg, 0, Src.SubReg);
961     NewCopy->getOperand(0).setSubReg(Def.SubReg);
962     if (Def.SubReg)
963       NewCopy->getOperand(0).setIsUndef();
964     LocalMIs.insert(NewCopy);
965     MRI->replaceRegWith(Def.Reg, NewVR);
966     MRI->clearKillFlags(NewVR);
967     // We extended the lifetime of Src.
968     // Clear the kill flags to account for that.
969     MRI->clearKillFlags(Src.Reg);
970   }
971   // MI is now dead.
972   MI->eraseFromParent();
973   ++NumUncoalescableCopies;
974   return true;
975 }
976
977 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
978 /// instruction. We only fold loads to virtual registers and the virtual
979 /// register defined has a single use.
980 bool PeepholeOptimizer::isLoadFoldable(
981                               MachineInstr *MI,
982                               SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
983   if (!MI->canFoldAsLoad() || !MI->mayLoad())
984     return false;
985   const MCInstrDesc &MCID = MI->getDesc();
986   if (MCID.getNumDefs() != 1)
987     return false;
988
989   unsigned Reg = MI->getOperand(0).getReg();
990   // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
991   // loads. It should be checked when processing uses of the load, since
992   // uses can be removed during peephole.
993   if (!MI->getOperand(0).getSubReg() &&
994       TargetRegisterInfo::isVirtualRegister(Reg) &&
995       MRI->hasOneNonDBGUse(Reg)) {
996     FoldAsLoadDefCandidates.insert(Reg);
997     return true;
998   }
999   return false;
1000 }
1001
1002 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1003                                         SmallSet<unsigned, 4> &ImmDefRegs,
1004                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1005   const MCInstrDesc &MCID = MI->getDesc();
1006   if (!MI->isMoveImmediate())
1007     return false;
1008   if (MCID.getNumDefs() != 1)
1009     return false;
1010   unsigned Reg = MI->getOperand(0).getReg();
1011   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1012     ImmDefMIs.insert(std::make_pair(Reg, MI));
1013     ImmDefRegs.insert(Reg);
1014     return true;
1015   }
1016
1017   return false;
1018 }
1019
1020 /// foldImmediate - Try folding register operands that are defined by move
1021 /// immediate instructions, i.e. a trivial constant folding optimization, if
1022 /// and only if the def and use are in the same BB.
1023 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
1024                                       SmallSet<unsigned, 4> &ImmDefRegs,
1025                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1026   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1027     MachineOperand &MO = MI->getOperand(i);
1028     if (!MO.isReg() || MO.isDef())
1029       continue;
1030     unsigned Reg = MO.getReg();
1031     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1032       continue;
1033     if (ImmDefRegs.count(Reg) == 0)
1034       continue;
1035     DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1036     assert(II != ImmDefMIs.end());
1037     if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1038       ++NumImmFold;
1039       return true;
1040     }
1041   }
1042   return false;
1043 }
1044
1045 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1046   if (skipOptnoneFunction(*MF.getFunction()))
1047     return false;
1048
1049   DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1050   DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1051
1052   if (DisablePeephole)
1053     return false;
1054
1055   TM  = &MF.getTarget();
1056   TII = TM->getSubtargetImpl()->getInstrInfo();
1057   MRI = &MF.getRegInfo();
1058   DT  = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1059
1060   bool Changed = false;
1061
1062   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
1063     MachineBasicBlock *MBB = &*I;
1064
1065     bool SeenMoveImm = false;
1066     SmallPtrSet<MachineInstr*, 16> LocalMIs;
1067     SmallSet<unsigned, 4> ImmDefRegs;
1068     DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1069     SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1070
1071     for (MachineBasicBlock::iterator
1072            MII = I->begin(), MIE = I->end(); MII != MIE; ) {
1073       MachineInstr *MI = &*MII;
1074       // We may be erasing MI below, increment MII now.
1075       ++MII;
1076       LocalMIs.insert(MI);
1077
1078       // Skip debug values. They should not affect this peephole optimization.
1079       if (MI->isDebugValue())
1080           continue;
1081
1082       // If there exists an instruction which belongs to the following
1083       // categories, we will discard the load candidates.
1084       if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
1085           MI->isKill() || MI->isInlineAsm() ||
1086           MI->hasUnmodeledSideEffects()) {
1087         FoldAsLoadDefCandidates.clear();
1088         continue;
1089       }
1090       if (MI->mayStore() || MI->isCall())
1091         FoldAsLoadDefCandidates.clear();
1092
1093       if ((isUncoalescableCopy(*MI) &&
1094            optimizeUncoalescableCopy(MI, LocalMIs)) ||
1095           (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1096           (MI->isSelect() && optimizeSelect(MI))) {
1097         // MI is deleted.
1098         LocalMIs.erase(MI);
1099         Changed = true;
1100         continue;
1101       }
1102
1103       if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1104         // MI is just rewritten.
1105         Changed = true;
1106         continue;
1107       }
1108
1109       if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1110         SeenMoveImm = true;
1111       } else {
1112         Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
1113         // optimizeExtInstr might have created new instructions after MI
1114         // and before the already incremented MII. Adjust MII so that the
1115         // next iteration sees the new instructions.
1116         MII = MI;
1117         ++MII;
1118         if (SeenMoveImm)
1119           Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
1120       }
1121
1122       // Check whether MI is a load candidate for folding into a later
1123       // instruction. If MI is not a candidate, check whether we can fold an
1124       // earlier load into MI.
1125       if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1126           !FoldAsLoadDefCandidates.empty()) {
1127         const MCInstrDesc &MIDesc = MI->getDesc();
1128         for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1129              ++i) {
1130           const MachineOperand &MOp = MI->getOperand(i);
1131           if (!MOp.isReg())
1132             continue;
1133           unsigned FoldAsLoadDefReg = MOp.getReg();
1134           if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1135             // We need to fold load after optimizeCmpInstr, since
1136             // optimizeCmpInstr can enable folding by converting SUB to CMP.
1137             // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1138             // we need it for markUsesInDebugValueAsUndef().
1139             unsigned FoldedReg = FoldAsLoadDefReg;
1140             MachineInstr *DefMI = nullptr;
1141             MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1142                                                           FoldAsLoadDefReg,
1143                                                           DefMI);
1144             if (FoldMI) {
1145               // Update LocalMIs since we replaced MI with FoldMI and deleted
1146               // DefMI.
1147               DEBUG(dbgs() << "Replacing: " << *MI);
1148               DEBUG(dbgs() << "     With: " << *FoldMI);
1149               LocalMIs.erase(MI);
1150               LocalMIs.erase(DefMI);
1151               LocalMIs.insert(FoldMI);
1152               MI->eraseFromParent();
1153               DefMI->eraseFromParent();
1154               MRI->markUsesInDebugValueAsUndef(FoldedReg);
1155               FoldAsLoadDefCandidates.erase(FoldedReg);
1156               ++NumLoadFold;
1157               // MI is replaced with FoldMI.
1158               Changed = true;
1159               break;
1160             }
1161           }
1162         }
1163       }
1164     }
1165   }
1166
1167   return Changed;
1168 }
1169
1170 bool ValueTracker::getNextSourceFromCopy(unsigned &SrcReg,
1171                                          unsigned &SrcSubReg) {
1172   assert(Def->isCopy() && "Invalid definition");
1173   // Copy instruction are supposed to be: Def = Src.
1174   // If someone breaks this assumption, bad things will happen everywhere.
1175   assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1176
1177   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1178     // If we look for a different subreg, it means we want a subreg of src.
1179     // Bails as we do not support composing subreg yet.
1180     return false;
1181   // Otherwise, we want the whole source.
1182   const MachineOperand &Src = Def->getOperand(1);
1183   SrcReg = Src.getReg();
1184   SrcSubReg = Src.getSubReg();
1185   return true;
1186 }
1187
1188 bool ValueTracker::getNextSourceFromBitcast(unsigned &SrcReg,
1189                                             unsigned &SrcSubReg) {
1190   assert(Def->isBitcast() && "Invalid definition");
1191
1192   // Bail if there are effects that a plain copy will not expose.
1193   if (Def->hasUnmodeledSideEffects())
1194     return false;
1195
1196   // Bitcasts with more than one def are not supported.
1197   if (Def->getDesc().getNumDefs() != 1)
1198     return false;
1199   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1200     // If we look for a different subreg, it means we want a subreg of the src.
1201     // Bails as we do not support composing subreg yet.
1202     return false;
1203
1204   unsigned SrcIdx = Def->getNumOperands();
1205   for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1206        ++OpIdx) {
1207     const MachineOperand &MO = Def->getOperand(OpIdx);
1208     if (!MO.isReg() || !MO.getReg())
1209       continue;
1210     assert(!MO.isDef() && "We should have skipped all the definitions by now");
1211     if (SrcIdx != EndOpIdx)
1212       // Multiple sources?
1213       return false;
1214     SrcIdx = OpIdx;
1215   }
1216   const MachineOperand &Src = Def->getOperand(SrcIdx);
1217   SrcReg = Src.getReg();
1218   SrcSubReg = Src.getSubReg();
1219   return true;
1220 }
1221
1222 bool ValueTracker::getNextSourceFromRegSequence(unsigned &SrcReg,
1223                                                 unsigned &SrcSubReg) {
1224   assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1225          "Invalid definition");
1226
1227   if (Def->getOperand(DefIdx).getSubReg())
1228     // If we are composing subreg, bails out.
1229     // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1230     // This should almost never happen as the SSA property is tracked at
1231     // the register level (as opposed to the subreg level).
1232     // I.e.,
1233     // Def.sub0 =
1234     // Def.sub1 =
1235     // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1236     // Def. Thus, it must not be generated.
1237     // However, some code could theoretically generates a single
1238     // Def.sub0 (i.e, not defining the other subregs) and we would
1239     // have this case.
1240     // If we can ascertain (or force) that this never happens, we could
1241     // turn that into an assertion.
1242     return false;
1243
1244   if (!TII)
1245     // We could handle the REG_SEQUENCE here, but we do not want to
1246     // duplicate the code from the generic TII.
1247     return false;
1248
1249   SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1250   if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1251     return false;
1252
1253   // We are looking at:
1254   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1255   // Check if one of the operand defines the subreg we are interested in.
1256   for (auto &RegSeqInput : RegSeqInputRegs) {
1257     if (RegSeqInput.SubIdx == DefSubReg) {
1258       if (RegSeqInput.SubReg)
1259         // Bails if we have to compose sub registers.
1260         return false;
1261
1262       SrcReg = RegSeqInput.Reg;
1263       SrcSubReg = RegSeqInput.SubReg;
1264       return true;
1265     }
1266   }
1267
1268   // If the subreg we are tracking is super-defined by another subreg,
1269   // we could follow this value. However, this would require to compose
1270   // the subreg and we do not do that for now.
1271   return false;
1272 }
1273
1274 /// Extract the inputs from INSERT_SUBREG.
1275 /// INSERT_SUBREG vreg0:sub0, vreg1:sub1, sub3 would produce:
1276 /// - BaseReg: vreg0:sub0
1277 /// - InsertedReg: vreg1:sub1, sub3
1278 static void
1279 getInsertSubregInputs(const MachineInstr &MI,
1280                       TargetInstrInfo::RegSubRegPair &BaseReg,
1281                       TargetInstrInfo::RegSubRegPairAndIdx &InsertedReg) {
1282   assert(MI.isInsertSubreg() && "Instruction do not have the proper type");
1283
1284   // We are looking at:
1285   // Def = INSERT_SUBREG v0, v1, sub0.
1286   const MachineOperand &MOBaseReg = MI.getOperand(1);
1287   const MachineOperand &MOInsertedReg = MI.getOperand(2);
1288   const MachineOperand &MOSubIdx = MI.getOperand(3);
1289   assert(MOSubIdx.isImm() &&
1290          "One of the subindex of the reg_sequence is not an immediate");
1291   BaseReg.Reg = MOBaseReg.getReg();
1292   BaseReg.SubReg = MOBaseReg.getSubReg();
1293
1294   InsertedReg.Reg = MOInsertedReg.getReg();
1295   InsertedReg.SubReg = MOInsertedReg.getSubReg();
1296   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
1297 }
1298
1299 bool ValueTracker::getNextSourceFromInsertSubreg(unsigned &SrcReg,
1300                                                  unsigned &SrcSubReg) {
1301   assert(Def->isInsertSubreg() && "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.
1306     return false;
1307
1308   TargetInstrInfo::RegSubRegPair BaseReg;
1309   TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
1310   assert(DefIdx == 0 && "Invalid definition");
1311   getInsertSubregInputs(*Def, BaseReg, InsertedReg);
1312
1313   // We are looking at:
1314   // Def = INSERT_SUBREG v0, v1, sub1
1315   // There are two cases:
1316   // 1. DefSubReg == sub1, get v1.
1317   // 2. DefSubReg != sub1, the value may be available through v0.
1318
1319   // #1 Check if the inserted register matches the required sub index.
1320   if (InsertedReg.SubIdx == DefSubReg) {
1321     SrcReg = InsertedReg.Reg;
1322     SrcSubReg = InsertedReg.SubReg;
1323     return true;
1324   }
1325   // #2 Otherwise, if the sub register we are looking for is not partial
1326   // defined by the inserted element, we can look through the main
1327   // register (v0).
1328   const MachineOperand &MODef = Def->getOperand(DefIdx);
1329   // If the result register (Def) and the base register (v0) do not
1330   // have the same register class or if we have to compose
1331   // subregisters, bails out.
1332   if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1333       BaseReg.SubReg)
1334     return false;
1335
1336   // Get the TRI and check if the inserted sub-register overlaps with the
1337   // sub-register we are tracking.
1338   const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1339   if (!TRI ||
1340       (TRI->getSubRegIndexLaneMask(DefSubReg) &
1341        TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
1342     return false;
1343   // At this point, the value is available in v0 via the same subreg
1344   // we used for Def.
1345   SrcReg = BaseReg.Reg;
1346   SrcSubReg = DefSubReg;
1347   return true;
1348 }
1349
1350 bool ValueTracker::getNextSourceFromExtractSubreg(unsigned &SrcReg,
1351                                                   unsigned &SrcSubReg) {
1352   assert((Def->isExtractSubreg() ||
1353           Def->isExtractSubregLike()) && "Invalid definition");
1354   // We are looking at:
1355   // Def = EXTRACT_SUBREG v0, sub0
1356
1357   // Bails if we have to compose sub registers.
1358   // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1359   if (DefSubReg)
1360     return false;
1361
1362   if (!TII)
1363     // We could handle the EXTRACT_SUBREG here, but we do not want to
1364     // duplicate the code from the generic TII.
1365     return false;
1366
1367   TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
1368   if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1369     return false;
1370
1371   // Bails if we have to compose sub registers.
1372   // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1373   if (ExtractSubregInputReg.SubReg)
1374     return false;
1375   // Otherwise, the value is available in the v0.sub0.
1376   SrcReg = ExtractSubregInputReg.Reg;
1377   SrcSubReg = ExtractSubregInputReg.SubIdx;
1378   return true;
1379 }
1380
1381 bool ValueTracker::getNextSourceFromSubregToReg(unsigned &SrcReg,
1382                                                 unsigned &SrcSubReg) {
1383   assert(Def->isSubregToReg() && "Invalid definition");
1384   // We are looking at:
1385   // Def = SUBREG_TO_REG Imm, v0, sub0
1386
1387   // Bails if we have to compose sub registers.
1388   // If DefSubReg != sub0, we would have to check that all the bits
1389   // we track are included in sub0 and if yes, we would have to
1390   // determine the right subreg in v0.
1391   if (DefSubReg != Def->getOperand(3).getImm())
1392     return false;
1393   // Bails if we have to compose sub registers.
1394   // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1395   if (Def->getOperand(2).getSubReg())
1396     return false;
1397
1398   SrcReg = Def->getOperand(2).getReg();
1399   SrcSubReg = Def->getOperand(3).getImm();
1400   return true;
1401 }
1402
1403 bool ValueTracker::getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg) {
1404   assert(Def && "This method needs a valid definition");
1405
1406   assert(
1407       (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1408       Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1409   if (Def->isCopy())
1410     return getNextSourceFromCopy(SrcReg, SrcSubReg);
1411   if (Def->isBitcast())
1412     return getNextSourceFromBitcast(SrcReg, SrcSubReg);
1413   // All the remaining cases involve "complex" instructions.
1414   // Bails if we did not ask for the advanced tracking.
1415   if (!UseAdvancedTracking)
1416     return false;
1417   if (Def->isRegSequence() || Def->isRegSequenceLike())
1418     return getNextSourceFromRegSequence(SrcReg, SrcSubReg);
1419   if (Def->isInsertSubreg())
1420     return getNextSourceFromInsertSubreg(SrcReg, SrcSubReg);
1421   if (Def->isExtractSubreg() || Def->isExtractSubregLike())
1422     return getNextSourceFromExtractSubreg(SrcReg, SrcSubReg);
1423   if (Def->isSubregToReg())
1424     return getNextSourceFromSubregToReg(SrcReg, SrcSubReg);
1425   return false;
1426 }
1427
1428 const MachineInstr *ValueTracker::getNextSource(unsigned &SrcReg,
1429                                                 unsigned &SrcSubReg) {
1430   // If we reach a point where we cannot move up in the use-def chain,
1431   // there is nothing we can get.
1432   if (!Def)
1433     return nullptr;
1434
1435   const MachineInstr *PrevDef = nullptr;
1436   // Try to find the next source.
1437   if (getNextSourceImpl(SrcReg, SrcSubReg)) {
1438     // Update definition, definition index, and subregister for the
1439     // next call of getNextSource.
1440     // Update the current register.
1441     Reg = SrcReg;
1442     // Update the return value before moving up in the use-def chain.
1443     PrevDef = Def;
1444     // If we can still move up in the use-def chain, move to the next
1445     // defintion.
1446     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
1447       Def = MRI.getVRegDef(Reg);
1448       DefIdx = MRI.def_begin(Reg).getOperandNo();
1449       DefSubReg = SrcSubReg;
1450       return PrevDef;
1451     }
1452   }
1453   // If we end up here, this means we will not be able to find another source
1454   // for the next iteration.
1455   // Make sure any new call to getNextSource bails out early by cutting the
1456   // use-def chain.
1457   Def = nullptr;
1458   return PrevDef;
1459 }