1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the machine instruction level if-conversion pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "ifcvt"
15 #include "llvm/Function.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/Statistic.h"
29 // Hidden options for help debugging.
30 cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31 cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32 cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33 cl::opt<bool> DisableSimple("disable-ifcvt-simple",
34 cl::init(false), cl::Hidden);
35 cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
36 cl::init(false), cl::Hidden);
37 cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
38 cl::init(false), cl::Hidden);
39 cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
40 cl::init(false), cl::Hidden);
41 cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
42 cl::init(false), cl::Hidden);
43 cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
44 cl::init(false), cl::Hidden);
47 STATISTIC(NumSimple, "Number of simple if-conversions performed");
48 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
49 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
50 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
51 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
52 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
53 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
56 class IfConverter : public MachineFunctionPass {
58 ICNotAnalyzed, // BB has not been analyzed.
59 ICReAnalyze, // BB must be re-analyzed.
60 ICNotClassfied, // BB data valid, but not classified.
61 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
62 ICSimpleFalse, // Same as ICSimple, but on the false path.
63 ICTriangle, // BB is entry of a triangle sub-CFG.
64 ICTriangleFalse, // Same as ICTriangle, but on the false path.
65 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
66 ICDiamond, // BB is entry of a diamond sub-CFG.
67 ICChild, // BB is part of the sub-CFG that'll be predicated.
68 ICDead // BB cannot be if-converted again.
71 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
72 /// if-conversion feasibility analysis. This includes results from
73 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
74 /// classification, and common tail block of its successors (if it's a
75 /// diamond shape), its size, whether it's predicable, and whether any
76 /// instruction can clobber the 'would-be' predicate.
78 /// Kind - Type of block. See BBICKind.
79 /// NonPredSize - Number of non-predicated instructions.
80 /// IsAnalyzable - True if AnalyzeBranch() returns false.
81 /// ModifyPredicate - True if BB would modify the predicate (e.g. has
83 /// BB - Corresponding MachineBasicBlock.
84 /// TrueBB / FalseBB- See AnalyzeBranch().
85 /// BrCond - Conditions for end of block conditional branches.
86 /// Predicate - Predicate used in the BB.
93 MachineBasicBlock *BB;
94 MachineBasicBlock *TrueBB;
95 MachineBasicBlock *FalseBB;
96 MachineBasicBlock *TailBB;
97 std::vector<MachineOperand> BrCond;
98 std::vector<MachineOperand> Predicate;
99 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
100 IsAnalyzable(false), HasFallThrough(false),
101 ModifyPredicate(false),
102 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
105 /// Roots - Basic blocks that do not have successors. These are the starting
106 /// points of Graph traversal.
107 std::vector<MachineBasicBlock*> Roots;
109 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
110 /// basic block number.
111 std::vector<BBInfo> BBAnalysis;
113 const TargetLowering *TLI;
114 const TargetInstrInfo *TII;
118 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
120 virtual bool runOnMachineFunction(MachineFunction &MF);
121 virtual const char *getPassName() const { return "If converter"; }
124 bool ReverseBranchCondition(BBInfo &BBI);
125 bool ValidSimple(BBInfo &TrueBBI) const;
126 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
127 bool FalseBranch = false) const;
128 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
129 void ScanInstructions(BBInfo &BBI);
130 void AnalyzeBlock(MachineBasicBlock *BB);
131 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
132 bool isTriangle = false, bool RevBranch = false);
133 bool AttemptRestructuring(BBInfo &BBI);
134 bool AnalyzeBlocks(MachineFunction &MF,
135 std::vector<BBInfo*> &Candidates);
136 void ReTryPreds(MachineBasicBlock *BB);
137 void RemoveExtraEdges(BBInfo &BBI);
138 bool IfConvertSimple(BBInfo &BBI);
139 bool IfConvertTriangle(BBInfo &BBI);
140 bool IfConvertDiamond(BBInfo &BBI);
141 void PredicateBlock(BBInfo &BBI,
142 std::vector<MachineOperand> &Cond,
143 bool IgnoreTerm = false);
144 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
146 // blockAlwaysFallThrough - Block ends without a terminator.
147 bool blockAlwaysFallThrough(BBInfo &BBI) const {
148 return BBI.IsAnalyzable && BBI.TrueBB == NULL;
151 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
152 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
153 // Favor diamond over triangle, etc.
154 return (unsigned)C1->Kind < (unsigned)C2->Kind;
157 char IfConverter::ID = 0;
160 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
162 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
163 TLI = MF.getTarget().getTargetLowering();
164 TII = MF.getTarget().getInstrInfo();
165 if (!TII) return false;
167 static int FnNum = -1;
168 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
169 << MF.getFunction()->getName() << "\'";
171 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
172 DOUT << " skipped\n";
178 BBAnalysis.resize(MF.getNumBlockIDs());
180 // Look for root nodes, i.e. blocks without successors.
181 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
182 if (I->succ_size() == 0)
185 std::vector<BBInfo*> Candidates;
187 while (IfCvtLimit == -1 || (int)NumIfConvBBs < IfCvtLimit) {
188 // Do an intial analysis for each basic block and finding all the potential
189 // candidates to perform if-convesion.
190 bool Change = AnalyzeBlocks(MF, Candidates);
191 while (!Candidates.empty()) {
192 BBInfo &BBI = *Candidates.back();
193 Candidates.pop_back();
197 default: assert(false && "Unexpected!");
200 // One or more of 'children' have been modified, abort!
202 // Block has been already been if-converted, abort!
205 case ICSimpleFalse: {
206 bool isFalse = BBI.Kind == ICSimpleFalse;
207 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
208 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
209 << "): BB#" << BBI.BB->getNumber() << " ("
210 << ((BBI.Kind == ICSimpleFalse)
211 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
212 RetVal = IfConvertSimple(BBI);
213 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
215 if (isFalse) NumSimpleFalse++;
220 case ICTriangleFalse:
221 case ICTriangleFRev: {
222 bool isFalse = BBI.Kind == ICTriangleFalse;
223 bool isFalseRev = BBI.Kind == ICTriangleFRev;
224 if (DisableTriangle && !isFalse && !isFalseRev) break;
225 if (DisableTriangleF && isFalse) break;
226 if (DisableTriangleFR && isFalseRev) break;
227 DOUT << "Ifcvt (Triangle";
231 DOUT << " false/rev";
232 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
233 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
235 RetVal = IfConvertTriangle(BBI);
236 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
238 if (isFalseRev) NumTriangleFRev++;
239 else if (isFalse) NumTriangleFalse++;
245 if (DisableDiamond) break;
246 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
247 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
249 DOUT << "," << BBI.TailBB->getNumber() ;
251 RetVal = IfConvertDiamond(BBI);
252 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
253 if (RetVal) NumDiamonds++;
258 if (IfCvtLimit != -1 && (int)NumIfConvBBs >= IfCvtLimit)
264 MadeChange |= Change;
273 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
274 MachineBasicBlock *TrueBB) {
275 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
276 E = BB->succ_end(); SI != E; ++SI) {
277 MachineBasicBlock *SuccBB = *SI;
278 if (SuccBB != TrueBB)
284 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
285 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
286 TII->RemoveBranch(*BBI.BB);
287 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
288 std::swap(BBI.TrueBB, BBI.FalseBB);
294 /// getNextBlock - Returns the next block in the function blocks ordering. If
295 /// it is the end, returns NULL.
296 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
297 MachineFunction::iterator I = BB;
298 MachineFunction::iterator E = BB->getParent()->end();
304 /// ValidSimple - Returns true if the 'true' block (along with its
305 /// predecessor) forms a valid simple shape for ifcvt.
306 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
307 return !blockAlwaysFallThrough(TrueBBI) &&
308 TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
311 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
312 /// with their common predecessor) forms a valid triangle shape for ifcvt.
313 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
314 bool FalseBranch) const {
315 if (TrueBBI.BB->pred_size() != 1)
318 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
319 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
320 MachineFunction::iterator I = TrueBBI.BB;
321 if (++I == TrueBBI.BB->getParent()->end())
325 return TExit && TExit == FalseBBI.BB;
328 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
329 /// with their common predecessor) forms a valid diamond shape for ifcvt.
330 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
331 MachineBasicBlock *TT = TrueBBI.TrueBB;
332 MachineBasicBlock *FT = FalseBBI.TrueBB;
334 if (!TT && blockAlwaysFallThrough(TrueBBI))
335 TT = getNextBlock(TrueBBI.BB);
336 if (!FT && blockAlwaysFallThrough(FalseBBI))
337 FT = getNextBlock(FalseBBI.BB);
340 if (TT == NULL && (TrueBBI.IsAnalyzable || FalseBBI.IsAnalyzable))
342 // FIXME: Allow false block to have an early exit?
343 return (TrueBBI.BB->pred_size() == 1 &&
344 FalseBBI.BB->pred_size() == 1 &&
345 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
348 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
349 /// the specified block. Record its successors and whether it looks like an
350 /// if-conversion candidate.
351 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
352 BBInfo &BBI = BBAnalysis[BB->getNumber()];
354 if (BBI.Kind == ICReAnalyze) {
356 BBI.TrueBB = BBI.FalseBB = NULL;
358 if (BBI.Kind != ICNotAnalyzed)
359 return; // Already analyzed.
361 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
364 // Look for 'root' of a simple (non-nested) triangle or diamond.
365 BBI.Kind = ICNotClassfied;
367 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
368 BBI.HasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
369 // Unanalyable or ends with fallthrough or unconditional branch.
370 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
372 // Do not ifcvt if either path is a back edge to the entry block.
373 if (BBI.TrueBB == BB || BBI.FalseBB == BB)
376 AnalyzeBlock(BBI.TrueBB);
377 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
379 // No false branch. This BB must end with a conditional branch and a
382 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
383 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
385 AnalyzeBlock(BBI.FalseBB);
386 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
388 // If both paths are dead, then forget about it.
389 if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
394 // Look for more opportunities to if-convert a triangle. Try to restructure
395 // the CFG to form a triangle with the 'false' path.
396 std::vector<MachineOperand> RevCond(BBI.BrCond);
397 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
399 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
400 !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
401 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
402 FeasibilityAnalysis(FalseBBI, RevCond)) {
410 // Note TailBB can be empty.
411 BBI.Kind = ICDiamond;
412 TrueBBI.Kind = FalseBBI.Kind = ICChild;
413 BBI.TailBB = TrueBBI.TrueBB;
415 // FIXME: Consider duplicating if BB is small.
416 if (ValidTriangle(TrueBBI, FalseBBI) &&
417 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
425 BBI.Kind = ICTriangle;
426 TrueBBI.Kind = ICChild;
427 } else if (ValidSimple(TrueBBI) &&
428 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
429 // Simple (split, no rejoin):
437 TrueBBI.Kind = ICChild;
438 } else if (CanRevCond) {
439 // Try the other path...
440 if (ValidTriangle(FalseBBI, TrueBBI) &&
441 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
442 BBI.Kind = ICTriangleFalse;
443 FalseBBI.Kind = ICChild;
444 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
445 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
446 BBI.Kind = ICTriangleFRev;
447 FalseBBI.Kind = ICChild;
448 } else if (ValidSimple(FalseBBI) &&
449 FeasibilityAnalysis(FalseBBI, RevCond)) {
450 BBI.Kind = ICSimpleFalse;
451 FalseBBI.Kind = ICChild;
458 /// FeasibilityAnalysis - Determine if the block is predicable. In most
459 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
460 /// Also checks if the block contains any instruction which can clobber a
461 /// predicate (e.g. condition code register). If so, the block is not
462 /// predicable unless it's the last instruction.
463 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
464 std::vector<MachineOperand> &Pred,
465 bool isTriangle, bool RevBranch) {
466 // If the block is dead, or it is going to be the entry block of a sub-CFG
467 // that will be if-converted, then it cannot be predicated.
468 if (BBI.Kind != ICNotAnalyzed &&
469 BBI.Kind != ICNotClassfied &&
473 // Check predication threshold.
474 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
477 // If it is already predicated, check if its predicate subsumes the new
479 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
482 bool SeenPredMod = false;
483 bool SeenCondBr = false;
484 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
486 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
488 // Predicate modification instruction should end the block (except for
489 // already predicated instructions and end of block branches).
490 if (!TII->isPredicated(I)) {
491 // This is the 'true' block of a triangle, i.e. its 'true' block is
492 // the same as the 'false' block of the entry. So false positive
494 if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
495 (TID->Flags & M_BRANCH_FLAG) != 0 &&
496 (TID->Flags & M_BARRIER_FLAG) == 0) {
497 // This is the first conditional branch, test predicate subsumsion.
498 std::vector<MachineOperand> RevPred(Pred);
499 std::vector<MachineOperand> Cond(BBI.BrCond);
501 if (TII->ReverseBranchCondition(Cond))
504 if (TII->ReverseBranchCondition(RevPred) ||
505 !TII->SubsumesPredicate(Cond, RevPred))
508 continue; // Conditional branches is not predicable.
514 if (TID->Flags & M_CLOBBERS_PRED) {
515 BBI.ModifyPredicate = true;
519 if (!I->isPredicable())
526 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
527 /// expose more if-conversion opportunities. e.g.
549 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
553 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
554 /// candidates. It returns true if any CFG restructuring is done to expose more
555 /// if-conversion opportunities.
556 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
557 std::vector<BBInfo*> &Candidates) {
559 std::set<MachineBasicBlock*> Visited;
560 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
561 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
562 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
563 MachineBasicBlock *BB = *I;
565 BBInfo &BBI = BBAnalysis[BB->getNumber()];
571 Candidates.push_back(&BBI);
574 Change |= AttemptRestructuring(BBI);
580 // Sort to favor more complex ifcvt scheme.
581 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
586 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
587 /// that all the intervening blocks are empty (given BB can fall through to its
589 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
590 MachineFunction::iterator I = BB;
591 MachineFunction::iterator TI = ToBB;
592 MachineFunction::iterator E = BB->getParent()->end();
594 if (I == E || !I->empty())
599 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
600 /// to determine if it can be if-converted.
601 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
602 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
603 E = BB->pred_end(); PI != E; ++PI) {
604 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
605 if (PBBI.Kind == ICNotClassfied)
606 PBBI.Kind = ICReAnalyze;
610 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
612 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
613 const TargetInstrInfo *TII) {
614 std::vector<MachineOperand> NoCond;
615 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
618 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
620 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
621 MachineBasicBlock *TBB = NULL, *FBB = NULL;
622 std::vector<MachineOperand> Cond;
623 bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
624 bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
625 if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
626 if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
627 (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
628 BBI.BB->removeSuccessor(BBI.TrueBB);
629 if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
630 if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
631 (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
632 BBI.BB->removeSuccessor(BBI.FalseBB);
635 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
637 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
638 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
639 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
640 BBInfo *CvtBBI = &TrueBBI;
641 BBInfo *NextBBI = &FalseBBI;
643 std::vector<MachineOperand> Cond(BBI.BrCond);
644 if (BBI.Kind == ICSimpleFalse) {
645 std::swap(CvtBBI, NextBBI);
646 TII->ReverseBranchCondition(Cond);
649 PredicateBlock(*CvtBBI, Cond);
651 // Merge converted block into entry block.
652 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
653 MergeBlocks(BBI, *CvtBBI);
655 bool IterIfcvt = true;
656 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
657 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
658 BBI.HasFallThrough = false;
659 // Now ifcvt'd block will look like this:
666 // We cannot further ifcvt this block because the unconditional branch
667 // will have to be predicated on the new condition, that will not be
668 // available if cmp executes.
672 RemoveExtraEdges(BBI);
674 // Update block info. BB can be iteratively if-converted.
676 BBI.Kind = ICReAnalyze;
680 CvtBBI->Kind = ICDead;
682 // FIXME: Must maintain LiveIns.
686 /// IfConvertTriangle - If convert a triangle sub-CFG.
688 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
689 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
690 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
691 BBInfo *CvtBBI = &TrueBBI;
692 BBInfo *NextBBI = &FalseBBI;
694 std::vector<MachineOperand> Cond(BBI.BrCond);
695 if (BBI.Kind == ICTriangleFalse || BBI.Kind == ICTriangleFRev) {
696 if (BBI.Kind == ICTriangleFRev) {
697 ReverseBranchCondition(*NextBBI);
698 // False BB has been changed, modify its predecessors (except for this
699 // one) so they don't get ifcvt'ed based on bad intel.
700 for (MachineBasicBlock::pred_iterator PI = NextBBI->BB->pred_begin(),
701 E = NextBBI->BB->pred_end(); PI != E; ++PI) {
702 MachineBasicBlock *PBB = *PI;
705 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
706 PBBI.Kind = ICReAnalyze;
709 std::swap(CvtBBI, NextBBI);
710 TII->ReverseBranchCondition(Cond);
713 // Predicate the 'true' block after removing its branch.
714 TrueBBI.NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
715 PredicateBlock(*CvtBBI, Cond);
717 // If 'true' block has a 'false' successor, add an exit branch to it.
718 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
720 std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
721 if (TII->ReverseBranchCondition(RevCond))
722 assert(false && "Unable to reverse branch condition!");
723 TII->InsertBranch(*CvtBBI->BB, CvtBBI->FalseBB, NULL, RevCond);
726 // Now merge the entry of the triangle with the true block.
727 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
728 MergeBlocks(BBI, *CvtBBI);
730 // Merge in the 'false' block if the 'false' block has no other
731 // predecessors. Otherwise, add a unconditional branch from to 'false'.
732 bool FalseBBDead = false;
733 bool IterIfcvt = true;
734 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
735 if (!isFallThrough) {
736 // Only merge them if the true block does not fallthrough to the false
737 // block. By not merging them, we make it possible to iteratively
739 if (!HasEarlyExit && NextBBI->BB->pred_size() == 1) {
740 MergeBlocks(BBI, *NextBBI);
743 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
744 BBI.HasFallThrough = false;
746 // Mixed predicated and unpredicated code. This cannot be iteratively
751 RemoveExtraEdges(BBI);
753 // Update block info. BB can be iteratively if-converted.
755 BBI.Kind = ICReAnalyze;
759 CvtBBI->Kind = ICDead;
761 NextBBI->Kind = ICDead;
763 // FIXME: Must maintain LiveIns.
767 /// IfConvertDiamond - If convert a diamond sub-CFG.
769 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
770 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
771 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
773 SmallVector<MachineInstr*, 2> Dups;
775 // No common merge block. Check if the terminators (e.g. return) are
776 // the same or predicable.
777 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
778 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
779 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
780 if (TT->isIdenticalTo(FT))
781 Dups.push_back(TT); // Will erase these later.
782 else if (!TT->isPredicable() && !FT->isPredicable())
783 return false; // Can't if-convert. Abort!
788 // One of the two pathes have more terminators, make sure they are
790 while (TT != BBI.TrueBB->end()) {
791 if (!TT->isPredicable()) {
792 return false; // Can't if-convert. Abort!
796 while (FT != BBI.FalseBB->end()) {
797 if (!FT->isPredicable()) {
798 return false; // Can't if-convert. Abort!
804 // Remove the duplicated instructions from the 'true' block.
805 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
806 Dups[i]->eraseFromParent();
807 --TrueBBI.NonPredSize;
810 // Merge the 'true' and 'false' blocks by copying the instructions
811 // from the 'false' block to the 'true' block. That is, unless the true
812 // block would clobber the predicate, in that case, do the opposite.
813 BBInfo *BBI1 = &TrueBBI;
814 BBInfo *BBI2 = &FalseBBI;
815 std::vector<MachineOperand> RevCond(BBI.BrCond);
816 TII->ReverseBranchCondition(RevCond);
817 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
818 std::vector<MachineOperand> *Cond2 = &RevCond;
819 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
820 // Either the block fallthrough to another block or it ends with a
821 // return. If it's the former, add a branch to its successor.
822 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
823 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
825 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
826 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
827 NeedBr1 && !NeedBr2)) {
828 std::swap(BBI1, BBI2);
829 std::swap(Cond1, Cond2);
830 std::swap(NeedBr1, NeedBr2);
833 // Predicate the 'true' block after removing its branch.
834 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
835 PredicateBlock(*BBI1, *Cond1);
837 // Add an early exit branch if needed.
839 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
841 // Predicate the 'false' block.
842 PredicateBlock(*BBI2, *Cond2, true);
844 // Add an unconditional branch from 'false' to to 'false' successor if it
845 // will not be the fallthrough block.
846 if (NeedBr2 && !NeedBr1) {
847 // If BBI2 isn't going to be merged in, then the existing fallthrough
848 // or branch is fine.
849 if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
850 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
851 BBI2->HasFallThrough = false;
855 // Keep them as two separate blocks if there is an early exit.
857 MergeBlocks(*BBI1, *BBI2);
859 // Remove the conditional branch from entry to the blocks.
860 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
862 // Merge the combined block into the entry of the diamond.
863 MergeBlocks(BBI, *BBI1);
865 // 'True' and 'false' aren't combined, see if we need to add a unconditional
866 // branch to the 'false' block.
867 if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
868 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
869 BBI1->HasFallThrough = false;
872 // If the if-converted block fallthrough or unconditionally branch into the
873 // tail block, and the tail block does not have other predecessors, then
874 // fold the tail block in as well.
875 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
877 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
878 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
879 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
880 MergeBlocks(*CvtBBI, TailBBI);
881 TailBBI.Kind = ICDead;
884 RemoveExtraEdges(BBI);
886 // Update block info.
888 TrueBBI.Kind = ICDead;
889 FalseBBI.Kind = ICDead;
891 // FIXME: Must maintain LiveIns.
895 /// PredicateBlock - Predicate every instruction in the block with the specified
896 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
897 void IfConverter::PredicateBlock(BBInfo &BBI,
898 std::vector<MachineOperand> &Cond,
900 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
902 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
904 if (TII->isPredicated(I))
906 if (!TII->PredicateInstruction(I, Cond)) {
907 cerr << "Unable to predicate " << *I << "!\n";
913 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
918 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
920 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
921 ToBBI.BB->splice(ToBBI.BB->end(),
922 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
924 // Redirect all branches to FromBB to ToBB.
925 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
926 FromBBI.BB->pred_end());
927 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
928 MachineBasicBlock *Pred = Preds[i];
929 if (Pred == ToBBI.BB)
931 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
934 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
935 FromBBI.BB->succ_end());
936 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
937 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
939 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
940 MachineBasicBlock *Succ = Succs[i];
941 // Fallthrough edge can't be transferred.
942 if (Succ == FallThrough)
944 FromBBI.BB->removeSuccessor(Succ);
945 if (!ToBBI.BB->isSuccessor(Succ))
946 ToBBI.BB->addSuccessor(Succ);
949 // Now FromBBI always fall through to the next block!
951 FromBBI.BB->addSuccessor(NBB);
953 ToBBI.NonPredSize += FromBBI.NonPredSize;
954 FromBBI.NonPredSize = 0;
956 ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
957 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
959 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
960 std::back_inserter(ToBBI.Predicate));
961 FromBBI.Predicate.clear();