1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
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 // Early if-conversion is for out-of-order CPUs that don't have a lot of
10 // predicable instructions. The goal is to eliminate conditional branches that
11 // may mispredict.
12 //
13 // Instructions from both sides of the branch are executed specutatively, and a
14 // cmov instruction selects the result.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SparseSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/MachineTraceMetrics.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetInstrInfo.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "early-ifcvt"
45 
46 // Absolute maximum number of instructions allowed per speculated block.
47 // This bypasses all other heuristics, so it should be set fairly high.
48 static cl::opt<unsigned>
49 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
50   cl::desc("Maximum number of instructions per speculated block."));
51 
52 // Stress testing mode - disable heuristics.
53 static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
54   cl::desc("Turn all knobs to 11"));
55 
56 STATISTIC(NumDiamondsSeen,  "Number of diamonds");
57 STATISTIC(NumDiamondsConv,  "Number of diamonds converted");
58 STATISTIC(NumTrianglesSeen, "Number of triangles");
59 STATISTIC(NumTrianglesConv, "Number of triangles converted");
60 
61 //===----------------------------------------------------------------------===//
62 //                                 SSAIfConv
63 //===----------------------------------------------------------------------===//
64 //
65 // The SSAIfConv class performs if-conversion on SSA form machine code after
66 // determining if it is possible. The class contains no heuristics; external
67 // code should be used to determine when if-conversion is a good idea.
68 //
69 // SSAIfConv can convert both triangles and diamonds:
70 //
71 //   Triangle: Head              Diamond: Head
72 //              | \                       /  \_
73 //              |  \                     /    |
74 //              |  [TF]BB              FBB    TBB
75 //              |  /                     \    /
76 //              | /                       \  /
77 //             Tail                       Tail
78 //
79 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
80 // Head block, and phis in the Tail block are converted to select instructions.
81 //
82 namespace {
83 class SSAIfConv {
84   const TargetInstrInfo *TII;
85   const TargetRegisterInfo *TRI;
86   MachineRegisterInfo *MRI;
87 
88 public:
89   /// The block containing the conditional branch.
90   MachineBasicBlock *Head;
91 
92   /// The block containing phis after the if-then-else.
93   MachineBasicBlock *Tail;
94 
95   /// The 'true' conditional block as determined by analyzeBranch.
96   MachineBasicBlock *TBB;
97 
98   /// The 'false' conditional block as determined by analyzeBranch.
99   MachineBasicBlock *FBB;
100 
101   /// isTriangle - When there is no 'else' block, either TBB or FBB will be
102   /// equal to Tail.
isTriangle() const103   bool isTriangle() const { return TBB == Tail || FBB == Tail; }
104 
105   /// Returns the Tail predecessor for the True side.
getTPred() const106   MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
107 
108   /// Returns the Tail predecessor for the  False side.
getFPred() const109   MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
110 
111   /// Information about each phi in the Tail block.
112   struct PHIInfo {
113     MachineInstr *PHI;
114     unsigned TReg, FReg;
115     // Latencies from Cond+Branch, TReg, and FReg to DstReg.
116     int CondCycles, TCycles, FCycles;
117 
PHIInfo__anonee2abff40111::SSAIfConv::PHIInfo118     PHIInfo(MachineInstr *phi)
119       : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
120   };
121 
122   SmallVector<PHIInfo, 8> PHIs;
123 
124 private:
125   /// The branch condition determined by analyzeBranch.
126   SmallVector<MachineOperand, 4> Cond;
127 
128   /// Instructions in Head that define values used by the conditional blocks.
129   /// The hoisted instructions must be inserted after these instructions.
130   SmallPtrSet<MachineInstr*, 8> InsertAfter;
131 
132   /// Register units clobbered by the conditional blocks.
133   BitVector ClobberedRegUnits;
134 
135   // Scratch pad for findInsertionPoint.
136   SparseSet<unsigned> LiveRegUnits;
137 
138   /// Insertion point in Head for speculatively executed instructions form TBB
139   /// and FBB.
140   MachineBasicBlock::iterator InsertionPoint;
141 
142   /// Return true if all non-terminator instructions in MBB can be safely
143   /// speculated.
144   bool canSpeculateInstrs(MachineBasicBlock *MBB);
145 
146   /// Return true if all non-terminator instructions in MBB can be safely
147   /// predicated.
148   bool canPredicateInstrs(MachineBasicBlock *MBB);
149 
150   /// Scan through instruction dependencies and update InsertAfter array.
151   /// Return false if any dependency is incompatible with if conversion.
152   bool InstrDependenciesAllowIfConv(MachineInstr *I);
153 
154   /// Predicate all instructions of the basic block with current condition
155   /// except for terminators. Reverse the condition if ReversePredicate is set.
156   void PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate);
157 
158   /// Find a valid insertion point in Head.
159   bool findInsertionPoint();
160 
161   /// Replace PHI instructions in Tail with selects.
162   void replacePHIInstrs();
163 
164   /// Insert selects and rewrite PHI operands to use them.
165   void rewritePHIOperands();
166 
167 public:
168   /// runOnMachineFunction - Initialize per-function data structures.
runOnMachineFunction(MachineFunction & MF)169   void runOnMachineFunction(MachineFunction &MF) {
170     TII = MF.getSubtarget().getInstrInfo();
171     TRI = MF.getSubtarget().getRegisterInfo();
172     MRI = &MF.getRegInfo();
173     LiveRegUnits.clear();
174     LiveRegUnits.setUniverse(TRI->getNumRegUnits());
175     ClobberedRegUnits.clear();
176     ClobberedRegUnits.resize(TRI->getNumRegUnits());
177   }
178 
179   /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
180   /// initialize the internal state, and return true.
181   /// If predicate is set try to predicate the block otherwise try to
182   /// speculatively execute it.
183   bool canConvertIf(MachineBasicBlock *MBB, bool Predicate = false);
184 
185   /// convertIf - If-convert the last block passed to canConvertIf(), assuming
186   /// it is possible. Add any erased blocks to RemovedBlocks.
187   void convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
188                  bool Predicate = false);
189 };
190 } // end anonymous namespace
191 
192 
193 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
194 /// be speculated. The terminators are not considered.
195 ///
196 /// If instructions use any values that are defined in the head basic block,
197 /// the defining instructions are added to InsertAfter.
198 ///
199 /// Any clobbered regunits are added to ClobberedRegUnits.
200 ///
canSpeculateInstrs(MachineBasicBlock * MBB)201 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
202   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
203   // get right.
204   if (!MBB->livein_empty()) {
205     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
206     return false;
207   }
208 
209   unsigned InstrCount = 0;
210 
211   // Check all instructions, except the terminators. It is assumed that
212   // terminators never have side effects or define any used register values.
213   for (MachineBasicBlock::iterator I = MBB->begin(),
214        E = MBB->getFirstTerminator(); I != E; ++I) {
215     if (I->isDebugInstr())
216       continue;
217 
218     if (++InstrCount > BlockInstrLimit && !Stress) {
219       LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
220                         << BlockInstrLimit << " instructions.\n");
221       return false;
222     }
223 
224     // There shouldn't normally be any phis in a single-predecessor block.
225     if (I->isPHI()) {
226       LLVM_DEBUG(dbgs() << "Can't hoist: " << *I);
227       return false;
228     }
229 
230     // Don't speculate loads. Note that it may be possible and desirable to
231     // speculate GOT or constant pool loads that are guaranteed not to trap,
232     // but we don't support that for now.
233     if (I->mayLoad()) {
234       LLVM_DEBUG(dbgs() << "Won't speculate load: " << *I);
235       return false;
236     }
237 
238     // We never speculate stores, so an AA pointer isn't necessary.
239     bool DontMoveAcrossStore = true;
240     if (!I->isSafeToMove(nullptr, DontMoveAcrossStore)) {
241       LLVM_DEBUG(dbgs() << "Can't speculate: " << *I);
242       return false;
243     }
244 
245     // Check for any dependencies on Head instructions.
246     if (!InstrDependenciesAllowIfConv(&(*I)))
247       return false;
248   }
249   return true;
250 }
251 
252 /// Check that there is no dependencies preventing if conversion.
253 ///
254 /// If instruction uses any values that are defined in the head basic block,
255 /// the defining instructions are added to InsertAfter.
InstrDependenciesAllowIfConv(MachineInstr * I)256 bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr *I) {
257   for (const MachineOperand &MO : I->operands()) {
258     if (MO.isRegMask()) {
259       LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I);
260       return false;
261     }
262     if (!MO.isReg())
263       continue;
264     Register Reg = MO.getReg();
265 
266     // Remember clobbered regunits.
267     if (MO.isDef() && Register::isPhysicalRegister(Reg))
268       for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
269            ++Units)
270         ClobberedRegUnits.set(*Units);
271 
272     if (!MO.readsReg() || !Register::isVirtualRegister(Reg))
273       continue;
274     MachineInstr *DefMI = MRI->getVRegDef(Reg);
275     if (!DefMI || DefMI->getParent() != Head)
276       continue;
277     if (InsertAfter.insert(DefMI).second)
278       LLVM_DEBUG(dbgs() << printMBBReference(*I->getParent()) << " depends on "
279                         << *DefMI);
280     if (DefMI->isTerminator()) {
281       LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
282       return false;
283     }
284   }
285   return true;
286 }
287 
288 /// canPredicateInstrs - Returns true if all the instructions in MBB can safely
289 /// be predicates. The terminators are not considered.
290 ///
291 /// If instructions use any values that are defined in the head basic block,
292 /// the defining instructions are added to InsertAfter.
293 ///
294 /// Any clobbered regunits are added to ClobberedRegUnits.
295 ///
canPredicateInstrs(MachineBasicBlock * MBB)296 bool SSAIfConv::canPredicateInstrs(MachineBasicBlock *MBB) {
297   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
298   // get right.
299   if (!MBB->livein_empty()) {
300     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
301     return false;
302   }
303 
304   unsigned InstrCount = 0;
305 
306   // Check all instructions, except the terminators. It is assumed that
307   // terminators never have side effects or define any used register values.
308   for (MachineBasicBlock::iterator I = MBB->begin(),
309                                    E = MBB->getFirstTerminator();
310        I != E; ++I) {
311     if (I->isDebugInstr())
312       continue;
313 
314     if (++InstrCount > BlockInstrLimit && !Stress) {
315       LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
316                         << BlockInstrLimit << " instructions.\n");
317       return false;
318     }
319 
320     // There shouldn't normally be any phis in a single-predecessor block.
321     if (I->isPHI()) {
322       LLVM_DEBUG(dbgs() << "Can't predicate: " << *I);
323       return false;
324     }
325 
326     // Check that instruction is predicable and that it is not already
327     // predicated.
328     if (!TII->isPredicable(*I) || TII->isPredicated(*I)) {
329       return false;
330     }
331 
332     // Check for any dependencies on Head instructions.
333     if (!InstrDependenciesAllowIfConv(&(*I)))
334       return false;
335   }
336   return true;
337 }
338 
339 // Apply predicate to all instructions in the machine block.
PredicateBlock(MachineBasicBlock * MBB,bool ReversePredicate)340 void SSAIfConv::PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate) {
341   auto Condition = Cond;
342   if (ReversePredicate)
343     TII->reverseBranchCondition(Condition);
344   // Terminators don't need to be predicated as they will be removed.
345   for (MachineBasicBlock::iterator I = MBB->begin(),
346                                    E = MBB->getFirstTerminator();
347        I != E; ++I) {
348     if (I->isDebugInstr())
349       continue;
350     TII->PredicateInstruction(*I, Condition);
351   }
352 }
353 
354 /// Find an insertion point in Head for the speculated instructions. The
355 /// insertion point must be:
356 ///
357 /// 1. Before any terminators.
358 /// 2. After any instructions in InsertAfter.
359 /// 3. Not have any clobbered regunits live.
360 ///
361 /// This function sets InsertionPoint and returns true when successful, it
362 /// returns false if no valid insertion point could be found.
363 ///
findInsertionPoint()364 bool SSAIfConv::findInsertionPoint() {
365   // Keep track of live regunits before the current position.
366   // Only track RegUnits that are also in ClobberedRegUnits.
367   LiveRegUnits.clear();
368   SmallVector<MCRegister, 8> Reads;
369   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
370   MachineBasicBlock::iterator I = Head->end();
371   MachineBasicBlock::iterator B = Head->begin();
372   while (I != B) {
373     --I;
374     // Some of the conditional code depends in I.
375     if (InsertAfter.count(&*I)) {
376       LLVM_DEBUG(dbgs() << "Can't insert code after " << *I);
377       return false;
378     }
379 
380     // Update live regunits.
381     for (const MachineOperand &MO : I->operands()) {
382       // We're ignoring regmask operands. That is conservatively correct.
383       if (!MO.isReg())
384         continue;
385       Register Reg = MO.getReg();
386       if (!Register::isPhysicalRegister(Reg))
387         continue;
388       // I clobbers Reg, so it isn't live before I.
389       if (MO.isDef())
390         for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
391              ++Units)
392           LiveRegUnits.erase(*Units);
393       // Unless I reads Reg.
394       if (MO.readsReg())
395         Reads.push_back(Reg.asMCReg());
396     }
397     // Anything read by I is live before I.
398     while (!Reads.empty())
399       for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
400            ++Units)
401         if (ClobberedRegUnits.test(*Units))
402           LiveRegUnits.insert(*Units);
403 
404     // We can't insert before a terminator.
405     if (I != FirstTerm && I->isTerminator())
406       continue;
407 
408     // Some of the clobbered registers are live before I, not a valid insertion
409     // point.
410     if (!LiveRegUnits.empty()) {
411       LLVM_DEBUG({
412         dbgs() << "Would clobber";
413         for (unsigned LRU : LiveRegUnits)
414           dbgs() << ' ' << printRegUnit(LRU, TRI);
415         dbgs() << " live before " << *I;
416       });
417       continue;
418     }
419 
420     // This is a valid insertion point.
421     InsertionPoint = I;
422     LLVM_DEBUG(dbgs() << "Can insert before " << *I);
423     return true;
424   }
425   LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
426   return false;
427 }
428 
429 
430 
431 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
432 /// a potential candidate for if-conversion. Fill out the internal state.
433 ///
canConvertIf(MachineBasicBlock * MBB,bool Predicate)434 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB, bool Predicate) {
435   Head = MBB;
436   TBB = FBB = Tail = nullptr;
437 
438   if (Head->succ_size() != 2)
439     return false;
440   MachineBasicBlock *Succ0 = Head->succ_begin()[0];
441   MachineBasicBlock *Succ1 = Head->succ_begin()[1];
442 
443   // Canonicalize so Succ0 has MBB as its single predecessor.
444   if (Succ0->pred_size() != 1)
445     std::swap(Succ0, Succ1);
446 
447   if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
448     return false;
449 
450   Tail = Succ0->succ_begin()[0];
451 
452   // This is not a triangle.
453   if (Tail != Succ1) {
454     // Check for a diamond. We won't deal with any critical edges.
455     if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
456         Succ1->succ_begin()[0] != Tail)
457       return false;
458     LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head) << " -> "
459                       << printMBBReference(*Succ0) << "/"
460                       << printMBBReference(*Succ1) << " -> "
461                       << printMBBReference(*Tail) << '\n');
462 
463     // Live-in physregs are tricky to get right when speculating code.
464     if (!Tail->livein_empty()) {
465       LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
466       return false;
467     }
468   } else {
469     LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
470                       << printMBBReference(*Succ0) << " -> "
471                       << printMBBReference(*Tail) << '\n');
472   }
473 
474   // This is a triangle or a diamond.
475   // Skip if we cannot predicate and there are no phis skip as there must be
476   // side effects that can only be handled with predication.
477   if (!Predicate && (Tail->empty() || !Tail->front().isPHI())) {
478     LLVM_DEBUG(dbgs() << "No phis in tail.\n");
479     return false;
480   }
481 
482   // The branch we're looking to eliminate must be analyzable.
483   Cond.clear();
484   if (TII->analyzeBranch(*Head, TBB, FBB, Cond)) {
485     LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
486     return false;
487   }
488 
489   // This is weird, probably some sort of degenerate CFG.
490   if (!TBB) {
491     LLVM_DEBUG(dbgs() << "analyzeBranch didn't find conditional branch.\n");
492     return false;
493   }
494 
495   // Make sure the analyzed branch is conditional; one of the successors
496   // could be a landing pad. (Empty landing pads can be generated on Windows.)
497   if (Cond.empty()) {
498     LLVM_DEBUG(dbgs() << "analyzeBranch found an unconditional branch.\n");
499     return false;
500   }
501 
502   // analyzeBranch doesn't set FBB on a fall-through branch.
503   // Make sure it is always set.
504   FBB = TBB == Succ0 ? Succ1 : Succ0;
505 
506   // Any phis in the tail block must be convertible to selects.
507   PHIs.clear();
508   MachineBasicBlock *TPred = getTPred();
509   MachineBasicBlock *FPred = getFPred();
510   for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
511        I != E && I->isPHI(); ++I) {
512     PHIs.push_back(&*I);
513     PHIInfo &PI = PHIs.back();
514     // Find PHI operands corresponding to TPred and FPred.
515     for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
516       if (PI.PHI->getOperand(i+1).getMBB() == TPred)
517         PI.TReg = PI.PHI->getOperand(i).getReg();
518       if (PI.PHI->getOperand(i+1).getMBB() == FPred)
519         PI.FReg = PI.PHI->getOperand(i).getReg();
520     }
521     assert(Register::isVirtualRegister(PI.TReg) && "Bad PHI");
522     assert(Register::isVirtualRegister(PI.FReg) && "Bad PHI");
523 
524     // Get target information.
525     if (!TII->canInsertSelect(*Head, Cond, PI.PHI->getOperand(0).getReg(),
526                               PI.TReg, PI.FReg, PI.CondCycles, PI.TCycles,
527                               PI.FCycles)) {
528       LLVM_DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
529       return false;
530     }
531   }
532 
533   // Check that the conditional instructions can be speculated.
534   InsertAfter.clear();
535   ClobberedRegUnits.reset();
536   if (Predicate) {
537     if (TBB != Tail && !canPredicateInstrs(TBB))
538       return false;
539     if (FBB != Tail && !canPredicateInstrs(FBB))
540       return false;
541   } else {
542     if (TBB != Tail && !canSpeculateInstrs(TBB))
543       return false;
544     if (FBB != Tail && !canSpeculateInstrs(FBB))
545       return false;
546   }
547 
548   // Try to find a valid insertion point for the speculated instructions in the
549   // head basic block.
550   if (!findInsertionPoint())
551     return false;
552 
553   if (isTriangle())
554     ++NumTrianglesSeen;
555   else
556     ++NumDiamondsSeen;
557   return true;
558 }
559 
560 /// \return true iff the two registers are known to have the same value.
hasSameValue(const MachineRegisterInfo & MRI,const TargetInstrInfo * TII,Register TReg,Register FReg)561 static bool hasSameValue(const MachineRegisterInfo &MRI,
562                          const TargetInstrInfo *TII, Register TReg,
563                          Register FReg) {
564   if (TReg == FReg)
565     return true;
566 
567   if (!TReg.isVirtual() || !FReg.isVirtual())
568     return false;
569 
570   const MachineInstr *TDef = MRI.getUniqueVRegDef(TReg);
571   const MachineInstr *FDef = MRI.getUniqueVRegDef(FReg);
572   if (!TDef || !FDef)
573     return false;
574 
575   // If there are side-effects, all bets are off.
576   if (TDef->hasUnmodeledSideEffects())
577     return false;
578 
579   // If the instruction could modify memory, or there may be some intervening
580   // store between the two, we can't consider them to be equal.
581   if (TDef->mayLoadOrStore() && !TDef->isDereferenceableInvariantLoad(nullptr))
582     return false;
583 
584   // We also can't guarantee that they are the same if, for example, the
585   // instructions are both a copy from a physical reg, because some other
586   // instruction may have modified the value in that reg between the two
587   // defining insts.
588   if (any_of(TDef->uses(), [](const MachineOperand &MO) {
589         return MO.isReg() && MO.getReg().isPhysical();
590       }))
591     return false;
592 
593   // Check whether the two defining instructions produce the same value(s).
594   if (!TII->produceSameValue(*TDef, *FDef, &MRI))
595     return false;
596 
597   // Further, check that the two defs come from corresponding operands.
598   int TIdx = TDef->findRegisterDefOperandIdx(TReg);
599   int FIdx = FDef->findRegisterDefOperandIdx(FReg);
600   if (TIdx == -1 || FIdx == -1)
601     return false;
602 
603   return TIdx == FIdx;
604 }
605 
606 /// replacePHIInstrs - Completely replace PHI instructions with selects.
607 /// This is possible when the only Tail predecessors are the if-converted
608 /// blocks.
replacePHIInstrs()609 void SSAIfConv::replacePHIInstrs() {
610   assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
611   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
612   assert(FirstTerm != Head->end() && "No terminators");
613   DebugLoc HeadDL = FirstTerm->getDebugLoc();
614 
615   // Convert all PHIs to select instructions inserted before FirstTerm.
616   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
617     PHIInfo &PI = PHIs[i];
618     LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
619     Register DstReg = PI.PHI->getOperand(0).getReg();
620     if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
621       // We do not need the select instruction if both incoming values are
622       // equal, but we do need a COPY.
623       BuildMI(*Head, FirstTerm, HeadDL, TII->get(TargetOpcode::COPY), DstReg)
624           .addReg(PI.TReg);
625     } else {
626       TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg,
627                         PI.FReg);
628     }
629     LLVM_DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
630     PI.PHI->eraseFromParent();
631     PI.PHI = nullptr;
632   }
633 }
634 
635 /// rewritePHIOperands - When there are additional Tail predecessors, insert
636 /// select instructions in Head and rewrite PHI operands to use the selects.
637 /// Keep the PHI instructions in Tail to handle the other predecessors.
rewritePHIOperands()638 void SSAIfConv::rewritePHIOperands() {
639   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
640   assert(FirstTerm != Head->end() && "No terminators");
641   DebugLoc HeadDL = FirstTerm->getDebugLoc();
642 
643   // Convert all PHIs to select instructions inserted before FirstTerm.
644   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
645     PHIInfo &PI = PHIs[i];
646     unsigned DstReg = 0;
647 
648     LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
649     if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
650       // We do not need the select instruction if both incoming values are
651       // equal.
652       DstReg = PI.TReg;
653     } else {
654       Register PHIDst = PI.PHI->getOperand(0).getReg();
655       DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
656       TII->insertSelect(*Head, FirstTerm, HeadDL,
657                          DstReg, Cond, PI.TReg, PI.FReg);
658       LLVM_DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
659     }
660 
661     // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
662     for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
663       MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
664       if (MBB == getTPred()) {
665         PI.PHI->getOperand(i-1).setMBB(Head);
666         PI.PHI->getOperand(i-2).setReg(DstReg);
667       } else if (MBB == getFPred()) {
668         PI.PHI->RemoveOperand(i-1);
669         PI.PHI->RemoveOperand(i-2);
670       }
671     }
672     LLVM_DEBUG(dbgs() << "          --> " << *PI.PHI);
673   }
674 }
675 
676 /// convertIf - Execute the if conversion after canConvertIf has determined the
677 /// feasibility.
678 ///
679 /// Any basic blocks erased will be added to RemovedBlocks.
680 ///
convertIf(SmallVectorImpl<MachineBasicBlock * > & RemovedBlocks,bool Predicate)681 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
682                           bool Predicate) {
683   assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
684 
685   // Update statistics.
686   if (isTriangle())
687     ++NumTrianglesConv;
688   else
689     ++NumDiamondsConv;
690 
691   // Move all instructions into Head, except for the terminators.
692   if (TBB != Tail) {
693     if (Predicate)
694       PredicateBlock(TBB, /*ReversePredicate=*/false);
695     Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
696   }
697   if (FBB != Tail) {
698     if (Predicate)
699       PredicateBlock(FBB, /*ReversePredicate=*/true);
700     Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
701   }
702   // Are there extra Tail predecessors?
703   bool ExtraPreds = Tail->pred_size() != 2;
704   if (ExtraPreds)
705     rewritePHIOperands();
706   else
707     replacePHIInstrs();
708 
709   // Fix up the CFG, temporarily leave Head without any successors.
710   Head->removeSuccessor(TBB);
711   Head->removeSuccessor(FBB, true);
712   if (TBB != Tail)
713     TBB->removeSuccessor(Tail, true);
714   if (FBB != Tail)
715     FBB->removeSuccessor(Tail, true);
716 
717   // Fix up Head's terminators.
718   // It should become a single branch or a fallthrough.
719   DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
720   TII->removeBranch(*Head);
721 
722   // Erase the now empty conditional blocks. It is likely that Head can fall
723   // through to Tail, and we can join the two blocks.
724   if (TBB != Tail) {
725     RemovedBlocks.push_back(TBB);
726     TBB->eraseFromParent();
727   }
728   if (FBB != Tail) {
729     RemovedBlocks.push_back(FBB);
730     FBB->eraseFromParent();
731   }
732 
733   assert(Head->succ_empty() && "Additional head successors?");
734   if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
735     // Splice Tail onto the end of Head.
736     LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
737                       << " into head " << printMBBReference(*Head) << '\n');
738     Head->splice(Head->end(), Tail,
739                      Tail->begin(), Tail->end());
740     Head->transferSuccessorsAndUpdatePHIs(Tail);
741     RemovedBlocks.push_back(Tail);
742     Tail->eraseFromParent();
743   } else {
744     // We need a branch to Tail, let code placement work it out later.
745     LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
746     SmallVector<MachineOperand, 0> EmptyCond;
747     TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
748     Head->addSuccessor(Tail);
749   }
750   LLVM_DEBUG(dbgs() << *Head);
751 }
752 
753 //===----------------------------------------------------------------------===//
754 //                           EarlyIfConverter Pass
755 //===----------------------------------------------------------------------===//
756 
757 namespace {
758 class EarlyIfConverter : public MachineFunctionPass {
759   const TargetInstrInfo *TII;
760   const TargetRegisterInfo *TRI;
761   MCSchedModel SchedModel;
762   MachineRegisterInfo *MRI;
763   MachineDominatorTree *DomTree;
764   MachineLoopInfo *Loops;
765   MachineTraceMetrics *Traces;
766   MachineTraceMetrics::Ensemble *MinInstr;
767   SSAIfConv IfConv;
768 
769 public:
770   static char ID;
EarlyIfConverter()771   EarlyIfConverter() : MachineFunctionPass(ID) {}
772   void getAnalysisUsage(AnalysisUsage &AU) const override;
773   bool runOnMachineFunction(MachineFunction &MF) override;
getPassName() const774   StringRef getPassName() const override { return "Early If-Conversion"; }
775 
776 private:
777   bool tryConvertIf(MachineBasicBlock*);
778   void invalidateTraces();
779   bool shouldConvertIf();
780 };
781 } // end anonymous namespace
782 
783 char EarlyIfConverter::ID = 0;
784 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
785 
786 INITIALIZE_PASS_BEGIN(EarlyIfConverter, DEBUG_TYPE,
787                       "Early If Converter", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)788 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
789 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
790 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
791 INITIALIZE_PASS_END(EarlyIfConverter, DEBUG_TYPE,
792                     "Early If Converter", false, false)
793 
794 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
795   AU.addRequired<MachineBranchProbabilityInfo>();
796   AU.addRequired<MachineDominatorTree>();
797   AU.addPreserved<MachineDominatorTree>();
798   AU.addRequired<MachineLoopInfo>();
799   AU.addPreserved<MachineLoopInfo>();
800   AU.addRequired<MachineTraceMetrics>();
801   AU.addPreserved<MachineTraceMetrics>();
802   MachineFunctionPass::getAnalysisUsage(AU);
803 }
804 
805 namespace {
806 /// Update the dominator tree after if-conversion erased some blocks.
updateDomTree(MachineDominatorTree * DomTree,const SSAIfConv & IfConv,ArrayRef<MachineBasicBlock * > Removed)807 void updateDomTree(MachineDominatorTree *DomTree, const SSAIfConv &IfConv,
808                    ArrayRef<MachineBasicBlock *> Removed) {
809   // convertIf can remove TBB, FBB, and Tail can be merged into Head.
810   // TBB and FBB should not dominate any blocks.
811   // Tail children should be transferred to Head.
812   MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
813   for (auto B : Removed) {
814     MachineDomTreeNode *Node = DomTree->getNode(B);
815     assert(Node != HeadNode && "Cannot erase the head node");
816     while (Node->getNumChildren()) {
817       assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
818       DomTree->changeImmediateDominator(Node->back(), HeadNode);
819     }
820     DomTree->eraseNode(B);
821   }
822 }
823 
824 /// Update LoopInfo after if-conversion.
updateLoops(MachineLoopInfo * Loops,ArrayRef<MachineBasicBlock * > Removed)825 void updateLoops(MachineLoopInfo *Loops,
826                  ArrayRef<MachineBasicBlock *> Removed) {
827   if (!Loops)
828     return;
829   // If-conversion doesn't change loop structure, and it doesn't mess with back
830   // edges, so updating LoopInfo is simply removing the dead blocks.
831   for (auto B : Removed)
832     Loops->removeBlock(B);
833 }
834 } // namespace
835 
836 /// Invalidate MachineTraceMetrics before if-conversion.
invalidateTraces()837 void EarlyIfConverter::invalidateTraces() {
838   Traces->verifyAnalysis();
839   Traces->invalidate(IfConv.Head);
840   Traces->invalidate(IfConv.Tail);
841   Traces->invalidate(IfConv.TBB);
842   Traces->invalidate(IfConv.FBB);
843   Traces->verifyAnalysis();
844 }
845 
846 // Adjust cycles with downward saturation.
adjCycles(unsigned Cyc,int Delta)847 static unsigned adjCycles(unsigned Cyc, int Delta) {
848   if (Delta < 0 && Cyc + Delta > Cyc)
849     return 0;
850   return Cyc + Delta;
851 }
852 
853 namespace {
854 /// Helper class to simplify emission of cycle counts into optimization remarks.
855 struct Cycles {
856   const char *Key;
857   unsigned Value;
858 };
operator <<(Remark & R,Cycles C)859 template <typename Remark> Remark &operator<<(Remark &R, Cycles C) {
860   return R << ore::NV(C.Key, C.Value) << (C.Value == 1 ? " cycle" : " cycles");
861 }
862 } // anonymous namespace
863 
864 /// Apply cost model and heuristics to the if-conversion in IfConv.
865 /// Return true if the conversion is a good idea.
866 ///
shouldConvertIf()867 bool EarlyIfConverter::shouldConvertIf() {
868   // Stress testing mode disables all cost considerations.
869   if (Stress)
870     return true;
871 
872   if (!MinInstr)
873     MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
874 
875   MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
876   MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
877   LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
878   unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
879                               FBBTrace.getCriticalPath());
880 
881   // Set a somewhat arbitrary limit on the critical path extension we accept.
882   unsigned CritLimit = SchedModel.MispredictPenalty/2;
883 
884   MachineBasicBlock &MBB = *IfConv.Head;
885   MachineOptimizationRemarkEmitter MORE(*MBB.getParent(), nullptr);
886 
887   // If-conversion only makes sense when there is unexploited ILP. Compute the
888   // maximum-ILP resource length of the trace after if-conversion. Compare it
889   // to the shortest critical path.
890   SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
891   if (IfConv.TBB != IfConv.Tail)
892     ExtraBlocks.push_back(IfConv.TBB);
893   unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
894   LLVM_DEBUG(dbgs() << "Resource length " << ResLength
895                     << ", minimal critical path " << MinCrit << '\n');
896   if (ResLength > MinCrit + CritLimit) {
897     LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
898     MORE.emit([&]() {
899       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
900                                         MBB.findDebugLoc(MBB.back()), &MBB);
901       R << "did not if-convert branch: the resulting critical path ("
902         << Cycles{"ResLength", ResLength}
903         << ") would extend the shorter leg's critical path ("
904         << Cycles{"MinCrit", MinCrit} << ") by more than the threshold of "
905         << Cycles{"CritLimit", CritLimit}
906         << ", which cannot be hidden by available ILP.";
907       return R;
908     });
909     return false;
910   }
911 
912   // Assume that the depth of the first head terminator will also be the depth
913   // of the select instruction inserted, as determined by the flag dependency.
914   // TBB / FBB data dependencies may delay the select even more.
915   MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
916   unsigned BranchDepth =
917       HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
918   LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
919 
920   // Look at all the tail phis, and compute the critical path extension caused
921   // by inserting select instructions.
922   MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
923   struct CriticalPathInfo {
924     unsigned Extra; // Count of extra cycles that the component adds.
925     unsigned Depth; // Absolute depth of the component in cycles.
926   };
927   CriticalPathInfo Cond{};
928   CriticalPathInfo TBlock{};
929   CriticalPathInfo FBlock{};
930   bool ShouldConvert = true;
931   for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
932     SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
933     unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
934     unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
935     LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
936 
937     // The condition is pulled into the critical path.
938     unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
939     if (CondDepth > MaxDepth) {
940       unsigned Extra = CondDepth - MaxDepth;
941       LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
942       if (Extra > Cond.Extra)
943         Cond = {Extra, CondDepth};
944       if (Extra > CritLimit) {
945         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
946         ShouldConvert = false;
947       }
948     }
949 
950     // The TBB value is pulled into the critical path.
951     unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
952     if (TDepth > MaxDepth) {
953       unsigned Extra = TDepth - MaxDepth;
954       LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
955       if (Extra > TBlock.Extra)
956         TBlock = {Extra, TDepth};
957       if (Extra > CritLimit) {
958         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
959         ShouldConvert = false;
960       }
961     }
962 
963     // The FBB value is pulled into the critical path.
964     unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
965     if (FDepth > MaxDepth) {
966       unsigned Extra = FDepth - MaxDepth;
967       LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
968       if (Extra > FBlock.Extra)
969         FBlock = {Extra, FDepth};
970       if (Extra > CritLimit) {
971         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
972         ShouldConvert = false;
973       }
974     }
975   }
976 
977   // Organize by "short" and "long" legs, since the diagnostics get confusing
978   // when referring to the "true" and "false" sides of the branch, given that
979   // those don't always correlate with what the user wrote in source-terms.
980   const CriticalPathInfo Short = TBlock.Extra > FBlock.Extra ? FBlock : TBlock;
981   const CriticalPathInfo Long = TBlock.Extra > FBlock.Extra ? TBlock : FBlock;
982 
983   if (ShouldConvert) {
984     MORE.emit([&]() {
985       MachineOptimizationRemark R(DEBUG_TYPE, "IfConversion",
986                                   MBB.back().getDebugLoc(), &MBB);
987       R << "performing if-conversion on branch: the condition adds "
988         << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
989       if (Short.Extra > 0)
990         R << ", and the short leg adds another "
991           << Cycles{"ShortCycles", Short.Extra};
992       if (Long.Extra > 0)
993         R << ", and the long leg adds another "
994           << Cycles{"LongCycles", Long.Extra};
995       R << ", each staying under the threshold of "
996         << Cycles{"CritLimit", CritLimit} << ".";
997       return R;
998     });
999   } else {
1000     MORE.emit([&]() {
1001       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
1002                                         MBB.back().getDebugLoc(), &MBB);
1003       R << "did not if-convert branch: the condition would add "
1004         << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
1005       if (Cond.Extra > CritLimit)
1006         R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1007       if (Short.Extra > 0) {
1008         R << ", and the short leg would add another "
1009           << Cycles{"ShortCycles", Short.Extra};
1010         if (Short.Extra > CritLimit)
1011           R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1012       }
1013       if (Long.Extra > 0) {
1014         R << ", and the long leg would add another "
1015           << Cycles{"LongCycles", Long.Extra};
1016         if (Long.Extra > CritLimit)
1017           R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1018       }
1019       R << ".";
1020       return R;
1021     });
1022   }
1023 
1024   return ShouldConvert;
1025 }
1026 
1027 /// Attempt repeated if-conversion on MBB, return true if successful.
1028 ///
tryConvertIf(MachineBasicBlock * MBB)1029 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
1030   bool Changed = false;
1031   while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
1032     // If-convert MBB and update analyses.
1033     invalidateTraces();
1034     SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
1035     IfConv.convertIf(RemovedBlocks);
1036     Changed = true;
1037     updateDomTree(DomTree, IfConv, RemovedBlocks);
1038     updateLoops(Loops, RemovedBlocks);
1039   }
1040   return Changed;
1041 }
1042 
runOnMachineFunction(MachineFunction & MF)1043 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
1044   LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
1045                     << "********** Function: " << MF.getName() << '\n');
1046   if (skipFunction(MF.getFunction()))
1047     return false;
1048 
1049   // Only run if conversion if the target wants it.
1050   const TargetSubtargetInfo &STI = MF.getSubtarget();
1051   if (!STI.enableEarlyIfConversion())
1052     return false;
1053 
1054   TII = STI.getInstrInfo();
1055   TRI = STI.getRegisterInfo();
1056   SchedModel = STI.getSchedModel();
1057   MRI = &MF.getRegInfo();
1058   DomTree = &getAnalysis<MachineDominatorTree>();
1059   Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1060   Traces = &getAnalysis<MachineTraceMetrics>();
1061   MinInstr = nullptr;
1062 
1063   bool Changed = false;
1064   IfConv.runOnMachineFunction(MF);
1065 
1066   // Visit blocks in dominator tree post-order. The post-order enables nested
1067   // if-conversion in a single pass. The tryConvertIf() function may erase
1068   // blocks, but only blocks dominated by the head block. This makes it safe to
1069   // update the dominator tree while the post-order iterator is still active.
1070   for (auto DomNode : post_order(DomTree))
1071     if (tryConvertIf(DomNode->getBlock()))
1072       Changed = true;
1073 
1074   return Changed;
1075 }
1076 
1077 //===----------------------------------------------------------------------===//
1078 //                           EarlyIfPredicator Pass
1079 //===----------------------------------------------------------------------===//
1080 
1081 namespace {
1082 class EarlyIfPredicator : public MachineFunctionPass {
1083   const TargetInstrInfo *TII;
1084   const TargetRegisterInfo *TRI;
1085   TargetSchedModel SchedModel;
1086   MachineRegisterInfo *MRI;
1087   MachineDominatorTree *DomTree;
1088   MachineBranchProbabilityInfo *MBPI;
1089   MachineLoopInfo *Loops;
1090   SSAIfConv IfConv;
1091 
1092 public:
1093   static char ID;
EarlyIfPredicator()1094   EarlyIfPredicator() : MachineFunctionPass(ID) {}
1095   void getAnalysisUsage(AnalysisUsage &AU) const override;
1096   bool runOnMachineFunction(MachineFunction &MF) override;
getPassName() const1097   StringRef getPassName() const override { return "Early If-predicator"; }
1098 
1099 protected:
1100   bool tryConvertIf(MachineBasicBlock *);
1101   bool shouldConvertIf();
1102 };
1103 } // end anonymous namespace
1104 
1105 #undef DEBUG_TYPE
1106 #define DEBUG_TYPE "early-if-predicator"
1107 
1108 char EarlyIfPredicator::ID = 0;
1109 char &llvm::EarlyIfPredicatorID = EarlyIfPredicator::ID;
1110 
1111 INITIALIZE_PASS_BEGIN(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator",
1112                       false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)1113 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1114 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1115 INITIALIZE_PASS_END(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator", false,
1116                     false)
1117 
1118 void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage &AU) const {
1119   AU.addRequired<MachineBranchProbabilityInfo>();
1120   AU.addRequired<MachineDominatorTree>();
1121   AU.addPreserved<MachineDominatorTree>();
1122   AU.addRequired<MachineLoopInfo>();
1123   AU.addPreserved<MachineLoopInfo>();
1124   MachineFunctionPass::getAnalysisUsage(AU);
1125 }
1126 
1127 /// Apply the target heuristic to decide if the transformation is profitable.
shouldConvertIf()1128 bool EarlyIfPredicator::shouldConvertIf() {
1129   auto TrueProbability = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
1130   if (IfConv.isTriangle()) {
1131     MachineBasicBlock &IfBlock =
1132         (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
1133 
1134     unsigned ExtraPredCost = 0;
1135     unsigned Cycles = 0;
1136     for (MachineInstr &I : IfBlock) {
1137       unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1138       if (NumCycles > 1)
1139         Cycles += NumCycles - 1;
1140       ExtraPredCost += TII->getPredicationCost(I);
1141     }
1142 
1143     return TII->isProfitableToIfCvt(IfBlock, Cycles, ExtraPredCost,
1144                                     TrueProbability);
1145   }
1146   unsigned TExtra = 0;
1147   unsigned FExtra = 0;
1148   unsigned TCycle = 0;
1149   unsigned FCycle = 0;
1150   for (MachineInstr &I : *IfConv.TBB) {
1151     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1152     if (NumCycles > 1)
1153       TCycle += NumCycles - 1;
1154     TExtra += TII->getPredicationCost(I);
1155   }
1156   for (MachineInstr &I : *IfConv.FBB) {
1157     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1158     if (NumCycles > 1)
1159       FCycle += NumCycles - 1;
1160     FExtra += TII->getPredicationCost(I);
1161   }
1162   return TII->isProfitableToIfCvt(*IfConv.TBB, TCycle, TExtra, *IfConv.FBB,
1163                                   FCycle, FExtra, TrueProbability);
1164 }
1165 
1166 /// Attempt repeated if-conversion on MBB, return true if successful.
1167 ///
tryConvertIf(MachineBasicBlock * MBB)1168 bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *MBB) {
1169   bool Changed = false;
1170   while (IfConv.canConvertIf(MBB, /*Predicate*/ true) && shouldConvertIf()) {
1171     // If-convert MBB and update analyses.
1172     SmallVector<MachineBasicBlock *, 4> RemovedBlocks;
1173     IfConv.convertIf(RemovedBlocks, /*Predicate*/ true);
1174     Changed = true;
1175     updateDomTree(DomTree, IfConv, RemovedBlocks);
1176     updateLoops(Loops, RemovedBlocks);
1177   }
1178   return Changed;
1179 }
1180 
runOnMachineFunction(MachineFunction & MF)1181 bool EarlyIfPredicator::runOnMachineFunction(MachineFunction &MF) {
1182   LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1183                     << "********** Function: " << MF.getName() << '\n');
1184   if (skipFunction(MF.getFunction()))
1185     return false;
1186 
1187   const TargetSubtargetInfo &STI = MF.getSubtarget();
1188   TII = STI.getInstrInfo();
1189   TRI = STI.getRegisterInfo();
1190   MRI = &MF.getRegInfo();
1191   SchedModel.init(&STI);
1192   DomTree = &getAnalysis<MachineDominatorTree>();
1193   Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1194   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1195 
1196   bool Changed = false;
1197   IfConv.runOnMachineFunction(MF);
1198 
1199   // Visit blocks in dominator tree post-order. The post-order enables nested
1200   // if-conversion in a single pass. The tryConvertIf() function may erase
1201   // blocks, but only blocks dominated by the head block. This makes it safe to
1202   // update the dominator tree while the post-order iterator is still active.
1203   for (auto DomNode : post_order(DomTree))
1204     if (tryConvertIf(DomNode->getBlock()))
1205       Changed = true;
1206 
1207   return Changed;
1208 }
1209