LLVM  9.0.0svn
PeepholeOptimizer.cpp
Go to the documentation of this file.
1 //===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Perform peephole optimizations on the machine code:
10 //
11 // - Optimize Extensions
12 //
13 // Optimization of sign / zero extension instructions. It may be extended to
14 // handle other instructions with similar properties.
15 //
16 // On some targets, some instructions, e.g. X86 sign / zero extension, may
17 // leave the source value in the lower part of the result. This optimization
18 // will replace some uses of the pre-extension value with uses of the
19 // sub-register of the results.
20 //
21 // - Optimize Comparisons
22 //
23 // Optimization of comparison instructions. For instance, in this code:
24 //
25 // sub r1, 1
26 // cmp r1, 0
27 // bz L1
28 //
29 // If the "sub" instruction all ready sets (or could be modified to set) the
30 // same flag that the "cmp" instruction sets and that "bz" uses, then we can
31 // eliminate the "cmp" instruction.
32 //
33 // Another instance, in this code:
34 //
35 // sub r1, r3 | sub r1, imm
36 // cmp r3, r1 or cmp r1, r3 | cmp r1, imm
37 // bge L1
38 //
39 // If the branch instruction can use flag from "sub", then we can replace
40 // "sub" with "subs" and eliminate the "cmp" instruction.
41 //
42 // - Optimize Loads:
43 //
44 // Loads that can be folded into a later instruction. A load is foldable
45 // if it loads to virtual registers and the virtual register defined has
46 // a single use.
47 //
48 // - Optimize Copies and Bitcast (more generally, target specific copies):
49 //
50 // Rewrite copies and bitcasts to avoid cross register bank copies
51 // when possible.
52 // E.g., Consider the following example, where capital and lower
53 // letters denote different register file:
54 // b = copy A <-- cross-bank copy
55 // C = copy b <-- cross-bank copy
56 // =>
57 // b = copy A <-- cross-bank copy
58 // C = copy A <-- same-bank copy
59 //
60 // E.g., for bitcast:
61 // b = bitcast A <-- cross-bank copy
62 // C = bitcast b <-- cross-bank copy
63 // =>
64 // b = bitcast A <-- cross-bank copy
65 // C = copy A <-- same-bank copy
66 //===----------------------------------------------------------------------===//
67 
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/SmallPtrSet.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
87 #include "llvm/MC/LaneBitmask.h"
88 #include "llvm/MC/MCInstrDesc.h"
89 #include "llvm/Pass.h"
91 #include "llvm/Support/Debug.h"
94 #include <cassert>
95 #include <cstdint>
96 #include <memory>
97 #include <utility>
98 
99 using namespace llvm;
102 
103 #define DEBUG_TYPE "peephole-opt"
104 
105 // Optimize Extensions
106 static cl::opt<bool>
107 Aggressive("aggressive-ext-opt", cl::Hidden,
108  cl::desc("Aggressive extension optimization"));
109 
110 static cl::opt<bool>
111 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
112  cl::desc("Disable the peephole optimizer"));
113 
114 /// Specifiy whether or not the value tracking looks through
115 /// complex instructions. When this is true, the value tracker
116 /// bails on everything that is not a copy or a bitcast.
117 static cl::opt<bool>
118 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
119  cl::desc("Disable advanced copy optimization"));
120 
122  "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
123  cl::desc("Disable non-allocatable physical register copy optimization"));
124 
125 // Limit the number of PHI instructions to process
126 // in PeepholeOptimizer::getNextSource.
128  "rewrite-phi-limit", cl::Hidden, cl::init(10),
129  cl::desc("Limit the length of PHI chains to lookup"));
130 
131 // Limit the length of recurrence chain when evaluating the benefit of
132 // commuting operands.
134  "recurrence-chain-limit", cl::Hidden, cl::init(3),
135  cl::desc("Maximum length of recurrence chain when evaluating the benefit "
136  "of commuting operands"));
137 
138 
139 STATISTIC(NumReuse, "Number of extension results reused");
140 STATISTIC(NumCmps, "Number of compares eliminated");
141 STATISTIC(NumImmFold, "Number of move immediate folded");
142 STATISTIC(NumLoadFold, "Number of loads folded");
143 STATISTIC(NumSelects, "Number of selects optimized");
144 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
145 STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
146 STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
147 
148 namespace {
149 
150  class ValueTrackerResult;
151  class RecurrenceInstr;
152 
153  class PeepholeOptimizer : public MachineFunctionPass {
154  const TargetInstrInfo *TII;
155  const TargetRegisterInfo *TRI;
157  MachineDominatorTree *DT; // Machine dominator tree
158  MachineLoopInfo *MLI;
159 
160  public:
161  static char ID; // Pass identification
162 
163  PeepholeOptimizer() : MachineFunctionPass(ID) {
165  }
166 
167  bool runOnMachineFunction(MachineFunction &MF) override;
168 
169  void getAnalysisUsage(AnalysisUsage &AU) const override {
170  AU.setPreservesCFG();
174  if (Aggressive) {
177  }
178  }
179 
180  /// Track Def -> Use info used for rewriting copies.
182 
183  /// Sequence of instructions that formulate recurrence cycle.
184  using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
185 
186  private:
187  bool optimizeCmpInstr(MachineInstr &MI);
188  bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
190  bool optimizeSelect(MachineInstr &MI,
192  bool optimizeCondBranch(MachineInstr &MI);
193  bool optimizeCoalescableCopy(MachineInstr &MI);
194  bool optimizeUncoalescableCopy(MachineInstr &MI,
196  bool optimizeRecurrence(MachineInstr &PHI);
197  bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
198  bool isMoveImmediate(MachineInstr &MI,
199  SmallSet<unsigned, 4> &ImmDefRegs,
201  bool foldImmediate(MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
203 
204  /// Finds recurrence cycles, but only ones that formulated around
205  /// a def operand and a use operand that are tied. If there is a use
206  /// operand commutable with the tied use operand, find recurrence cycle
207  /// along that operand as well.
208  bool findTargetRecurrence(unsigned Reg,
209  const SmallSet<unsigned, 2> &TargetReg,
210  RecurrenceCycle &RC);
211 
212  /// If copy instruction \p MI is a virtual register copy, track it in
213  /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
214  /// previously seen as a copy, replace the uses of this copy with the
215  /// previously seen copy's destination register.
216  bool foldRedundantCopy(MachineInstr &MI,
217  SmallSet<unsigned, 4> &CopySrcRegs,
219 
220  /// Is the register \p Reg a non-allocatable physical register?
221  bool isNAPhysCopy(unsigned Reg);
222 
223  /// If copy instruction \p MI is a non-allocatable virtual<->physical
224  /// register copy, track it in the \p NAPhysToVirtMIs map. If this
225  /// non-allocatable physical register was previously copied to a virtual
226  /// registered and hasn't been clobbered, the virt->phys copy can be
227  /// deleted.
228  bool foldRedundantNAPhysCopy(MachineInstr &MI,
229  DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
230 
231  bool isLoadFoldable(MachineInstr &MI,
232  SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
233 
234  /// Check whether \p MI is understood by the register coalescer
235  /// but may require some rewriting.
236  bool isCoalescableCopy(const MachineInstr &MI) {
237  // SubregToRegs are not interesting, because they are already register
238  // coalescer friendly.
239  return MI.isCopy() || (!DisableAdvCopyOpt &&
240  (MI.isRegSequence() || MI.isInsertSubreg() ||
241  MI.isExtractSubreg()));
242  }
243 
244  /// Check whether \p MI is a copy like instruction that is
245  /// not recognized by the register coalescer.
246  bool isUncoalescableCopy(const MachineInstr &MI) {
247  return MI.isBitcast() ||
248  (!DisableAdvCopyOpt &&
249  (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
250  MI.isExtractSubregLike()));
251  }
252 
253  MachineInstr &rewriteSource(MachineInstr &CopyLike,
254  RegSubRegPair Def, RewriteMapTy &RewriteMap);
255  };
256 
257  /// Helper class to hold instructions that are inside recurrence cycles.
258  /// The recurrence cycle is formulated around 1) a def operand and its
259  /// tied use operand, or 2) a def operand and a use operand that is commutable
260  /// with another use operand which is tied to the def operand. In the latter
261  /// case, index of the tied use operand and the commutable use operand are
262  /// maintained with CommutePair.
263  class RecurrenceInstr {
264  public:
265  using IndexPair = std::pair<unsigned, unsigned>;
266 
267  RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
268  RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
269  : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
270 
271  MachineInstr *getMI() const { return MI; }
272  Optional<IndexPair> getCommutePair() const { return CommutePair; }
273 
274  private:
275  MachineInstr *MI;
276  Optional<IndexPair> CommutePair;
277  };
278 
279  /// Helper class to hold a reply for ValueTracker queries.
280  /// Contains the returned sources for a given search and the instructions
281  /// where the sources were tracked from.
282  class ValueTrackerResult {
283  private:
284  /// Track all sources found by one ValueTracker query.
286 
287  /// Instruction using the sources in 'RegSrcs'.
288  const MachineInstr *Inst = nullptr;
289 
290  public:
291  ValueTrackerResult() = default;
292 
293  ValueTrackerResult(unsigned Reg, unsigned SubReg) {
294  addSource(Reg, SubReg);
295  }
296 
297  bool isValid() const { return getNumSources() > 0; }
298 
299  void setInst(const MachineInstr *I) { Inst = I; }
300  const MachineInstr *getInst() const { return Inst; }
301 
302  void clear() {
303  RegSrcs.clear();
304  Inst = nullptr;
305  }
306 
307  void addSource(unsigned SrcReg, unsigned SrcSubReg) {
308  RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
309  }
310 
311  void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
312  assert(Idx < getNumSources() && "Reg pair source out of index");
313  RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
314  }
315 
316  int getNumSources() const { return RegSrcs.size(); }
317 
318  RegSubRegPair getSrc(int Idx) const {
319  return RegSrcs[Idx];
320  }
321 
322  unsigned getSrcReg(int Idx) const {
323  assert(Idx < getNumSources() && "Reg source out of index");
324  return RegSrcs[Idx].Reg;
325  }
326 
327  unsigned getSrcSubReg(int Idx) const {
328  assert(Idx < getNumSources() && "SubReg source out of index");
329  return RegSrcs[Idx].SubReg;
330  }
331 
332  bool operator==(const ValueTrackerResult &Other) {
333  if (Other.getInst() != getInst())
334  return false;
335 
336  if (Other.getNumSources() != getNumSources())
337  return false;
338 
339  for (int i = 0, e = Other.getNumSources(); i != e; ++i)
340  if (Other.getSrcReg(i) != getSrcReg(i) ||
341  Other.getSrcSubReg(i) != getSrcSubReg(i))
342  return false;
343  return true;
344  }
345  };
346 
347  /// Helper class to track the possible sources of a value defined by
348  /// a (chain of) copy related instructions.
349  /// Given a definition (instruction and definition index), this class
350  /// follows the use-def chain to find successive suitable sources.
351  /// The given source can be used to rewrite the definition into
352  /// def = COPY src.
353  ///
354  /// For instance, let us consider the following snippet:
355  /// v0 =
356  /// v2 = INSERT_SUBREG v1, v0, sub0
357  /// def = COPY v2.sub0
358  ///
359  /// Using a ValueTracker for def = COPY v2.sub0 will give the following
360  /// suitable sources:
361  /// v2.sub0 and v0.
362  /// Then, def can be rewritten into def = COPY v0.
363  class ValueTracker {
364  private:
365  /// The current point into the use-def chain.
366  const MachineInstr *Def = nullptr;
367 
368  /// The index of the definition in Def.
369  unsigned DefIdx = 0;
370 
371  /// The sub register index of the definition.
372  unsigned DefSubReg;
373 
374  /// The register where the value can be found.
375  unsigned Reg;
376 
377  /// MachineRegisterInfo used to perform tracking.
378  const MachineRegisterInfo &MRI;
379 
380  /// Optional TargetInstrInfo used to perform some complex tracking.
381  const TargetInstrInfo *TII;
382 
383  /// Dispatcher to the right underlying implementation of getNextSource.
384  ValueTrackerResult getNextSourceImpl();
385 
386  /// Specialized version of getNextSource for Copy instructions.
387  ValueTrackerResult getNextSourceFromCopy();
388 
389  /// Specialized version of getNextSource for Bitcast instructions.
390  ValueTrackerResult getNextSourceFromBitcast();
391 
392  /// Specialized version of getNextSource for RegSequence instructions.
393  ValueTrackerResult getNextSourceFromRegSequence();
394 
395  /// Specialized version of getNextSource for InsertSubreg instructions.
396  ValueTrackerResult getNextSourceFromInsertSubreg();
397 
398  /// Specialized version of getNextSource for ExtractSubreg instructions.
399  ValueTrackerResult getNextSourceFromExtractSubreg();
400 
401  /// Specialized version of getNextSource for SubregToReg instructions.
402  ValueTrackerResult getNextSourceFromSubregToReg();
403 
404  /// Specialized version of getNextSource for PHI instructions.
405  ValueTrackerResult getNextSourceFromPHI();
406 
407  public:
408  /// Create a ValueTracker instance for the value defined by \p Reg.
409  /// \p DefSubReg represents the sub register index the value tracker will
410  /// track. It does not need to match the sub register index used in the
411  /// definition of \p Reg.
412  /// If \p Reg is a physical register, a value tracker constructed with
413  /// this constructor will not find any alternative source.
414  /// Indeed, when \p Reg is a physical register that constructor does not
415  /// know which definition of \p Reg it should track.
416  /// Use the next constructor to track a physical register.
417  ValueTracker(unsigned Reg, unsigned DefSubReg,
418  const MachineRegisterInfo &MRI,
419  const TargetInstrInfo *TII = nullptr)
420  : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
422  Def = MRI.getVRegDef(Reg);
423  DefIdx = MRI.def_begin(Reg).getOperandNo();
424  }
425  }
426 
427  /// Following the use-def chain, get the next available source
428  /// for the tracked value.
429  /// \return A ValueTrackerResult containing a set of registers
430  /// and sub registers with tracked values. A ValueTrackerResult with
431  /// an empty set of registers means no source was found.
432  ValueTrackerResult getNextSource();
433  };
434 
435 } // end anonymous namespace
436 
437 char PeepholeOptimizer::ID = 0;
438 
440 
441 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
442  "Peephole Optimizations", false, false)
445 INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
446  "Peephole Optimizations", false, false)
447 
448 /// If instruction is a copy-like instruction, i.e. it reads a single register
449 /// and writes a single register and it does not modify the source, and if the
450 /// source value is preserved as a sub-register of the result, then replace all
451 /// reachable uses of the source with the subreg of the result.
452 ///
453 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
454 /// the code. Since this code does not currently share EXTRACTs, just ignore all
455 /// debug uses.
456 bool PeepholeOptimizer::
457 optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
458  SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
459  unsigned SrcReg, DstReg, SubIdx;
460  if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
461  return false;
462 
465  return false;
466 
467  if (MRI->hasOneNonDBGUse(SrcReg))
468  // No other uses.
469  return false;
470 
471  // Ensure DstReg can get a register class that actually supports
472  // sub-registers. Don't change the class until we commit.
473  const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
474  DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
475  if (!DstRC)
476  return false;
477 
478  // The ext instr may be operating on a sub-register of SrcReg as well.
479  // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
480  // register.
481  // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
482  // SrcReg:SubIdx should be replaced.
483  bool UseSrcSubIdx =
484  TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
485 
486  // The source has other uses. See if we can replace the other uses with use of
487  // the result of the extension.
489  for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
490  ReachedBBs.insert(UI.getParent());
491 
492  // Uses that are in the same BB of uses of the result of the instruction.
494 
495  // Uses that the result of the instruction can reach.
496  SmallVector<MachineOperand*, 8> ExtendedUses;
497 
498  bool ExtendLife = true;
499  for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
500  MachineInstr *UseMI = UseMO.getParent();
501  if (UseMI == &MI)
502  continue;
503 
504  if (UseMI->isPHI()) {
505  ExtendLife = false;
506  continue;
507  }
508 
509  // Only accept uses of SrcReg:SubIdx.
510  if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
511  continue;
512 
513  // It's an error to translate this:
514  //
515  // %reg1025 = <sext> %reg1024
516  // ...
517  // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
518  //
519  // into this:
520  //
521  // %reg1025 = <sext> %reg1024
522  // ...
523  // %reg1027 = COPY %reg1025:4
524  // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
525  //
526  // The problem here is that SUBREG_TO_REG is there to assert that an
527  // implicit zext occurs. It doesn't insert a zext instruction. If we allow
528  // the COPY here, it will give us the value after the <sext>, not the
529  // original value of %reg1024 before <sext>.
530  if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
531  continue;
532 
533  MachineBasicBlock *UseMBB = UseMI->getParent();
534  if (UseMBB == &MBB) {
535  // Local uses that come after the extension.
536  if (!LocalMIs.count(UseMI))
537  Uses.push_back(&UseMO);
538  } else if (ReachedBBs.count(UseMBB)) {
539  // Non-local uses where the result of the extension is used. Always
540  // replace these unless it's a PHI.
541  Uses.push_back(&UseMO);
542  } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
543  // We may want to extend the live range of the extension result in order
544  // to replace these uses.
545  ExtendedUses.push_back(&UseMO);
546  } else {
547  // Both will be live out of the def MBB anyway. Don't extend live range of
548  // the extension result.
549  ExtendLife = false;
550  break;
551  }
552  }
553 
554  if (ExtendLife && !ExtendedUses.empty())
555  // Extend the liveness of the extension result.
556  Uses.append(ExtendedUses.begin(), ExtendedUses.end());
557 
558  // Now replace all uses.
559  bool Changed = false;
560  if (!Uses.empty()) {
562 
563  // Look for PHI uses of the extended result, we don't want to extend the
564  // liveness of a PHI input. It breaks all kinds of assumptions down
565  // stream. A PHI use is expected to be the kill of its source values.
566  for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
567  if (UI.isPHI())
568  PHIBBs.insert(UI.getParent());
569 
570  const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
571  for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
572  MachineOperand *UseMO = Uses[i];
573  MachineInstr *UseMI = UseMO->getParent();
574  MachineBasicBlock *UseMBB = UseMI->getParent();
575  if (PHIBBs.count(UseMBB))
576  continue;
577 
578  // About to add uses of DstReg, clear DstReg's kill flags.
579  if (!Changed) {
580  MRI->clearKillFlags(DstReg);
581  MRI->constrainRegClass(DstReg, DstRC);
582  }
583 
584  unsigned NewVR = MRI->createVirtualRegister(RC);
585  MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
586  TII->get(TargetOpcode::COPY), NewVR)
587  .addReg(DstReg, 0, SubIdx);
588  // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
589  if (UseSrcSubIdx) {
590  Copy->getOperand(0).setSubReg(SubIdx);
591  Copy->getOperand(0).setIsUndef();
592  }
593  UseMO->setReg(NewVR);
594  ++NumReuse;
595  Changed = true;
596  }
597  }
598 
599  return Changed;
600 }
601 
602 /// If the instruction is a compare and the previous instruction it's comparing
603 /// against already sets (or could be modified to set) the same flag as the
604 /// compare, then we can remove the comparison and use the flag from the
605 /// previous instruction.
606 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) {
607  // If this instruction is a comparison against zero and isn't comparing a
608  // physical register, we can try to optimize it.
609  unsigned SrcReg, SrcReg2;
610  int CmpMask, CmpValue;
611  if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
613  (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
614  return false;
615 
616  // Attempt to optimize the comparison instruction.
617  if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
618  ++NumCmps;
619  return true;
620  }
621 
622  return false;
623 }
624 
625 /// Optimize a select instruction.
626 bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI,
628  unsigned TrueOp = 0;
629  unsigned FalseOp = 0;
630  bool Optimizable = false;
632  if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
633  return false;
634  if (!Optimizable)
635  return false;
636  if (!TII->optimizeSelect(MI, LocalMIs))
637  return false;
638  MI.eraseFromParent();
639  ++NumSelects;
640  return true;
641 }
642 
643 /// Check if a simpler conditional branch can be generated.
644 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
645  return TII->optimizeCondBranch(MI);
646 }
647 
648 /// Try to find the next source that share the same register file
649 /// for the value defined by \p Reg and \p SubReg.
650 /// When true is returned, the \p RewriteMap can be used by the client to
651 /// retrieve all Def -> Use along the way up to the next source. Any found
652 /// Use that is not itself a key for another entry, is the next source to
653 /// use. During the search for the next source, multiple sources can be found
654 /// given multiple incoming sources of a PHI instruction. In this case, we
655 /// look in each PHI source for the next source; all found next sources must
656 /// share the same register file as \p Reg and \p SubReg. The client should
657 /// then be capable to rewrite all intermediate PHIs to get the next source.
658 /// \return False if no alternative sources are available. True otherwise.
659 bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg,
660  RewriteMapTy &RewriteMap) {
661  // Do not try to find a new source for a physical register.
662  // So far we do not have any motivating example for doing that.
663  // Thus, instead of maintaining untested code, we will revisit that if
664  // that changes at some point.
665  unsigned Reg = RegSubReg.Reg;
667  return false;
668  const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
669 
671  RegSubRegPair CurSrcPair = RegSubReg;
672  SrcToLook.push_back(CurSrcPair);
673 
674  unsigned PHICount = 0;
675  do {
676  CurSrcPair = SrcToLook.pop_back_val();
677  // As explained above, do not handle physical registers
679  return false;
680 
681  ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
682 
683  // Follow the chain of copies until we find a more suitable source, a phi
684  // or have to abort.
685  while (true) {
686  ValueTrackerResult Res = ValTracker.getNextSource();
687  // Abort at the end of a chain (without finding a suitable source).
688  if (!Res.isValid())
689  return false;
690 
691  // Insert the Def -> Use entry for the recently found source.
692  ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
693  if (CurSrcRes.isValid()) {
694  assert(CurSrcRes == Res && "ValueTrackerResult found must match");
695  // An existent entry with multiple sources is a PHI cycle we must avoid.
696  // Otherwise it's an entry with a valid next source we already found.
697  if (CurSrcRes.getNumSources() > 1) {
698  LLVM_DEBUG(dbgs()
699  << "findNextSource: found PHI cycle, aborting...\n");
700  return false;
701  }
702  break;
703  }
704  RewriteMap.insert(std::make_pair(CurSrcPair, Res));
705 
706  // ValueTrackerResult usually have one source unless it's the result from
707  // a PHI instruction. Add the found PHI edges to be looked up further.
708  unsigned NumSrcs = Res.getNumSources();
709  if (NumSrcs > 1) {
710  PHICount++;
711  if (PHICount >= RewritePHILimit) {
712  LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
713  return false;
714  }
715 
716  for (unsigned i = 0; i < NumSrcs; ++i)
717  SrcToLook.push_back(Res.getSrc(i));
718  break;
719  }
720 
721  CurSrcPair = Res.getSrc(0);
722  // Do not extend the live-ranges of physical registers as they add
723  // constraints to the register allocator. Moreover, if we want to extend
724  // the live-range of a physical register, unlike SSA virtual register,
725  // we will have to check that they aren't redefine before the related use.
727  return false;
728 
729  // Keep following the chain if the value isn't any better yet.
730  const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
731  if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC,
732  CurSrcPair.SubReg))
733  continue;
734 
735  // We currently cannot deal with subreg operands on PHI instructions
736  // (see insertPHI()).
737  if (PHICount > 0 && CurSrcPair.SubReg != 0)
738  continue;
739 
740  // We found a suitable source, and are done with this chain.
741  break;
742  }
743  } while (!SrcToLook.empty());
744 
745  // If we did not find a more suitable source, there is nothing to optimize.
746  return CurSrcPair.Reg != Reg;
747 }
748 
749 /// Insert a PHI instruction with incoming edges \p SrcRegs that are
750 /// guaranteed to have the same register class. This is necessary whenever we
751 /// successfully traverse a PHI instruction and find suitable sources coming
752 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
753 /// suitable to be used in a new COPY instruction.
754 static MachineInstr &
756  const SmallVectorImpl<RegSubRegPair> &SrcRegs,
757  MachineInstr &OrigPHI) {
758  assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
759 
760  const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
761  // NewRC is only correct if no subregisters are involved. findNextSource()
762  // should have rejected those cases already.
763  assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
764  unsigned NewVR = MRI.createVirtualRegister(NewRC);
765  MachineBasicBlock *MBB = OrigPHI.getParent();
766  MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
767  TII.get(TargetOpcode::PHI), NewVR);
768 
769  unsigned MBBOpIdx = 2;
770  for (const RegSubRegPair &RegPair : SrcRegs) {
771  MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
772  MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
773  // Since we're extended the lifetime of RegPair.Reg, clear the
774  // kill flags to account for that and make RegPair.Reg reaches
775  // the new PHI.
776  MRI.clearKillFlags(RegPair.Reg);
777  MBBOpIdx += 2;
778  }
779 
780  return *MIB;
781 }
782 
783 namespace {
784 
785 /// Interface to query instructions amenable to copy rewriting.
786 class Rewriter {
787 protected:
788  MachineInstr &CopyLike;
789  unsigned CurrentSrcIdx = 0; ///< The index of the source being rewritten.
790 public:
791  Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
792  virtual ~Rewriter() {}
793 
794  /// Get the next rewritable source (SrcReg, SrcSubReg) and
795  /// the related value that it affects (DstReg, DstSubReg).
796  /// A source is considered rewritable if its register class and the
797  /// register class of the related DstReg may not be register
798  /// coalescer friendly. In other words, given a copy-like instruction
799  /// not all the arguments may be returned at rewritable source, since
800  /// some arguments are none to be register coalescer friendly.
801  ///
802  /// Each call of this method moves the current source to the next
803  /// rewritable source.
804  /// For instance, let CopyLike be the instruction to rewrite.
805  /// CopyLike has one definition and one source:
806  /// dst.dstSubIdx = CopyLike src.srcSubIdx.
807  ///
808  /// The first call will give the first rewritable source, i.e.,
809  /// the only source this instruction has:
810  /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
811  /// This source defines the whole definition, i.e.,
812  /// (DstReg, DstSubReg) = (dst, dstSubIdx).
813  ///
814  /// The second and subsequent calls will return false, as there is only one
815  /// rewritable source.
816  ///
817  /// \return True if a rewritable source has been found, false otherwise.
818  /// The output arguments are valid if and only if true is returned.
819  virtual bool getNextRewritableSource(RegSubRegPair &Src,
820  RegSubRegPair &Dst) = 0;
821 
822  /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
823  /// \return True if the rewriting was possible, false otherwise.
824  virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) = 0;
825 };
826 
827 /// Rewriter for COPY instructions.
828 class CopyRewriter : public Rewriter {
829 public:
830  CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
831  assert(MI.isCopy() && "Expected copy instruction");
832  }
833  virtual ~CopyRewriter() = default;
834 
835  bool getNextRewritableSource(RegSubRegPair &Src,
836  RegSubRegPair &Dst) override {
837  // CurrentSrcIdx > 0 means this function has already been called.
838  if (CurrentSrcIdx > 0)
839  return false;
840  // This is the first call to getNextRewritableSource.
841  // Move the CurrentSrcIdx to remember that we made that call.
842  CurrentSrcIdx = 1;
843  // The rewritable source is the argument.
844  const MachineOperand &MOSrc = CopyLike.getOperand(1);
845  Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
846  // What we track are the alternative sources of the definition.
847  const MachineOperand &MODef = CopyLike.getOperand(0);
848  Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
849  return true;
850  }
851 
852  bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
853  if (CurrentSrcIdx != 1)
854  return false;
855  MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
856  MOSrc.setReg(NewReg);
857  MOSrc.setSubReg(NewSubReg);
858  return true;
859  }
860 };
861 
862 /// Helper class to rewrite uncoalescable copy like instructions
863 /// into new COPY (coalescable friendly) instructions.
864 class UncoalescableRewriter : public Rewriter {
865  unsigned NumDefs; ///< Number of defs in the bitcast.
866 
867 public:
868  UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
869  NumDefs = MI.getDesc().getNumDefs();
870  }
871 
872  /// \see See Rewriter::getNextRewritableSource()
873  /// All such sources need to be considered rewritable in order to
874  /// rewrite a uncoalescable copy-like instruction. This method return
875  /// each definition that must be checked if rewritable.
876  bool getNextRewritableSource(RegSubRegPair &Src,
877  RegSubRegPair &Dst) override {
878  // Find the next non-dead definition and continue from there.
879  if (CurrentSrcIdx == NumDefs)
880  return false;
881 
882  while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
883  ++CurrentSrcIdx;
884  if (CurrentSrcIdx == NumDefs)
885  return false;
886  }
887 
888  // What we track are the alternative sources of the definition.
889  Src = RegSubRegPair(0, 0);
890  const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
891  Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
892 
893  CurrentSrcIdx++;
894  return true;
895  }
896 
897  bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
898  return false;
899  }
900 };
901 
902 /// Specialized rewriter for INSERT_SUBREG instruction.
903 class InsertSubregRewriter : public Rewriter {
904 public:
905  InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
906  assert(MI.isInsertSubreg() && "Invalid instruction");
907  }
908 
909  /// \see See Rewriter::getNextRewritableSource()
910  /// Here CopyLike has the following form:
911  /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
912  /// Src1 has the same register class has dst, hence, there is
913  /// nothing to rewrite.
914  /// Src2.src2SubIdx, may not be register coalescer friendly.
915  /// Therefore, the first call to this method returns:
916  /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
917  /// (DstReg, DstSubReg) = (dst, subIdx).
918  ///
919  /// Subsequence calls will return false.
920  bool getNextRewritableSource(RegSubRegPair &Src,
921  RegSubRegPair &Dst) override {
922  // If we already get the only source we can rewrite, return false.
923  if (CurrentSrcIdx == 2)
924  return false;
925  // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
926  CurrentSrcIdx = 2;
927  const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
928  Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
929  const MachineOperand &MODef = CopyLike.getOperand(0);
930 
931  // We want to track something that is compatible with the
932  // partial definition.
933  if (MODef.getSubReg())
934  // Bail if we have to compose sub-register indices.
935  return false;
936  Dst = RegSubRegPair(MODef.getReg(),
937  (unsigned)CopyLike.getOperand(3).getImm());
938  return true;
939  }
940 
941  bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
942  if (CurrentSrcIdx != 2)
943  return false;
944  // We are rewriting the inserted reg.
945  MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
946  MO.setReg(NewReg);
947  MO.setSubReg(NewSubReg);
948  return true;
949  }
950 };
951 
952 /// Specialized rewriter for EXTRACT_SUBREG instruction.
953 class ExtractSubregRewriter : public Rewriter {
954  const TargetInstrInfo &TII;
955 
956 public:
957  ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
958  : Rewriter(MI), TII(TII) {
959  assert(MI.isExtractSubreg() && "Invalid instruction");
960  }
961 
962  /// \see Rewriter::getNextRewritableSource()
963  /// Here CopyLike has the following form:
964  /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
965  /// There is only one rewritable source: Src.subIdx,
966  /// which defines dst.dstSubIdx.
967  bool getNextRewritableSource(RegSubRegPair &Src,
968  RegSubRegPair &Dst) override {
969  // If we already get the only source we can rewrite, return false.
970  if (CurrentSrcIdx == 1)
971  return false;
972  // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
973  CurrentSrcIdx = 1;
974  const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
975  // If we have to compose sub-register indices, bail out.
976  if (MOExtractedReg.getSubReg())
977  return false;
978 
979  Src = RegSubRegPair(MOExtractedReg.getReg(),
980  CopyLike.getOperand(2).getImm());
981 
982  // We want to track something that is compatible with the definition.
983  const MachineOperand &MODef = CopyLike.getOperand(0);
984  Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
985  return true;
986  }
987 
988  bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
989  // The only source we can rewrite is the input register.
990  if (CurrentSrcIdx != 1)
991  return false;
992 
993  CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
994 
995  // If we find a source that does not require to extract something,
996  // rewrite the operation with a copy.
997  if (!NewSubReg) {
998  // Move the current index to an invalid position.
999  // We do not want another call to this method to be able
1000  // to do any change.
1001  CurrentSrcIdx = -1;
1002  // Rewrite the operation as a COPY.
1003  // Get rid of the sub-register index.
1004  CopyLike.RemoveOperand(2);
1005  // Morph the operation into a COPY.
1006  CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1007  return true;
1008  }
1009  CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1010  return true;
1011  }
1012 };
1013 
1014 /// Specialized rewriter for REG_SEQUENCE instruction.
1015 class RegSequenceRewriter : public Rewriter {
1016 public:
1017  RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
1018  assert(MI.isRegSequence() && "Invalid instruction");
1019  }
1020 
1021  /// \see Rewriter::getNextRewritableSource()
1022  /// Here CopyLike has the following form:
1023  /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1024  /// Each call will return a different source, walking all the available
1025  /// source.
1026  ///
1027  /// The first call returns:
1028  /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1029  /// (DstReg, DstSubReg) = (dst, subIdx1).
1030  ///
1031  /// The second call returns:
1032  /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1033  /// (DstReg, DstSubReg) = (dst, subIdx2).
1034  ///
1035  /// And so on, until all the sources have been traversed, then
1036  /// it returns false.
1037  bool getNextRewritableSource(RegSubRegPair &Src,
1038  RegSubRegPair &Dst) override {
1039  // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1040 
1041  // If this is the first call, move to the first argument.
1042  if (CurrentSrcIdx == 0) {
1043  CurrentSrcIdx = 1;
1044  } else {
1045  // Otherwise, move to the next argument and check that it is valid.
1046  CurrentSrcIdx += 2;
1047  if (CurrentSrcIdx >= CopyLike.getNumOperands())
1048  return false;
1049  }
1050  const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1051  Src.Reg = MOInsertedReg.getReg();
1052  // If we have to compose sub-register indices, bail out.
1053  if ((Src.SubReg = MOInsertedReg.getSubReg()))
1054  return false;
1055 
1056  // We want to track something that is compatible with the related
1057  // partial definition.
1058  Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1059 
1060  const MachineOperand &MODef = CopyLike.getOperand(0);
1061  Dst.Reg = MODef.getReg();
1062  // If we have to compose sub-registers, bail.
1063  return MODef.getSubReg() == 0;
1064  }
1065 
1066  bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1067  // We cannot rewrite out of bound operands.
1068  // Moreover, rewritable sources are at odd positions.
1069  if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1070  return false;
1071 
1072  MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1073  MO.setReg(NewReg);
1074  MO.setSubReg(NewSubReg);
1075  return true;
1076  }
1077 };
1078 
1079 } // end anonymous namespace
1080 
1081 /// Get the appropriated Rewriter for \p MI.
1082 /// \return A pointer to a dynamically allocated Rewriter or nullptr if no
1083 /// rewriter works for \p MI.
1085  // Handle uncoalescable copy-like instructions.
1086  if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1087  MI.isExtractSubregLike())
1088  return new UncoalescableRewriter(MI);
1089 
1090  switch (MI.getOpcode()) {
1091  default:
1092  return nullptr;
1093  case TargetOpcode::COPY:
1094  return new CopyRewriter(MI);
1095  case TargetOpcode::INSERT_SUBREG:
1096  return new InsertSubregRewriter(MI);
1097  case TargetOpcode::EXTRACT_SUBREG:
1098  return new ExtractSubregRewriter(MI, TII);
1099  case TargetOpcode::REG_SEQUENCE:
1100  return new RegSequenceRewriter(MI);
1101  }
1102 }
1103 
1104 /// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
1105 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
1106 /// multiple sources for a given \p Def are found along the way, we found a
1107 /// PHI instructions that needs to be rewritten.
1108 /// TODO: HandleMultipleSources should be removed once we test PHI handling
1109 /// with coalescable copies.
1110 static RegSubRegPair
1112  RegSubRegPair Def,
1113  const PeepholeOptimizer::RewriteMapTy &RewriteMap,
1114  bool HandleMultipleSources = true) {
1115  RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
1116  while (true) {
1117  ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
1118  // If there are no entries on the map, LookupSrc is the new source.
1119  if (!Res.isValid())
1120  return LookupSrc;
1121 
1122  // There's only one source for this definition, keep searching...
1123  unsigned NumSrcs = Res.getNumSources();
1124  if (NumSrcs == 1) {
1125  LookupSrc.Reg = Res.getSrcReg(0);
1126  LookupSrc.SubReg = Res.getSrcSubReg(0);
1127  continue;
1128  }
1129 
1130  // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1131  if (!HandleMultipleSources)
1132  break;
1133 
1134  // Multiple sources, recurse into each source to find a new source
1135  // for it. Then, rewrite the PHI accordingly to its new edges.
1136  SmallVector<RegSubRegPair, 4> NewPHISrcs;
1137  for (unsigned i = 0; i < NumSrcs; ++i) {
1138  RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
1139  NewPHISrcs.push_back(
1140  getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
1141  }
1142 
1143  // Build the new PHI node and return its def register as the new source.
1144  MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
1145  MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
1146  LLVM_DEBUG(dbgs() << "-- getNewSource\n");
1147  LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI);
1148  LLVM_DEBUG(dbgs() << " With: " << NewPHI);
1149  const MachineOperand &MODef = NewPHI.getOperand(0);
1150  return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
1151  }
1152 
1153  return RegSubRegPair(0, 0);
1154 }
1155 
1156 /// Optimize generic copy instructions to avoid cross register bank copy.
1157 /// The optimization looks through a chain of copies and tries to find a source
1158 /// that has a compatible register class.
1159 /// Two register classes are considered to be compatible if they share the same
1160 /// register bank.
1161 /// New copies issued by this optimization are register allocator
1162 /// friendly. This optimization does not remove any copy as it may
1163 /// overconstrain the register allocator, but replaces some operands
1164 /// when possible.
1165 /// \pre isCoalescableCopy(*MI) is true.
1166 /// \return True, when \p MI has been rewritten. False otherwise.
1167 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
1168  assert(isCoalescableCopy(MI) && "Invalid argument");
1169  assert(MI.getDesc().getNumDefs() == 1 &&
1170  "Coalescer can understand multiple defs?!");
1171  const MachineOperand &MODef = MI.getOperand(0);
1172  // Do not rewrite physical definitions.
1173  if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1174  return false;
1175 
1176  bool Changed = false;
1177  // Get the right rewriter for the current copy.
1178  std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII));
1179  // If none exists, bail out.
1180  if (!CpyRewriter)
1181  return false;
1182  // Rewrite each rewritable source.
1183  RegSubRegPair Src;
1184  RegSubRegPair TrackPair;
1185  while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) {
1186  // Keep track of PHI nodes and its incoming edges when looking for sources.
1187  RewriteMapTy RewriteMap;
1188  // Try to find a more suitable source. If we failed to do so, or get the
1189  // actual source, move to the next source.
1190  if (!findNextSource(TrackPair, RewriteMap))
1191  continue;
1192 
1193  // Get the new source to rewrite. TODO: Only enable handling of multiple
1194  // sources (PHIs) once we have a motivating example and testcases for it.
1195  RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
1196  /*HandleMultipleSources=*/false);
1197  if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0)
1198  continue;
1199 
1200  // Rewrite source.
1201  if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1202  // We may have extended the live-range of NewSrc, account for that.
1203  MRI->clearKillFlags(NewSrc.Reg);
1204  Changed = true;
1205  }
1206  }
1207  // TODO: We could have a clean-up method to tidy the instruction.
1208  // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1209  // => v0 = COPY v1
1210  // Currently we haven't seen motivating example for that and we
1211  // want to avoid untested code.
1212  NumRewrittenCopies += Changed;
1213  return Changed;
1214 }
1215 
1216 /// Rewrite the source found through \p Def, by using the \p RewriteMap
1217 /// and create a new COPY instruction. More info about RewriteMap in
1218 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1219 /// Uncoalescable copies, since they are copy like instructions that aren't
1220 /// recognized by the register allocator.
1221 MachineInstr &
1222 PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
1223  RegSubRegPair Def, RewriteMapTy &RewriteMap) {
1225  "We do not rewrite physical registers");
1226 
1227  // Find the new source to use in the COPY rewrite.
1228  RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
1229 
1230  // Insert the COPY.
1231  const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1232  unsigned NewVReg = MRI->createVirtualRegister(DefRC);
1233 
1234  MachineInstr *NewCopy =
1235  BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1236  TII->get(TargetOpcode::COPY), NewVReg)
1237  .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
1238 
1239  if (Def.SubReg) {
1240  NewCopy->getOperand(0).setSubReg(Def.SubReg);
1241  NewCopy->getOperand(0).setIsUndef();
1242  }
1243 
1244  LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
1245  LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike);
1246  LLVM_DEBUG(dbgs() << " With: " << *NewCopy);
1247  MRI->replaceRegWith(Def.Reg, NewVReg);
1248  MRI->clearKillFlags(NewVReg);
1249 
1250  // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1251  // account for that.
1252  MRI->clearKillFlags(NewSrc.Reg);
1253 
1254  return *NewCopy;
1255 }
1256 
1257 /// Optimize copy-like instructions to create
1258 /// register coalescer friendly instruction.
1259 /// The optimization tries to kill-off the \p MI by looking
1260 /// through a chain of copies to find a source that has a compatible
1261 /// register class.
1262 /// If such a source is found, it replace \p MI by a generic COPY
1263 /// operation.
1264 /// \pre isUncoalescableCopy(*MI) is true.
1265 /// \return True, when \p MI has been optimized. In that case, \p MI has
1266 /// been removed from its parent.
1267 /// All COPY instructions created, are inserted in \p LocalMIs.
1268 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1270  assert(isUncoalescableCopy(MI) && "Invalid argument");
1271  UncoalescableRewriter CpyRewriter(MI);
1272 
1273  // Rewrite each rewritable source by generating new COPYs. This works
1274  // differently from optimizeCoalescableCopy since it first makes sure that all
1275  // definitions can be rewritten.
1276  RewriteMapTy RewriteMap;
1277  RegSubRegPair Src;
1279  SmallVector<RegSubRegPair, 4> RewritePairs;
1280  while (CpyRewriter.getNextRewritableSource(Src, Def)) {
1281  // If a physical register is here, this is probably for a good reason.
1282  // Do not rewrite that.
1284  return false;
1285 
1286  // If we do not know how to rewrite this definition, there is no point
1287  // in trying to kill this instruction.
1288  if (!findNextSource(Def, RewriteMap))
1289  return false;
1290 
1291  RewritePairs.push_back(Def);
1292  }
1293 
1294  // The change is possible for all defs, do it.
1295  for (const RegSubRegPair &Def : RewritePairs) {
1296  // Rewrite the "copy" in a way the register coalescer understands.
1297  MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
1298  LocalMIs.insert(&NewCopy);
1299  }
1300 
1301  // MI is now dead.
1302  MI.eraseFromParent();
1303  ++NumUncoalescableCopies;
1304  return true;
1305 }
1306 
1307 /// Check whether MI is a candidate for folding into a later instruction.
1308 /// We only fold loads to virtual registers and the virtual register defined
1309 /// has a single use.
1310 bool PeepholeOptimizer::isLoadFoldable(
1311  MachineInstr &MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1312  if (!MI.canFoldAsLoad() || !MI.mayLoad())
1313  return false;
1314  const MCInstrDesc &MCID = MI.getDesc();
1315  if (MCID.getNumDefs() != 1)
1316  return false;
1317 
1318  unsigned Reg = MI.getOperand(0).getReg();
1319  // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
1320  // loads. It should be checked when processing uses of the load, since
1321  // uses can be removed during peephole.
1322  if (!MI.getOperand(0).getSubReg() &&
1324  MRI->hasOneNonDBGUse(Reg)) {
1325  FoldAsLoadDefCandidates.insert(Reg);
1326  return true;
1327  }
1328  return false;
1329 }
1330 
1331 bool PeepholeOptimizer::isMoveImmediate(
1332  MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
1334  const MCInstrDesc &MCID = MI.getDesc();
1335  if (!MI.isMoveImmediate())
1336  return false;
1337  if (MCID.getNumDefs() != 1)
1338  return false;
1339  unsigned Reg = MI.getOperand(0).getReg();
1341  ImmDefMIs.insert(std::make_pair(Reg, &MI));
1342  ImmDefRegs.insert(Reg);
1343  return true;
1344  }
1345 
1346  return false;
1347 }
1348 
1349 /// Try folding register operands that are defined by move immediate
1350 /// instructions, i.e. a trivial constant folding optimization, if
1351 /// and only if the def and use are in the same BB.
1352 bool PeepholeOptimizer::foldImmediate(MachineInstr &MI,
1353  SmallSet<unsigned, 4> &ImmDefRegs,
1355  for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1356  MachineOperand &MO = MI.getOperand(i);
1357  if (!MO.isReg() || MO.isDef())
1358  continue;
1359  // Ignore dead implicit defs.
1360  if (MO.isImplicit() && MO.isDead())
1361  continue;
1362  unsigned Reg = MO.getReg();
1364  continue;
1365  if (ImmDefRegs.count(Reg) == 0)
1366  continue;
1368  assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
1369  if (TII->FoldImmediate(MI, *II->second, Reg, MRI)) {
1370  ++NumImmFold;
1371  return true;
1372  }
1373  }
1374  return false;
1375 }
1376 
1377 // FIXME: This is very simple and misses some cases which should be handled when
1378 // motivating examples are found.
1379 //
1380 // The copy rewriting logic should look at uses as well as defs and be able to
1381 // eliminate copies across blocks.
1382 //
1383 // Later copies that are subregister extracts will also not be eliminated since
1384 // only the first copy is considered.
1385 //
1386 // e.g.
1387 // %1 = COPY %0
1388 // %2 = COPY %0:sub1
1389 //
1390 // Should replace %2 uses with %1:sub1
1391 bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI,
1392  SmallSet<unsigned, 4> &CopySrcRegs,
1394  assert(MI.isCopy() && "expected a COPY machine instruction");
1395 
1396  unsigned SrcReg = MI.getOperand(1).getReg();
1398  return false;
1399 
1400  unsigned DstReg = MI.getOperand(0).getReg();
1402  return false;
1403 
1404  if (CopySrcRegs.insert(SrcReg).second) {
1405  // First copy of this reg seen.
1406  CopyMIs.insert(std::make_pair(SrcReg, &MI));
1407  return false;
1408  }
1409 
1410  MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1411 
1412  unsigned SrcSubReg = MI.getOperand(1).getSubReg();
1413  unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1414 
1415  // Can't replace different subregister extracts.
1416  if (SrcSubReg != PrevSrcSubReg)
1417  return false;
1418 
1419  unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1420 
1421  // Only replace if the copy register class is the same.
1422  //
1423  // TODO: If we have multiple copies to different register classes, we may want
1424  // to track multiple copies of the same source register.
1425  if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1426  return false;
1427 
1428  MRI->replaceRegWith(DstReg, PrevDstReg);
1429 
1430  // Lifetime of the previous copy has been extended.
1431  MRI->clearKillFlags(PrevDstReg);
1432  return true;
1433 }
1434 
1435 bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1437  !MRI->isAllocatable(Reg);
1438 }
1439 
1440 bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1441  MachineInstr &MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1442  assert(MI.isCopy() && "expected a COPY machine instruction");
1443 
1445  return false;
1446 
1447  unsigned DstReg = MI.getOperand(0).getReg();
1448  unsigned SrcReg = MI.getOperand(1).getReg();
1449  if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) {
1450  // %vreg = COPY %physreg
1451  // Avoid using a datastructure which can track multiple live non-allocatable
1452  // phys->virt copies since LLVM doesn't seem to do this.
1453  NAPhysToVirtMIs.insert({SrcReg, &MI});
1454  return false;
1455  }
1456 
1457  if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1458  return false;
1459 
1460  // %physreg = COPY %vreg
1461  auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1462  if (PrevCopy == NAPhysToVirtMIs.end()) {
1463  // We can't remove the copy: there was an intervening clobber of the
1464  // non-allocatable physical register after the copy to virtual.
1465  LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
1466  << MI);
1467  return false;
1468  }
1469 
1470  unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1471  if (PrevDstReg == SrcReg) {
1472  // Remove the virt->phys copy: we saw the virtual register definition, and
1473  // the non-allocatable physical register's state hasn't changed since then.
1474  LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
1475  ++NumNAPhysCopies;
1476  return true;
1477  }
1478 
1479  // Potential missed optimization opportunity: we saw a different virtual
1480  // register get a copy of the non-allocatable physical register, and we only
1481  // track one such copy. Avoid getting confused by this new non-allocatable
1482  // physical register definition, and remove it from the tracked copies.
1483  LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
1484  NAPhysToVirtMIs.erase(PrevCopy);
1485  return false;
1486 }
1487 
1488 /// \bried Returns true if \p MO is a virtual register operand.
1490  if (!MO.isReg())
1491  return false;
1493 }
1494 
1495 bool PeepholeOptimizer::findTargetRecurrence(
1496  unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs,
1497  RecurrenceCycle &RC) {
1498  // Recurrence found if Reg is in TargetRegs.
1499  if (TargetRegs.count(Reg))
1500  return true;
1501 
1502  // TODO: Curerntly, we only allow the last instruction of the recurrence
1503  // cycle (the instruction that feeds the PHI instruction) to have more than
1504  // one uses to guarantee that commuting operands does not tie registers
1505  // with overlapping live range. Once we have actual live range info of
1506  // each register, this constraint can be relaxed.
1507  if (!MRI->hasOneNonDBGUse(Reg))
1508  return false;
1509 
1510  // Give up if the reccurrence chain length is longer than the limit.
1511  if (RC.size() >= MaxRecurrenceChain)
1512  return false;
1513 
1514  MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1515  unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
1516 
1517  // Only interested in recurrences whose instructions have only one def, which
1518  // is a virtual register.
1519  if (MI.getDesc().getNumDefs() != 1)
1520  return false;
1521 
1522  MachineOperand &DefOp = MI.getOperand(0);
1523  if (!isVirtualRegisterOperand(DefOp))
1524  return false;
1525 
1526  // Check if def operand of MI is tied to any use operand. We are only
1527  // interested in the case that all the instructions in the recurrence chain
1528  // have there def operand tied with one of the use operand.
1529  unsigned TiedUseIdx;
1530  if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1531  return false;
1532 
1533  if (Idx == TiedUseIdx) {
1534  RC.push_back(RecurrenceInstr(&MI));
1535  return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1536  } else {
1537  // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1538  unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1539  if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1540  RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1541  return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1542  }
1543  }
1544 
1545  return false;
1546 }
1547 
1548 /// Phi instructions will eventually be lowered to copy instructions.
1549 /// If phi is in a loop header, a recurrence may formulated around the source
1550 /// and destination of the phi. For such case commuting operands of the
1551 /// instructions in the recurrence may enable coalescing of the copy instruction
1552 /// generated from the phi. For example, if there is a recurrence of
1553 ///
1554 /// LoopHeader:
1555 /// %1 = phi(%0, %100)
1556 /// LoopLatch:
1557 /// %0<def, tied1> = ADD %2<def, tied0>, %1
1558 ///
1559 /// , the fact that %0 and %2 are in the same tied operands set makes
1560 /// the coalescing of copy instruction generated from the phi in
1561 /// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1562 /// %2 have overlapping live range. This introduces additional move
1563 /// instruction to the final assembly. However, if we commute %2 and
1564 /// %1 of ADD instruction, the redundant move instruction can be
1565 /// avoided.
1566 bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1567  SmallSet<unsigned, 2> TargetRegs;
1568  for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1569  MachineOperand &MO = PHI.getOperand(Idx);
1570  assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1571  TargetRegs.insert(MO.getReg());
1572  }
1573 
1574  bool Changed = false;
1575  RecurrenceCycle RC;
1576  if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1577  // Commutes operands of instructions in RC if necessary so that the copy to
1578  // be generated from PHI can be coalesced.
1579  LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1580  for (auto &RI : RC) {
1581  LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1582  auto CP = RI.getCommutePair();
1583  if (CP) {
1584  Changed = true;
1585  TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1586  (*CP).second);
1587  LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1588  }
1589  }
1590  }
1591 
1592  return Changed;
1593 }
1594 
1595 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1596  if (skipFunction(MF.getFunction()))
1597  return false;
1598 
1599  LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1600  LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1601 
1602  if (DisablePeephole)
1603  return false;
1604 
1605  TII = MF.getSubtarget().getInstrInfo();
1606  TRI = MF.getSubtarget().getRegisterInfo();
1607  MRI = &MF.getRegInfo();
1608  DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1609  MLI = &getAnalysis<MachineLoopInfo>();
1610 
1611  bool Changed = false;
1612 
1613  for (MachineBasicBlock &MBB : MF) {
1614  bool SeenMoveImm = false;
1615 
1616  // During this forward scan, at some point it needs to answer the question
1617  // "given a pointer to an MI in the current BB, is it located before or
1618  // after the current instruction".
1619  // To perform this, the following set keeps track of the MIs already seen
1620  // during the scan, if a MI is not in the set, it is assumed to be located
1621  // after. Newly created MIs have to be inserted in the set as well.
1623  SmallSet<unsigned, 4> ImmDefRegs;
1625  SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1626 
1627  // Track when a non-allocatable physical register is copied to a virtual
1628  // register so that useless moves can be removed.
1629  //
1630  // %physreg is the map index; MI is the last valid `%vreg = COPY %physreg`
1631  // without any intervening re-definition of %physreg.
1632  DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1633 
1634  // Set of virtual registers that are copied from.
1635  SmallSet<unsigned, 4> CopySrcRegs;
1637 
1638  bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1639 
1640  for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1641  MII != MIE; ) {
1642  MachineInstr *MI = &*MII;
1643  // We may be erasing MI below, increment MII now.
1644  ++MII;
1645  LocalMIs.insert(MI);
1646 
1647  // Skip debug instructions. They should not affect this peephole optimization.
1648  if (MI->isDebugInstr())
1649  continue;
1650 
1651  if (MI->isPosition())
1652  continue;
1653 
1654  if (IsLoopHeader && MI->isPHI()) {
1655  if (optimizeRecurrence(*MI)) {
1656  Changed = true;
1657  continue;
1658  }
1659  }
1660 
1661  if (!MI->isCopy()) {
1662  for (const MachineOperand &MO : MI->operands()) {
1663  // Visit all operands: definitions can be implicit or explicit.
1664  if (MO.isReg()) {
1665  unsigned Reg = MO.getReg();
1666  if (MO.isDef() && isNAPhysCopy(Reg)) {
1667  const auto &Def = NAPhysToVirtMIs.find(Reg);
1668  if (Def != NAPhysToVirtMIs.end()) {
1669  // A new definition of the non-allocatable physical register
1670  // invalidates previous copies.
1671  LLVM_DEBUG(dbgs()
1672  << "NAPhysCopy: invalidating because of " << *MI);
1673  NAPhysToVirtMIs.erase(Def);
1674  }
1675  }
1676  } else if (MO.isRegMask()) {
1677  const uint32_t *RegMask = MO.getRegMask();
1678  for (auto &RegMI : NAPhysToVirtMIs) {
1679  unsigned Def = RegMI.first;
1680  if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1681  LLVM_DEBUG(dbgs()
1682  << "NAPhysCopy: invalidating because of " << *MI);
1683  NAPhysToVirtMIs.erase(Def);
1684  }
1685  }
1686  }
1687  }
1688  }
1689 
1690  if (MI->isImplicitDef() || MI->isKill())
1691  continue;
1692 
1693  if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1694  // Blow away all non-allocatable physical registers knowledge since we
1695  // don't know what's correct anymore.
1696  //
1697  // FIXME: handle explicit asm clobbers.
1698  LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
1699  << *MI);
1700  NAPhysToVirtMIs.clear();
1701  }
1702 
1703  if ((isUncoalescableCopy(*MI) &&
1704  optimizeUncoalescableCopy(*MI, LocalMIs)) ||
1705  (MI->isCompare() && optimizeCmpInstr(*MI)) ||
1706  (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
1707  // MI is deleted.
1708  LocalMIs.erase(MI);
1709  Changed = true;
1710  continue;
1711  }
1712 
1713  if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
1714  Changed = true;
1715  continue;
1716  }
1717 
1718  if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
1719  // MI is just rewritten.
1720  Changed = true;
1721  continue;
1722  }
1723 
1724  if (MI->isCopy() &&
1725  (foldRedundantCopy(*MI, CopySrcRegs, CopySrcMIs) ||
1726  foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
1727  LocalMIs.erase(MI);
1728  MI->eraseFromParent();
1729  Changed = true;
1730  continue;
1731  }
1732 
1733  if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
1734  SeenMoveImm = true;
1735  } else {
1736  Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
1737  // optimizeExtInstr might have created new instructions after MI
1738  // and before the already incremented MII. Adjust MII so that the
1739  // next iteration sees the new instructions.
1740  MII = MI;
1741  ++MII;
1742  if (SeenMoveImm)
1743  Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs);
1744  }
1745 
1746  // Check whether MI is a load candidate for folding into a later
1747  // instruction. If MI is not a candidate, check whether we can fold an
1748  // earlier load into MI.
1749  if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
1750  !FoldAsLoadDefCandidates.empty()) {
1751 
1752  // We visit each operand even after successfully folding a previous
1753  // one. This allows us to fold multiple loads into a single
1754  // instruction. We do assume that optimizeLoadInstr doesn't insert
1755  // foldable uses earlier in the argument list. Since we don't restart
1756  // iteration, we'd miss such cases.
1757  const MCInstrDesc &MIDesc = MI->getDesc();
1758  for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
1759  ++i) {
1760  const MachineOperand &MOp = MI->getOperand(i);
1761  if (!MOp.isReg())
1762  continue;
1763  unsigned FoldAsLoadDefReg = MOp.getReg();
1764  if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1765  // We need to fold load after optimizeCmpInstr, since
1766  // optimizeCmpInstr can enable folding by converting SUB to CMP.
1767  // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1768  // we need it for markUsesInDebugValueAsUndef().
1769  unsigned FoldedReg = FoldAsLoadDefReg;
1770  MachineInstr *DefMI = nullptr;
1771  if (MachineInstr *FoldMI =
1772  TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
1773  // Update LocalMIs since we replaced MI with FoldMI and deleted
1774  // DefMI.
1775  LLVM_DEBUG(dbgs() << "Replacing: " << *MI);
1776  LLVM_DEBUG(dbgs() << " With: " << *FoldMI);
1777  LocalMIs.erase(MI);
1778  LocalMIs.erase(DefMI);
1779  LocalMIs.insert(FoldMI);
1780  MI->eraseFromParent();
1781  DefMI->eraseFromParent();
1782  MRI->markUsesInDebugValueAsUndef(FoldedReg);
1783  FoldAsLoadDefCandidates.erase(FoldedReg);
1784  ++NumLoadFold;
1785 
1786  // MI is replaced with FoldMI so we can continue trying to fold
1787  Changed = true;
1788  MI = FoldMI;
1789  }
1790  }
1791  }
1792  }
1793 
1794  // If we run into an instruction we can't fold across, discard
1795  // the load candidates. Note: We might be able to fold *into* this
1796  // instruction, so this needs to be after the folding logic.
1797  if (MI->isLoadFoldBarrier()) {
1798  LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
1799  FoldAsLoadDefCandidates.clear();
1800  }
1801  }
1802  }
1803 
1804  return Changed;
1805 }
1806 
1807 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1808  assert(Def->isCopy() && "Invalid definition");
1809  // Copy instruction are supposed to be: Def = Src.
1810  // If someone breaks this assumption, bad things will happen everywhere.
1811  assert(Def->getNumOperands() == 2 && "Invalid number of operands");
1812 
1813  if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1814  // If we look for a different subreg, it means we want a subreg of src.
1815  // Bails as we do not support composing subregs yet.
1816  return ValueTrackerResult();
1817  // Otherwise, we want the whole source.
1818  const MachineOperand &Src = Def->getOperand(1);
1819  if (Src.isUndef())
1820  return ValueTrackerResult();
1821  return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1822 }
1823 
1824 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1825  assert(Def->isBitcast() && "Invalid definition");
1826 
1827  // Bail if there are effects that a plain copy will not expose.
1828  if (Def->hasUnmodeledSideEffects())
1829  return ValueTrackerResult();
1830 
1831  // Bitcasts with more than one def are not supported.
1832  if (Def->getDesc().getNumDefs() != 1)
1833  return ValueTrackerResult();
1834  const MachineOperand DefOp = Def->getOperand(DefIdx);
1835  if (DefOp.getSubReg() != DefSubReg)
1836  // If we look for a different subreg, it means we want a subreg of the src.
1837  // Bails as we do not support composing subregs yet.
1838  return ValueTrackerResult();
1839 
1840  unsigned SrcIdx = Def->getNumOperands();
1841  for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1842  ++OpIdx) {
1843  const MachineOperand &MO = Def->getOperand(OpIdx);
1844  if (!MO.isReg() || !MO.getReg())
1845  continue;
1846  // Ignore dead implicit defs.
1847  if (MO.isImplicit() && MO.isDead())
1848  continue;
1849  assert(!MO.isDef() && "We should have skipped all the definitions by now");
1850  if (SrcIdx != EndOpIdx)
1851  // Multiple sources?
1852  return ValueTrackerResult();
1853  SrcIdx = OpIdx;
1854  }
1855 
1856  // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1857  // will break the assumed guarantees for the upper bits.
1858  for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
1859  if (UseMI.isSubregToReg())
1860  return ValueTrackerResult();
1861  }
1862 
1863  const MachineOperand &Src = Def->getOperand(SrcIdx);
1864  if (Src.isUndef())
1865  return ValueTrackerResult();
1866  return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1867 }
1868 
1869 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1870  assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1871  "Invalid definition");
1872 
1873  if (Def->getOperand(DefIdx).getSubReg())
1874  // If we are composing subregs, bail out.
1875  // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1876  // This should almost never happen as the SSA property is tracked at
1877  // the register level (as opposed to the subreg level).
1878  // I.e.,
1879  // Def.sub0 =
1880  // Def.sub1 =
1881  // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1882  // Def. Thus, it must not be generated.
1883  // However, some code could theoretically generates a single
1884  // Def.sub0 (i.e, not defining the other subregs) and we would
1885  // have this case.
1886  // If we can ascertain (or force) that this never happens, we could
1887  // turn that into an assertion.
1888  return ValueTrackerResult();
1889 
1890  if (!TII)
1891  // We could handle the REG_SEQUENCE here, but we do not want to
1892  // duplicate the code from the generic TII.
1893  return ValueTrackerResult();
1894 
1895  SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1896  if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1897  return ValueTrackerResult();
1898 
1899  // We are looking at:
1900  // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1901  // Check if one of the operand defines the subreg we are interested in.
1902  for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
1903  if (RegSeqInput.SubIdx == DefSubReg) {
1904  if (RegSeqInput.SubReg)
1905  // Bail if we have to compose sub registers.
1906  return ValueTrackerResult();
1907 
1908  return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1909  }
1910  }
1911 
1912  // If the subreg we are tracking is super-defined by another subreg,
1913  // we could follow this value. However, this would require to compose
1914  // the subreg and we do not do that for now.
1915  return ValueTrackerResult();
1916 }
1917 
1918 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1919  assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1920  "Invalid definition");
1921 
1922  if (Def->getOperand(DefIdx).getSubReg())
1923  // If we are composing subreg, bail out.
1924  // Same remark as getNextSourceFromRegSequence.
1925  // I.e., this may be turned into an assert.
1926  return ValueTrackerResult();
1927 
1928  if (!TII)
1929  // We could handle the REG_SEQUENCE here, but we do not want to
1930  // duplicate the code from the generic TII.
1931  return ValueTrackerResult();
1932 
1933  RegSubRegPair BaseReg;
1934  RegSubRegPairAndIdx InsertedReg;
1935  if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1936  return ValueTrackerResult();
1937 
1938  // We are looking at:
1939  // Def = INSERT_SUBREG v0, v1, sub1
1940  // There are two cases:
1941  // 1. DefSubReg == sub1, get v1.
1942  // 2. DefSubReg != sub1, the value may be available through v0.
1943 
1944  // #1 Check if the inserted register matches the required sub index.
1945  if (InsertedReg.SubIdx == DefSubReg) {
1946  return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1947  }
1948  // #2 Otherwise, if the sub register we are looking for is not partial
1949  // defined by the inserted element, we can look through the main
1950  // register (v0).
1951  const MachineOperand &MODef = Def->getOperand(DefIdx);
1952  // If the result register (Def) and the base register (v0) do not
1953  // have the same register class or if we have to compose
1954  // subregisters, bail out.
1955  if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1956  BaseReg.SubReg)
1957  return ValueTrackerResult();
1958 
1959  // Get the TRI and check if the inserted sub-register overlaps with the
1960  // sub-register we are tracking.
1961  const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1962  if (!TRI ||
1963  !(TRI->getSubRegIndexLaneMask(DefSubReg) &
1964  TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
1965  return ValueTrackerResult();
1966  // At this point, the value is available in v0 via the same subreg
1967  // we used for Def.
1968  return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1969 }
1970 
1971 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1972  assert((Def->isExtractSubreg() ||
1973  Def->isExtractSubregLike()) && "Invalid definition");
1974  // We are looking at:
1975  // Def = EXTRACT_SUBREG v0, sub0
1976 
1977  // Bail if we have to compose sub registers.
1978  // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1979  if (DefSubReg)
1980  return ValueTrackerResult();
1981 
1982  if (!TII)
1983  // We could handle the EXTRACT_SUBREG here, but we do not want to
1984  // duplicate the code from the generic TII.
1985  return ValueTrackerResult();
1986 
1987  RegSubRegPairAndIdx ExtractSubregInputReg;
1988  if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1989  return ValueTrackerResult();
1990 
1991  // Bail if we have to compose sub registers.
1992  // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1993  if (ExtractSubregInputReg.SubReg)
1994  return ValueTrackerResult();
1995  // Otherwise, the value is available in the v0.sub0.
1996  return ValueTrackerResult(ExtractSubregInputReg.Reg,
1997  ExtractSubregInputReg.SubIdx);
1998 }
1999 
2000 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2001  assert(Def->isSubregToReg() && "Invalid definition");
2002  // We are looking at:
2003  // Def = SUBREG_TO_REG Imm, v0, sub0
2004 
2005  // Bail if we have to compose sub registers.
2006  // If DefSubReg != sub0, we would have to check that all the bits
2007  // we track are included in sub0 and if yes, we would have to
2008  // determine the right subreg in v0.
2009  if (DefSubReg != Def->getOperand(3).getImm())
2010  return ValueTrackerResult();
2011  // Bail if we have to compose sub registers.
2012  // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2013  if (Def->getOperand(2).getSubReg())
2014  return ValueTrackerResult();
2015 
2016  return ValueTrackerResult(Def->getOperand(2).getReg(),
2017  Def->getOperand(3).getImm());
2018 }
2019 
2020 /// Explore each PHI incoming operand and return its sources.
2021 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2022  assert(Def->isPHI() && "Invalid definition");
2023  ValueTrackerResult Res;
2024 
2025  // If we look for a different subreg, bail as we do not support composing
2026  // subregs yet.
2027  if (Def->getOperand(0).getSubReg() != DefSubReg)
2028  return ValueTrackerResult();
2029 
2030  // Return all register sources for PHI instructions.
2031  for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2032  const MachineOperand &MO = Def->getOperand(i);
2033  assert(MO.isReg() && "Invalid PHI instruction");
2034  // We have no code to deal with undef operands. They shouldn't happen in
2035  // normal programs anyway.
2036  if (MO.isUndef())
2037  return ValueTrackerResult();
2038  Res.addSource(MO.getReg(), MO.getSubReg());
2039  }
2040 
2041  return Res;
2042 }
2043 
2044 ValueTrackerResult ValueTracker::getNextSourceImpl() {
2045  assert(Def && "This method needs a valid definition");
2046 
2047  assert(((Def->getOperand(DefIdx).isDef() &&
2048  (DefIdx < Def->getDesc().getNumDefs() ||
2049  Def->getDesc().isVariadic())) ||
2050  Def->getOperand(DefIdx).isImplicit()) &&
2051  "Invalid DefIdx");
2052  if (Def->isCopy())
2053  return getNextSourceFromCopy();
2054  if (Def->isBitcast())
2055  return getNextSourceFromBitcast();
2056  // All the remaining cases involve "complex" instructions.
2057  // Bail if we did not ask for the advanced tracking.
2058  if (DisableAdvCopyOpt)
2059  return ValueTrackerResult();
2060  if (Def->isRegSequence() || Def->isRegSequenceLike())
2061  return getNextSourceFromRegSequence();
2062  if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2063  return getNextSourceFromInsertSubreg();
2064  if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2065  return getNextSourceFromExtractSubreg();
2066  if (Def->isSubregToReg())
2067  return getNextSourceFromSubregToReg();
2068  if (Def->isPHI())
2069  return getNextSourceFromPHI();
2070  return ValueTrackerResult();
2071 }
2072 
2073 ValueTrackerResult ValueTracker::getNextSource() {
2074  // If we reach a point where we cannot move up in the use-def chain,
2075  // there is nothing we can get.
2076  if (!Def)
2077  return ValueTrackerResult();
2078 
2079  ValueTrackerResult Res = getNextSourceImpl();
2080  if (Res.isValid()) {
2081  // Update definition, definition index, and subregister for the
2082  // next call of getNextSource.
2083  // Update the current register.
2084  bool OneRegSrc = Res.getNumSources() == 1;
2085  if (OneRegSrc)
2086  Reg = Res.getSrcReg(0);
2087  // Update the result before moving up in the use-def chain
2088  // with the instruction containing the last found sources.
2089  Res.setInst(Def);
2090 
2091  // If we can still move up in the use-def chain, move to the next
2092  // definition.
2093  if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
2095  if (DI != MRI.def_end()) {
2096  Def = DI->getParent();
2097  DefIdx = DI.getOperandNo();
2098  DefSubReg = Res.getSrcSubReg(0);
2099  } else {
2100  Def = nullptr;
2101  }
2102  return Res;
2103  }
2104  }
2105  // If we end up here, this means we will not be able to find another source
2106  // for the next iteration. Make sure any new call to getNextSource bails out
2107  // early by cutting the use-def chain.
2108  Def = nullptr;
2109  return Res;
2110 }
A common definition of LaneBitmask for use in TableGen and CodeGen.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
MachineBasicBlock * getMBB() const
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
bool isAllocatable(unsigned PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn&#39;t been...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg, unsigned SrcReg2, int Mask, int Value, const MachineRegisterInfo *MRI) const
See if the comparison instruction can be converted into something more efficient. ...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static cl::opt< bool > DisableNAPhysCopyOpt("disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable non-allocatable physical register copy optimization"))
bool isExtractSubregLike(QueryType Type=IgnoreBundle) const
Return true if this instruction behaves the same way as the generic EXTRACT_SUBREG instructions...
Definition: MachineInstr.h:781
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:382
iterator_range< use_nodbg_iterator > use_nodbg_operands(unsigned Reg) const
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
unsigned getReg() const
getReg - Returns the register number.
void setIsUndef(bool Val=true)
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
virtual bool analyzeSelect(const MachineInstr &MI, SmallVectorImpl< MachineOperand > &Cond, unsigned &TrueOp, unsigned &FalseOp, bool &Optimizable) const
Analyze the given select instruction, returning true if it cannot be understood.
unsigned Reg
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
unsigned getSubReg() const
bool isInlineAsm() const
bool isRegSequence() const
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:458
bool isPHI() const
bool erase(const T &V)
Definition: SmallSet.h:207
bool isMoveImmediate(QueryType Type=IgnoreBundle) const
Return true if this instruction is a move immediate (including conditional moves) instruction...
Definition: MachineInstr.h:699
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
bool isBitcast(QueryType Type=IgnoreBundle) const
Return true if this instruction is a bitcast instruction.
Definition: MachineInstr.h:710
static MachineInstr & insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const SmallVectorImpl< RegSubRegPair > &SrcRegs, MachineInstr &OrigPHI)
Insert a PHI instruction with incoming edges SrcRegs that are guaranteed to have the same register cl...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
LLVM_NODISCARD bool empty() const
Definition: SmallSet.h:155
Definition: BitVector.h:937
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
static cl::opt< bool > Aggressive("aggressive-ext-opt", cl::Hidden, cl::desc("Aggressive extension optimization"))
virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, unsigned Reg, MachineRegisterInfo *MRI) const
&#39;Reg&#39; is known to be defined by a move immediate instruction, try to fold the immediate into the use ...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
unsigned SubReg
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
virtual const TargetRegisterClass * getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const
Returns the largest legal sub-class of RC that supports the sub-register index Idx.
def_iterator def_begin(unsigned RegNo) const
static cl::opt< unsigned > MaxRecurrenceChain("recurrence-chain-limit", cl::Hidden, cl::init(3), cl::desc("Maximum length of recurrence chain when evaluating the benefit " "of commuting operands"))
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:405
void clear()
Definition: SmallSet.h:218
void clearKillFlags(unsigned Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
void initializePeepholeOptimizerPass(PassRegistry &)
virtual const TargetInstrInfo * getInstrInfo() const
TargetInstrInfo::RegSubRegPairAndIdx RegSubRegPairAndIdx
virtual MachineInstr * optimizeSelect(MachineInstr &MI, SmallPtrSetImpl< MachineInstr *> &NewMIs, bool PreferFalse=false) const
Given a select instruction that was understood by analyzeSelect and returned Optimizable = true...
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
TargetInstrInfo - Interface to description of machine instruction set.
TargetInstrInfo::RegSubRegPair RegSubRegPair
static const unsigned CommuteAnyOperandIndex
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
static bool isVirtualRegisterOperand(MachineOperand &MO)
Returns true if MO is a virtual register operand.
const TargetRegisterInfo * getTargetRegisterInfo() const
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
static cl::opt< unsigned > RewritePHILimit("rewrite-phi-limit", cl::Hidden, cl::init(10), cl::desc("Limit the length of PHI chains to lookup"))
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool isCompare(QueryType Type=IgnoreBundle) const
Return true if this instruction is a comparison.
Definition: MachineInstr.h:693
MachineInstrBuilder & UseMI
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
static RegSubRegPair getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII, RegSubRegPair Def, const PeepholeOptimizer::RewriteMapTy &RewriteMap, bool HandleMultipleSources=true)
Given a Def.Reg and Def.SubReg pair, use RewriteMap to find the new source to use for rewrite...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
Represent the analysis usage information of a pass.
bool isSelect(QueryType Type=IgnoreBundle) const
Return true if this instruction is a select instruction.
Definition: MachineInstr.h:715
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
static Rewriter * getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
Get the appropriated Rewriter for MI.
bool isCopy() const
bool isInsertSubregLike(QueryType Type=IgnoreBundle) const
Return true if this instruction behaves the same way as the generic INSERT_SUBREG instructions...
Definition: MachineInstr.h:795
bool isImplicitDef() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
size_t size() const
Definition: SmallVector.h:52
bool isDebugInstr() const
Definition: MachineInstr.h:998
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
virtual bool analyzeCompare(const MachineInstr &MI, unsigned &SrcReg, unsigned &SrcReg2, int &Mask, int &Value) const
For a comparison instruction, return the source registers in SrcReg and SrcReg2 if having two registe...
bool isConditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which may fall through to the next instruction or may transfer contro...
Definition: MachineInstr.h:670
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
virtual bool optimizeCondBranch(MachineInstr &MI) const
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:377
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
bool isInsertSubreg() const
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
A pair composed of a register and a sub-register index.
MachineInstrBuilder MachineInstrBuilder & DefMI
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:373
virtual bool isCoalescableExtInstr(const MachineInstr &MI, unsigned &SrcReg, unsigned &DstReg, unsigned &SubIdx) const
Return true if the instruction is a "coalescable" extension instruction.
LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const
Return a bitmask representing the parts of a register that are covered by SubIdx. ...
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
Definition: MCInstrDesc.h:225
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:285
bool getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx, SmallVectorImpl< RegSubRegPairAndIdx > &InputRegs) const
Build the equivalent inputs of a REG_SEQUENCE for the given MI and DefIdx.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
virtual bool findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
char & PeepholeOptimizerID
PeepholeOptimizer - This pass performs peephole optimizations - like extension and comparison elimina...
INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE, "Peephole Optimizations", false, false) INITIALIZE_PASS_END(PeepholeOptimizer
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:211
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:386
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Virtual Register Rewriter
Definition: VirtRegMap.cpp:221
bool isRegSequenceLike(QueryType Type=IgnoreBundle) const
Return true if this instruction behaves the same way as the generic REG_SEQUENCE instructions.
Definition: MachineInstr.h:766
Representation of each machine instruction.
Definition: MachineInstr.h:63
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
unsigned getOperandNo() const
getOperandNo - Return the operand # of this MachineOperand in its MachineInstr.
#define DEBUG_TYPE
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC, unsigned DefSubReg, const TargetRegisterClass *SrcRC, unsigned SrcSubReg) const
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
bool canFoldAsLoad(QueryType Type=IgnoreBundle) const
Return true for instructions that can be folded as memory operands in other instructions.
Definition: MachineInstr.h:752
Peephole Optimizations
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
static cl::opt< bool > DisablePeephole("disable-peephole", cl::Hidden, cl::init(false), cl::desc("Disable the peephole optimizer"))
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
void setSubReg(unsigned subReg)
void markUsesInDebugValueAsUndef(unsigned Reg) const
markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the specified register as undefined wh...
virtual MachineInstr * optimizeLoadInstr(MachineInstr &MI, const MachineRegisterInfo *MRI, unsigned &FoldAsLoadDefReg, MachineInstr *&DefMI) const
Try to remove the load by folding it to a register operand at the use.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
bool isLoadFoldBarrier() const
Returns true if it is illegal to fold a load across this instruction.
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
bool isKill() const
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:211
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Definition: MachineInstr.h:806
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static def_iterator def_end()
use_instr_nodbg_iterator use_instr_nodbg_begin(unsigned RegNo) const
bool isPosition() const
Definition: MachineInstr.h:994
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
IRTranslator LLVM IR MI
bool operator==(uint64_t V1, const APInt &V2)
Definition: APInt.h:1966
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPairAndIdx &InputReg) const
Build the equivalent inputs of a EXTRACT_SUBREG for the given MI and DefIdx.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(unsigned Reg) const
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
static cl::opt< bool > DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable advanced copy optimization"))
Specifiy whether or not the value tracking looks through complex instructions.
bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const
Build the equivalent inputs of a INSERT_SUBREG for the given MI and DefIdx.
bool isExtractSubreg() const
int findRegisterUseOperandIdx(unsigned Reg, bool isKill=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a use of the specific register or -1 if it is not found...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
unsigned createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool isImplicit() const
A pair composed of a pair of a register and a sub-register index, and another sub-register index...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:164