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.
103   bool isTriangle() const { return TBB == Tail || FBB == Tail; }
104 
105   /// Returns the Tail predecessor for the True side.
106   MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
107 
108   /// Returns the Tail predecessor for the  False side.
109   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 
118     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.
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 ///
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.
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 ///
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.
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 ///
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 ///
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 /// replacePHIInstrs - Completely replace PHI instructions with selects.
561 /// This is possible when the only Tail predecessors are the if-converted
562 /// blocks.
563 void SSAIfConv::replacePHIInstrs() {
564   assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
565   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
566   assert(FirstTerm != Head->end() && "No terminators");
567   DebugLoc HeadDL = FirstTerm->getDebugLoc();
568 
569   // Convert all PHIs to select instructions inserted before FirstTerm.
570   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
571     PHIInfo &PI = PHIs[i];
572     LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
573     Register DstReg = PI.PHI->getOperand(0).getReg();
574     TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
575     LLVM_DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
576     PI.PHI->eraseFromParent();
577     PI.PHI = nullptr;
578   }
579 }
580 
581 /// rewritePHIOperands - When there are additional Tail predecessors, insert
582 /// select instructions in Head and rewrite PHI operands to use the selects.
583 /// Keep the PHI instructions in Tail to handle the other predecessors.
584 void SSAIfConv::rewritePHIOperands() {
585   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
586   assert(FirstTerm != Head->end() && "No terminators");
587   DebugLoc HeadDL = FirstTerm->getDebugLoc();
588 
589   // Convert all PHIs to select instructions inserted before FirstTerm.
590   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
591     PHIInfo &PI = PHIs[i];
592     unsigned DstReg = 0;
593 
594     LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
595     if (PI.TReg == PI.FReg) {
596       // We do not need the select instruction if both incoming values are
597       // equal.
598       DstReg = PI.TReg;
599     } else {
600       Register PHIDst = PI.PHI->getOperand(0).getReg();
601       DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
602       TII->insertSelect(*Head, FirstTerm, HeadDL,
603                          DstReg, Cond, PI.TReg, PI.FReg);
604       LLVM_DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
605     }
606 
607     // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
608     for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
609       MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
610       if (MBB == getTPred()) {
611         PI.PHI->getOperand(i-1).setMBB(Head);
612         PI.PHI->getOperand(i-2).setReg(DstReg);
613       } else if (MBB == getFPred()) {
614         PI.PHI->RemoveOperand(i-1);
615         PI.PHI->RemoveOperand(i-2);
616       }
617     }
618     LLVM_DEBUG(dbgs() << "          --> " << *PI.PHI);
619   }
620 }
621 
622 /// convertIf - Execute the if conversion after canConvertIf has determined the
623 /// feasibility.
624 ///
625 /// Any basic blocks erased will be added to RemovedBlocks.
626 ///
627 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
628                           bool Predicate) {
629   assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
630 
631   // Update statistics.
632   if (isTriangle())
633     ++NumTrianglesConv;
634   else
635     ++NumDiamondsConv;
636 
637   // Move all instructions into Head, except for the terminators.
638   if (TBB != Tail) {
639     if (Predicate)
640       PredicateBlock(TBB, /*ReversePredicate=*/false);
641     Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
642   }
643   if (FBB != Tail) {
644     if (Predicate)
645       PredicateBlock(FBB, /*ReversePredicate=*/true);
646     Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
647   }
648   // Are there extra Tail predecessors?
649   bool ExtraPreds = Tail->pred_size() != 2;
650   if (ExtraPreds)
651     rewritePHIOperands();
652   else
653     replacePHIInstrs();
654 
655   // Fix up the CFG, temporarily leave Head without any successors.
656   Head->removeSuccessor(TBB);
657   Head->removeSuccessor(FBB, true);
658   if (TBB != Tail)
659     TBB->removeSuccessor(Tail, true);
660   if (FBB != Tail)
661     FBB->removeSuccessor(Tail, true);
662 
663   // Fix up Head's terminators.
664   // It should become a single branch or a fallthrough.
665   DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
666   TII->removeBranch(*Head);
667 
668   // Erase the now empty conditional blocks. It is likely that Head can fall
669   // through to Tail, and we can join the two blocks.
670   if (TBB != Tail) {
671     RemovedBlocks.push_back(TBB);
672     TBB->eraseFromParent();
673   }
674   if (FBB != Tail) {
675     RemovedBlocks.push_back(FBB);
676     FBB->eraseFromParent();
677   }
678 
679   assert(Head->succ_empty() && "Additional head successors?");
680   if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
681     // Splice Tail onto the end of Head.
682     LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
683                       << " into head " << printMBBReference(*Head) << '\n');
684     Head->splice(Head->end(), Tail,
685                      Tail->begin(), Tail->end());
686     Head->transferSuccessorsAndUpdatePHIs(Tail);
687     RemovedBlocks.push_back(Tail);
688     Tail->eraseFromParent();
689   } else {
690     // We need a branch to Tail, let code placement work it out later.
691     LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
692     SmallVector<MachineOperand, 0> EmptyCond;
693     TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
694     Head->addSuccessor(Tail);
695   }
696   LLVM_DEBUG(dbgs() << *Head);
697 }
698 
699 //===----------------------------------------------------------------------===//
700 //                           EarlyIfConverter Pass
701 //===----------------------------------------------------------------------===//
702 
703 namespace {
704 class EarlyIfConverter : public MachineFunctionPass {
705   const TargetInstrInfo *TII;
706   const TargetRegisterInfo *TRI;
707   MCSchedModel SchedModel;
708   MachineRegisterInfo *MRI;
709   MachineDominatorTree *DomTree;
710   MachineLoopInfo *Loops;
711   MachineTraceMetrics *Traces;
712   MachineTraceMetrics::Ensemble *MinInstr;
713   SSAIfConv IfConv;
714 
715 public:
716   static char ID;
717   EarlyIfConverter() : MachineFunctionPass(ID) {}
718   void getAnalysisUsage(AnalysisUsage &AU) const override;
719   bool runOnMachineFunction(MachineFunction &MF) override;
720   StringRef getPassName() const override { return "Early If-Conversion"; }
721 
722 private:
723   bool tryConvertIf(MachineBasicBlock*);
724   void invalidateTraces();
725   bool shouldConvertIf();
726 };
727 } // end anonymous namespace
728 
729 char EarlyIfConverter::ID = 0;
730 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
731 
732 INITIALIZE_PASS_BEGIN(EarlyIfConverter, DEBUG_TYPE,
733                       "Early If Converter", false, false)
734 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
735 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
736 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
737 INITIALIZE_PASS_END(EarlyIfConverter, DEBUG_TYPE,
738                     "Early If Converter", false, false)
739 
740 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
741   AU.addRequired<MachineBranchProbabilityInfo>();
742   AU.addRequired<MachineDominatorTree>();
743   AU.addPreserved<MachineDominatorTree>();
744   AU.addRequired<MachineLoopInfo>();
745   AU.addPreserved<MachineLoopInfo>();
746   AU.addRequired<MachineTraceMetrics>();
747   AU.addPreserved<MachineTraceMetrics>();
748   MachineFunctionPass::getAnalysisUsage(AU);
749 }
750 
751 namespace {
752 /// Update the dominator tree after if-conversion erased some blocks.
753 void updateDomTree(MachineDominatorTree *DomTree, const SSAIfConv &IfConv,
754                    ArrayRef<MachineBasicBlock *> Removed) {
755   // convertIf can remove TBB, FBB, and Tail can be merged into Head.
756   // TBB and FBB should not dominate any blocks.
757   // Tail children should be transferred to Head.
758   MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
759   for (auto B : Removed) {
760     MachineDomTreeNode *Node = DomTree->getNode(B);
761     assert(Node != HeadNode && "Cannot erase the head node");
762     while (Node->getNumChildren()) {
763       assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
764       DomTree->changeImmediateDominator(Node->back(), HeadNode);
765     }
766     DomTree->eraseNode(B);
767   }
768 }
769 
770 /// Update LoopInfo after if-conversion.
771 void updateLoops(MachineLoopInfo *Loops,
772                  ArrayRef<MachineBasicBlock *> Removed) {
773   if (!Loops)
774     return;
775   // If-conversion doesn't change loop structure, and it doesn't mess with back
776   // edges, so updating LoopInfo is simply removing the dead blocks.
777   for (auto B : Removed)
778     Loops->removeBlock(B);
779 }
780 } // namespace
781 
782 /// Invalidate MachineTraceMetrics before if-conversion.
783 void EarlyIfConverter::invalidateTraces() {
784   Traces->verifyAnalysis();
785   Traces->invalidate(IfConv.Head);
786   Traces->invalidate(IfConv.Tail);
787   Traces->invalidate(IfConv.TBB);
788   Traces->invalidate(IfConv.FBB);
789   Traces->verifyAnalysis();
790 }
791 
792 // Adjust cycles with downward saturation.
793 static unsigned adjCycles(unsigned Cyc, int Delta) {
794   if (Delta < 0 && Cyc + Delta > Cyc)
795     return 0;
796   return Cyc + Delta;
797 }
798 
799 namespace {
800 /// Helper class to simplify emission of cycle counts into optimization remarks.
801 struct Cycles {
802   const char *Key;
803   unsigned Value;
804 };
805 template <typename Remark> Remark &operator<<(Remark &R, Cycles C) {
806   return R << ore::NV(C.Key, C.Value) << (C.Value == 1 ? " cycle" : " cycles");
807 }
808 } // anonymous namespace
809 
810 /// Apply cost model and heuristics to the if-conversion in IfConv.
811 /// Return true if the conversion is a good idea.
812 ///
813 bool EarlyIfConverter::shouldConvertIf() {
814   // Stress testing mode disables all cost considerations.
815   if (Stress)
816     return true;
817 
818   if (!MinInstr)
819     MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
820 
821   MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
822   MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
823   LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
824   unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
825                               FBBTrace.getCriticalPath());
826 
827   // Set a somewhat arbitrary limit on the critical path extension we accept.
828   unsigned CritLimit = SchedModel.MispredictPenalty/2;
829 
830   MachineBasicBlock &MBB = *IfConv.Head;
831   MachineOptimizationRemarkEmitter MORE(*MBB.getParent(), nullptr);
832 
833   // If-conversion only makes sense when there is unexploited ILP. Compute the
834   // maximum-ILP resource length of the trace after if-conversion. Compare it
835   // to the shortest critical path.
836   SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
837   if (IfConv.TBB != IfConv.Tail)
838     ExtraBlocks.push_back(IfConv.TBB);
839   unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
840   LLVM_DEBUG(dbgs() << "Resource length " << ResLength
841                     << ", minimal critical path " << MinCrit << '\n');
842   if (ResLength > MinCrit + CritLimit) {
843     LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
844     MORE.emit([&]() {
845       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
846                                         MBB.findDebugLoc(MBB.back()), &MBB);
847       R << "did not if-convert branch: the resulting critical path ("
848         << Cycles{"ResLength", ResLength}
849         << ") would extend the shorter leg's critical path ("
850         << Cycles{"MinCrit", MinCrit} << ") by more than the threshold of "
851         << Cycles{"CritLimit", CritLimit}
852         << ", which cannot be hidden by available ILP.";
853       return R;
854     });
855     return false;
856   }
857 
858   // Assume that the depth of the first head terminator will also be the depth
859   // of the select instruction inserted, as determined by the flag dependency.
860   // TBB / FBB data dependencies may delay the select even more.
861   MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
862   unsigned BranchDepth =
863       HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
864   LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
865 
866   // Look at all the tail phis, and compute the critical path extension caused
867   // by inserting select instructions.
868   MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
869   struct CriticalPathInfo {
870     unsigned Extra; // Count of extra cycles that the component adds.
871     unsigned Depth; // Absolute depth of the component in cycles.
872   };
873   CriticalPathInfo Cond{};
874   CriticalPathInfo TBlock{};
875   CriticalPathInfo FBlock{};
876   bool ShouldConvert = true;
877   for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
878     SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
879     unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
880     unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
881     LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
882 
883     // The condition is pulled into the critical path.
884     unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
885     if (CondDepth > MaxDepth) {
886       unsigned Extra = CondDepth - MaxDepth;
887       LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
888       if (Extra > Cond.Extra)
889         Cond = {Extra, CondDepth};
890       if (Extra > CritLimit) {
891         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
892         ShouldConvert = false;
893       }
894     }
895 
896     // The TBB value is pulled into the critical path.
897     unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
898     if (TDepth > MaxDepth) {
899       unsigned Extra = TDepth - MaxDepth;
900       LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
901       if (Extra > TBlock.Extra)
902         TBlock = {Extra, TDepth};
903       if (Extra > CritLimit) {
904         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
905         ShouldConvert = false;
906       }
907     }
908 
909     // The FBB value is pulled into the critical path.
910     unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
911     if (FDepth > MaxDepth) {
912       unsigned Extra = FDepth - MaxDepth;
913       LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
914       if (Extra > FBlock.Extra)
915         FBlock = {Extra, FDepth};
916       if (Extra > CritLimit) {
917         LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
918         ShouldConvert = false;
919       }
920     }
921   }
922 
923   // Organize by "short" and "long" legs, since the diagnostics get confusing
924   // when referring to the "true" and "false" sides of the branch, given that
925   // those don't always correlate with what the user wrote in source-terms.
926   const CriticalPathInfo Short = TBlock.Extra > FBlock.Extra ? FBlock : TBlock;
927   const CriticalPathInfo Long = TBlock.Extra > FBlock.Extra ? TBlock : FBlock;
928 
929   if (ShouldConvert) {
930     MORE.emit([&]() {
931       MachineOptimizationRemark R(DEBUG_TYPE, "IfConversion",
932                                   MBB.back().getDebugLoc(), &MBB);
933       R << "performing if-conversion on branch: the condition adds "
934         << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
935       if (Short.Extra > 0)
936         R << ", and the short leg adds another "
937           << Cycles{"ShortCycles", Short.Extra};
938       if (Long.Extra > 0)
939         R << ", and the long leg adds another "
940           << Cycles{"LongCycles", Long.Extra};
941       R << ", each staying under the threshold of "
942         << Cycles{"CritLimit", CritLimit} << ".";
943       return R;
944     });
945   } else {
946     MORE.emit([&]() {
947       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
948                                         MBB.back().getDebugLoc(), &MBB);
949       R << "did not if-convert branch: the condition would add "
950         << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
951       if (Cond.Extra > CritLimit)
952         R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
953       if (Short.Extra > 0) {
954         R << ", and the short leg would add another "
955           << Cycles{"ShortCycles", Short.Extra};
956         if (Short.Extra > CritLimit)
957           R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
958       }
959       if (Long.Extra > 0) {
960         R << ", and the long leg would add another "
961           << Cycles{"LongCycles", Long.Extra};
962         if (Long.Extra > CritLimit)
963           R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
964       }
965       R << ".";
966       return R;
967     });
968   }
969 
970   return ShouldConvert;
971 }
972 
973 /// Attempt repeated if-conversion on MBB, return true if successful.
974 ///
975 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
976   bool Changed = false;
977   while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
978     // If-convert MBB and update analyses.
979     invalidateTraces();
980     SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
981     IfConv.convertIf(RemovedBlocks);
982     Changed = true;
983     updateDomTree(DomTree, IfConv, RemovedBlocks);
984     updateLoops(Loops, RemovedBlocks);
985   }
986   return Changed;
987 }
988 
989 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
990   LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
991                     << "********** Function: " << MF.getName() << '\n');
992   if (skipFunction(MF.getFunction()))
993     return false;
994 
995   // Only run if conversion if the target wants it.
996   const TargetSubtargetInfo &STI = MF.getSubtarget();
997   if (!STI.enableEarlyIfConversion())
998     return false;
999 
1000   TII = STI.getInstrInfo();
1001   TRI = STI.getRegisterInfo();
1002   SchedModel = STI.getSchedModel();
1003   MRI = &MF.getRegInfo();
1004   DomTree = &getAnalysis<MachineDominatorTree>();
1005   Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1006   Traces = &getAnalysis<MachineTraceMetrics>();
1007   MinInstr = nullptr;
1008 
1009   bool Changed = false;
1010   IfConv.runOnMachineFunction(MF);
1011 
1012   // Visit blocks in dominator tree post-order. The post-order enables nested
1013   // if-conversion in a single pass. The tryConvertIf() function may erase
1014   // blocks, but only blocks dominated by the head block. This makes it safe to
1015   // update the dominator tree while the post-order iterator is still active.
1016   for (auto DomNode : post_order(DomTree))
1017     if (tryConvertIf(DomNode->getBlock()))
1018       Changed = true;
1019 
1020   return Changed;
1021 }
1022 
1023 //===----------------------------------------------------------------------===//
1024 //                           EarlyIfPredicator Pass
1025 //===----------------------------------------------------------------------===//
1026 
1027 namespace {
1028 class EarlyIfPredicator : public MachineFunctionPass {
1029   const TargetInstrInfo *TII;
1030   const TargetRegisterInfo *TRI;
1031   TargetSchedModel SchedModel;
1032   MachineRegisterInfo *MRI;
1033   MachineDominatorTree *DomTree;
1034   MachineBranchProbabilityInfo *MBPI;
1035   MachineLoopInfo *Loops;
1036   SSAIfConv IfConv;
1037 
1038 public:
1039   static char ID;
1040   EarlyIfPredicator() : MachineFunctionPass(ID) {}
1041   void getAnalysisUsage(AnalysisUsage &AU) const override;
1042   bool runOnMachineFunction(MachineFunction &MF) override;
1043   StringRef getPassName() const override { return "Early If-predicator"; }
1044 
1045 protected:
1046   bool tryConvertIf(MachineBasicBlock *);
1047   bool shouldConvertIf();
1048 };
1049 } // end anonymous namespace
1050 
1051 #undef DEBUG_TYPE
1052 #define DEBUG_TYPE "early-if-predicator"
1053 
1054 char EarlyIfPredicator::ID = 0;
1055 char &llvm::EarlyIfPredicatorID = EarlyIfPredicator::ID;
1056 
1057 INITIALIZE_PASS_BEGIN(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator",
1058                       false, false)
1059 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1060 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1061 INITIALIZE_PASS_END(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator", false,
1062                     false)
1063 
1064 void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage &AU) const {
1065   AU.addRequired<MachineBranchProbabilityInfo>();
1066   AU.addRequired<MachineDominatorTree>();
1067   AU.addPreserved<MachineDominatorTree>();
1068   AU.addRequired<MachineLoopInfo>();
1069   AU.addPreserved<MachineLoopInfo>();
1070   MachineFunctionPass::getAnalysisUsage(AU);
1071 }
1072 
1073 /// Apply the target heuristic to decide if the transformation is profitable.
1074 bool EarlyIfPredicator::shouldConvertIf() {
1075   auto TrueProbability = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
1076   if (IfConv.isTriangle()) {
1077     MachineBasicBlock &IfBlock =
1078         (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
1079 
1080     unsigned ExtraPredCost = 0;
1081     unsigned Cycles = 0;
1082     for (MachineInstr &I : IfBlock) {
1083       unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1084       if (NumCycles > 1)
1085         Cycles += NumCycles - 1;
1086       ExtraPredCost += TII->getPredicationCost(I);
1087     }
1088 
1089     return TII->isProfitableToIfCvt(IfBlock, Cycles, ExtraPredCost,
1090                                     TrueProbability);
1091   }
1092   unsigned TExtra = 0;
1093   unsigned FExtra = 0;
1094   unsigned TCycle = 0;
1095   unsigned FCycle = 0;
1096   for (MachineInstr &I : *IfConv.TBB) {
1097     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1098     if (NumCycles > 1)
1099       TCycle += NumCycles - 1;
1100     TExtra += TII->getPredicationCost(I);
1101   }
1102   for (MachineInstr &I : *IfConv.FBB) {
1103     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1104     if (NumCycles > 1)
1105       FCycle += NumCycles - 1;
1106     FExtra += TII->getPredicationCost(I);
1107   }
1108   return TII->isProfitableToIfCvt(*IfConv.TBB, TCycle, TExtra, *IfConv.FBB,
1109                                   FCycle, FExtra, TrueProbability);
1110 }
1111 
1112 /// Attempt repeated if-conversion on MBB, return true if successful.
1113 ///
1114 bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *MBB) {
1115   bool Changed = false;
1116   while (IfConv.canConvertIf(MBB, /*Predicate*/ true) && shouldConvertIf()) {
1117     // If-convert MBB and update analyses.
1118     SmallVector<MachineBasicBlock *, 4> RemovedBlocks;
1119     IfConv.convertIf(RemovedBlocks, /*Predicate*/ true);
1120     Changed = true;
1121     updateDomTree(DomTree, IfConv, RemovedBlocks);
1122     updateLoops(Loops, RemovedBlocks);
1123   }
1124   return Changed;
1125 }
1126 
1127 bool EarlyIfPredicator::runOnMachineFunction(MachineFunction &MF) {
1128   LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1129                     << "********** Function: " << MF.getName() << '\n');
1130   if (skipFunction(MF.getFunction()))
1131     return false;
1132 
1133   const TargetSubtargetInfo &STI = MF.getSubtarget();
1134   TII = STI.getInstrInfo();
1135   TRI = STI.getRegisterInfo();
1136   MRI = &MF.getRegInfo();
1137   SchedModel.init(&STI);
1138   DomTree = &getAnalysis<MachineDominatorTree>();
1139   Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1140   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1141 
1142   bool Changed = false;
1143   IfConv.runOnMachineFunction(MF);
1144 
1145   // Visit blocks in dominator tree post-order. The post-order enables nested
1146   // if-conversion in a single pass. The tryConvertIf() function may erase
1147   // blocks, but only blocks dominated by the head block. This makes it safe to
1148   // update the dominator tree while the post-order iterator is still active.
1149   for (auto DomNode : post_order(DomTree))
1150     if (tryConvertIf(DomNode->getBlock()))
1151       Changed = true;
1152 
1153   return Changed;
1154 }
1155