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/Debug.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
27 STATISTIC(NumSimple, "Number of simple if-conversions performed");
28 STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
29 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
30 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
31 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
34 class IfConverter : public MachineFunctionPass {
36 ICNotAnalyzed, // BB has not been analyzed.
37 ICReAnalyze, // BB must be re-analyzed.
38 ICNotClassfied, // BB data valid, but not classified.
39 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
40 ICSimpleFalse, // Same as ICSimple, but on the false path.
41 ICTriangle, // BB is entry of a triangle sub-CFG.
42 ICDiamond, // BB is entry of a diamond sub-CFG.
43 ICChild, // BB is part of the sub-CFG that'll be predicated.
44 ICDead // BB cannot be if-converted again.
47 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
48 /// if-conversion feasibility analysis. This includes results from
49 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
50 /// classification, and common tail block of its successors (if it's a
51 /// diamond shape), its size, whether it's predicable, and whether any
52 /// instruction can clobber the 'would-be' predicate.
54 /// Kind - Type of block. See BBICKind.
55 /// NonPredSize - Number of non-predicated instructions.
56 /// IsAnalyzable - True if AnalyzeBranch() returns false.
57 /// ModifyPredicate - True if BB would modify the predicate (e.g. has
59 /// BB - Corresponding MachineBasicBlock.
60 /// TrueBB / FalseBB- See AnalyzeBranch().
61 /// BrCond - Conditions for end of block conditional branches.
62 /// Predicate - Predicate used in the BB.
69 MachineBasicBlock *BB;
70 MachineBasicBlock *TrueBB;
71 MachineBasicBlock *FalseBB;
72 MachineBasicBlock *TailBB;
73 std::vector<MachineOperand> BrCond;
74 std::vector<MachineOperand> Predicate;
75 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
76 IsAnalyzable(false), hasFallThrough(false),
77 ModifyPredicate(false),
78 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
81 /// Roots - Basic blocks that do not have successors. These are the starting
82 /// points of Graph traversal.
83 std::vector<MachineBasicBlock*> Roots;
85 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
86 /// basic block number.
87 std::vector<BBInfo> BBAnalysis;
89 const TargetLowering *TLI;
90 const TargetInstrInfo *TII;
94 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
96 virtual bool runOnMachineFunction(MachineFunction &MF);
97 virtual const char *getPassName() const { return "If converter"; }
100 bool ReverseBranchCondition(BBInfo &BBI);
101 bool ValidSimple(BBInfo &TrueBBI) const;
102 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
103 bool FalseBranch = false) const;
104 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
105 void ScanInstructions(BBInfo &BBI);
106 void AnalyzeBlock(MachineBasicBlock *BB);
107 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
108 bool isTriangle = false, bool RevBranch = false);
109 bool AttemptRestructuring(BBInfo &BBI);
110 bool AnalyzeBlocks(MachineFunction &MF,
111 std::vector<BBInfo*> &Candidates);
112 void ReTryPreds(MachineBasicBlock *BB);
113 bool IfConvertSimple(BBInfo &BBI);
114 bool IfConvertTriangle(BBInfo &BBI);
115 bool IfConvertDiamond(BBInfo &BBI);
116 void PredicateBlock(BBInfo &BBI,
117 std::vector<MachineOperand> &Cond,
118 bool IgnoreTerm = false);
119 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
121 // blockAlwaysFallThrough - Block ends without a terminator.
122 bool blockAlwaysFallThrough(BBInfo &BBI) const {
123 return BBI.IsAnalyzable && BBI.TrueBB == NULL;
126 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
127 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
128 // Favor diamond over triangle, etc.
129 return (unsigned)C1->Kind < (unsigned)C2->Kind;
132 char IfConverter::ID = 0;
135 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
137 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
138 TLI = MF.getTarget().getTargetLowering();
139 TII = MF.getTarget().getInstrInfo();
140 if (!TII) return false;
142 DOUT << "\nIfcvt: function \'" << MF.getFunction()->getName() << "\'\n";
145 BBAnalysis.resize(MF.getNumBlockIDs());
147 // Look for root nodes, i.e. blocks without successors.
148 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
149 if (I->succ_size() == 0)
152 std::vector<BBInfo*> Candidates;
155 // Do an intial analysis for each basic block and finding all the potential
156 // candidates to perform if-convesion.
157 bool Change = AnalyzeBlocks(MF, Candidates);
158 while (!Candidates.empty()) {
159 BBInfo &BBI = *Candidates.back();
160 Candidates.pop_back();
164 default: assert(false && "Unexpected!");
167 // One or more of 'children' have been modified, abort!
169 // Block has been already been if-converted, abort!
172 case ICSimpleFalse: {
173 bool isRev = BBI.Kind == ICSimpleFalse;
174 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
175 << "): BB#" << BBI.BB->getNumber() << " ("
176 << ((BBI.Kind == ICSimpleFalse)
177 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
178 RetVal = IfConvertSimple(BBI);
179 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
181 if (isRev) NumSimpleRev++;
186 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " (T:"
187 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
189 RetVal = IfConvertTriangle(BBI);
190 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
191 if (RetVal) NumTriangle++;
194 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
195 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
197 DOUT << "," << BBI.TailBB->getNumber() ;
199 RetVal = IfConvertDiamond(BBI);
200 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
201 if (RetVal) NumDiamonds++;
209 MadeChange |= Change;
218 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
219 MachineBasicBlock *TrueBB) {
220 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
221 E = BB->succ_end(); SI != E; ++SI) {
222 MachineBasicBlock *SuccBB = *SI;
223 if (SuccBB != TrueBB)
229 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
230 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
231 TII->RemoveBranch(*BBI.BB);
232 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
233 std::swap(BBI.TrueBB, BBI.FalseBB);
239 /// ValidSimple - Returns true if the 'true' block (along with its
240 /// predecessor) forms a valid simple shape for ifcvt.
241 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
242 return !blockAlwaysFallThrough(TrueBBI) &&
243 TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
246 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
247 /// with their common predecessor) forms a valid triangle shape for ifcvt.
248 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
249 bool FalseBranch) const {
250 if (TrueBBI.BB->pred_size() != 1)
253 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
254 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
255 MachineFunction::iterator I = TrueBBI.BB;
256 if (++I == TrueBBI.BB->getParent()->end())
260 return TExit && TExit == FalseBBI.BB;
263 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
264 /// with their common predecessor) forms a valid diamond shape for ifcvt.
265 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
266 // FIXME: Also look for fallthrough
267 return (TrueBBI.TrueBB == FalseBBI.TrueBB &&
268 TrueBBI.BB->pred_size() == 1 &&
269 FalseBBI.BB->pred_size() == 1 &&
270 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
273 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
274 /// the specified block. Record its successors and whether it looks like an
275 /// if-conversion candidate.
276 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
277 BBInfo &BBI = BBAnalysis[BB->getNumber()];
279 if (BBI.Kind == ICReAnalyze) {
281 BBI.TrueBB = BBI.FalseBB = NULL;
283 if (BBI.Kind != ICNotAnalyzed)
284 return; // Already analyzed.
286 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
289 // Look for 'root' of a simple (non-nested) triangle or diamond.
290 BBI.Kind = ICNotClassfied;
292 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
293 BBI.hasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
294 // Unanalyable or ends with fallthrough or unconditional branch.
295 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
297 // Do not ifcvt if either path is a back edge to the entry block.
298 if (BBI.TrueBB == BB || BBI.FalseBB == BB)
301 AnalyzeBlock(BBI.TrueBB);
302 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
304 // No false branch. This BB must end with a conditional branch and a
307 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
308 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
310 AnalyzeBlock(BBI.FalseBB);
311 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
313 // If both paths are dead, then forget about it.
314 if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
319 // Look for more opportunities to if-convert a triangle. Try to restructure
320 // the CFG to form a triangle with the 'false' path.
321 std::vector<MachineOperand> RevCond(BBI.BrCond);
322 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
324 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
325 !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
326 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
327 FeasibilityAnalysis(FalseBBI, RevCond)) {
335 // Note TailBB can be empty.
336 BBI.Kind = ICDiamond;
337 TrueBBI.Kind = FalseBBI.Kind = ICChild;
338 BBI.TailBB = TrueBBI.TrueBB;
340 // FIXME: Consider duplicating if BB is small.
341 if (ValidTriangle(TrueBBI, FalseBBI) &&
342 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
350 BBI.Kind = ICTriangle;
351 TrueBBI.Kind = ICChild;
352 } else if (ValidSimple(TrueBBI) &&
353 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
354 // Simple (split, no rejoin):
362 TrueBBI.Kind = ICChild;
363 } else if (CanRevCond) {
364 // Try the other path...
365 if (ValidTriangle(FalseBBI, TrueBBI) &&
366 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
367 // Reverse 'true' and 'false' paths.
368 ReverseBranchCondition(BBI);
369 BBI.Kind = ICTriangle;
370 FalseBBI.Kind = ICChild;
371 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
372 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
373 ReverseBranchCondition(FalseBBI);
374 ReverseBranchCondition(BBI);
375 BBI.Kind = ICTriangle;
376 FalseBBI.Kind = ICChild;
377 } else if (ValidSimple(FalseBBI) &&
378 FeasibilityAnalysis(FalseBBI, RevCond)) {
379 BBI.Kind = ICSimpleFalse;
380 FalseBBI.Kind = ICChild;
387 /// FeasibilityAnalysis - Determine if the block is predicable. In most
388 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
389 /// Also checks if the block contains any instruction which can clobber a
390 /// predicate (e.g. condition code register). If so, the block is not
391 /// predicable unless it's the last instruction.
392 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
393 std::vector<MachineOperand> &Pred,
394 bool isTriangle, bool RevBranch) {
395 // If the block is dead, or it is going to be the entry block of a sub-CFG
396 // that will be if-converted, then it cannot be predicated.
397 if (BBI.Kind != ICNotAnalyzed &&
398 BBI.Kind != ICNotClassfied &&
402 // Check predication threshold.
403 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
406 // If it is already predicated, check if its predicate subsumes the new
408 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
411 bool SeenPredMod = false;
412 bool SeenCondBr = false;
413 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
415 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
417 // Predicate modification instruction should end the block (except for
418 // already predicated instructions and end of block branches).
419 if (!TII->isPredicated(I)) {
420 // This is the 'true' block of a triangle, i.e. its 'true' block is
421 // the same as the 'false' block of the entry. So false positive
423 if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
424 (TID->Flags & M_BRANCH_FLAG) != 0 &&
425 (TID->Flags & M_BARRIER_FLAG) == 0) {
426 // This is the first conditional branch, test predicate subsumsion.
427 std::vector<MachineOperand> RevPred(Pred);
428 std::vector<MachineOperand> Cond(BBI.BrCond);
430 if (TII->ReverseBranchCondition(Cond))
433 if (TII->ReverseBranchCondition(RevPred) ||
434 !TII->SubsumesPredicate(Cond, RevPred))
437 continue; // Conditional branches is not predicable.
443 if (TID->Flags & M_CLOBBERS_PRED) {
444 BBI.ModifyPredicate = true;
448 if (!I->isPredicable())
455 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
456 /// expose more if-conversion opportunities. e.g.
478 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
482 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
483 /// candidates. It returns true if any CFG restructuring is done to expose more
484 /// if-conversion opportunities.
485 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
486 std::vector<BBInfo*> &Candidates) {
488 std::set<MachineBasicBlock*> Visited;
489 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
490 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
491 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
492 MachineBasicBlock *BB = *I;
494 BBInfo &BBI = BBAnalysis[BB->getNumber()];
500 Candidates.push_back(&BBI);
503 Change |= AttemptRestructuring(BBI);
509 // Sort to favor more complex ifcvt scheme.
510 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
515 /// isNextBlock - Returns true either if ToBB the next block after BB or
516 /// that all the intervening blocks are empty.
517 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
518 MachineFunction::iterator I = BB;
519 MachineFunction::iterator TI = ToBB;
520 MachineFunction::iterator E = BB->getParent()->end();
522 if (I == E || !I->empty())
527 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
528 /// to determine if it can be if-converted.
529 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
530 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
531 E = BB->pred_end(); PI != E; ++PI) {
532 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
533 PBBI.Kind = ICReAnalyze;
537 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
539 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
540 const TargetInstrInfo *TII) {
541 std::vector<MachineOperand> NoCond;
542 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
545 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
547 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
548 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
549 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
550 BBInfo *CvtBBI = &TrueBBI;
551 BBInfo *NextBBI = &FalseBBI;
553 std::vector<MachineOperand> Cond(BBI.BrCond);
554 if (BBI.Kind == ICSimpleFalse) {
555 std::swap(CvtBBI, NextBBI);
556 TII->ReverseBranchCondition(Cond);
559 PredicateBlock(*CvtBBI, Cond);
561 // Merge converted block into entry block. Also add an unconditional branch
562 // to the 'false' branch.
563 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
564 MergeBlocks(BBI, *CvtBBI);
565 BBI.BB->removeSuccessor(CvtBBI->BB);
567 bool IterIfcvt = true;
568 if (!isNextBlock(BBI.BB, NextBBI->BB)) {
569 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
570 BBI.hasFallThrough = false;
571 // Now ifcvt'd block will look like this:
578 // We cannot further ifcvt this block because the unconditional branch
579 // will have to be predicated on the new condition, that will not be
580 // available if cmp executes.
583 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
585 // Update block info. BB can be iteratively if-converted.
587 BBI.Kind = ICReAnalyze;
591 CvtBBI->Kind = ICDead;
593 // FIXME: Must maintain LiveIns.
597 /// IfConvertTriangle - If convert a triangle sub-CFG.
599 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
600 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
602 // Predicate the 'true' block after removing its branch.
603 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
604 PredicateBlock(TrueBBI, BBI.BrCond);
606 // If 'true' block has a 'false' successor, add an exit branch to it.
607 bool HasEarlyExit = TrueBBI.FalseBB != NULL;
609 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
610 if (TII->ReverseBranchCondition(RevCond))
611 assert(false && "Unable to reverse branch condition!");
612 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
615 // Now merge the entry of the triangle with the true block.
616 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
617 MergeBlocks(BBI, TrueBBI);
619 // Merge in the 'false' block if the 'false' block has no other
620 // predecessors. Otherwise, add a unconditional branch from to 'false'.
621 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
622 bool FalseBBDead = false;
623 bool IterIfcvt = true;
624 bool isFallThrough = isNextBlock(BBI.BB, FalseBBI.BB);
625 if (!isFallThrough) {
626 // Only merge them if the true block does not fallthrough to the false
627 // block. By not merging them, we make it possible to iteratively
629 if (!HasEarlyExit && FalseBBI.BB->pred_size() == 1) {
630 MergeBlocks(BBI, FalseBBI);
633 InsertUncondBranch(BBI.BB, FalseBBI.BB, TII);
634 TrueBBI.hasFallThrough = false;
636 // Mixed predicated and unpredicated code. This cannot be iteratively
641 // Remove entry to false edge if false block is merged in as well.
643 BBI.BB->removeSuccessor(FalseBBI.BB);
644 std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
645 std::back_inserter(BBI.Predicate));
647 // Update block info. BB can be iteratively if-converted.
649 BBI.Kind = ICReAnalyze;
653 TrueBBI.Kind = ICDead;
655 FalseBBI.Kind = ICDead;
657 // FIXME: Must maintain LiveIns.
661 /// IfConvertDiamond - If convert a diamond sub-CFG.
663 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
664 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
665 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
667 SmallVector<MachineInstr*, 2> Dups;
669 // No common merge block. Check if the terminators (e.g. return) are
670 // the same or predicable.
671 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
672 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
673 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
674 if (TT->isIdenticalTo(FT))
675 Dups.push_back(TT); // Will erase these later.
676 else if (!TT->isPredicable() && !FT->isPredicable())
677 return false; // Can't if-convert. Abort!
682 // One of the two pathes have more terminators, make sure they are
684 while (TT != BBI.TrueBB->end()) {
685 if (!TT->isPredicable()) {
686 return false; // Can't if-convert. Abort!
690 while (FT != BBI.FalseBB->end()) {
691 if (!FT->isPredicable()) {
692 return false; // Can't if-convert. Abort!
698 // Remove the duplicated instructions from the 'true' block.
699 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
700 Dups[i]->eraseFromParent();
701 --TrueBBI.NonPredSize;
704 // Merge the 'true' and 'false' blocks by copying the instructions
705 // from the 'false' block to the 'true' block. That is, unless the true
706 // block would clobber the predicate, in that case, do the opposite.
707 BBInfo *BBI1 = &TrueBBI;
708 BBInfo *BBI2 = &FalseBBI;
709 std::vector<MachineOperand> RevCond(BBI.BrCond);
710 TII->ReverseBranchCondition(RevCond);
711 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
712 std::vector<MachineOperand> *Cond2 = &RevCond;
713 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
714 // Either the block fallthrough to another block or it ends with a
715 // return. If it's the former, add a branch to its successor.
716 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
717 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
719 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
720 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
721 NeedBr1 && !NeedBr2)) {
722 std::swap(BBI1, BBI2);
723 std::swap(Cond1, Cond2);
724 std::swap(NeedBr1, NeedBr2);
727 // Predicate the 'true' block after removing its branch.
728 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
729 PredicateBlock(*BBI1, *Cond1);
731 // Add an early exit branch if needed.
733 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
735 // Predicate the 'false' block.
736 PredicateBlock(*BBI2, *Cond2, true);
738 // Add an unconditional branch from 'false' to to 'false' successor if it
739 // will not be the fallthrough block.
740 if (NeedBr2 && !NeedBr1) {
741 // If BBI2 isn't going to be merged in, then the existing fallthrough
742 // or branch is fine.
743 if (!isNextBlock(BBI.BB, *BBI2->BB->succ_begin())) {
744 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
745 BBI2->hasFallThrough = false;
749 // Keep them as two separate blocks if there is an early exit.
751 MergeBlocks(*BBI1, *BBI2);
753 // Remove the conditional branch from entry to the blocks.
754 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
756 // Merge the combined block into the entry of the diamond.
757 MergeBlocks(BBI, *BBI1);
758 std::copy(Cond1->begin(), Cond1->end(),
759 std::back_inserter(BBI.Predicate));
761 std::copy(Cond2->begin(), Cond2->end(),
762 std::back_inserter(BBI.Predicate));
764 // 'True' and 'false' aren't combined, see if we need to add a unconditional
765 // branch to the 'false' block.
766 if (NeedBr1 && !isNextBlock(BBI.BB, BBI2->BB)) {
767 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
768 BBI1->hasFallThrough = false;
771 // If the if-converted block fallthrough or unconditionally branch into the
772 // tail block, and the tail block does not have other predecessors, then
773 // fold the tail block in as well.
774 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
776 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
777 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
778 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
779 MergeBlocks(*CvtBBI, TailBBI);
780 TailBBI.Kind = ICDead;
783 // Update block info.
785 TrueBBI.Kind = ICDead;
786 FalseBBI.Kind = ICDead;
788 // FIXME: Must maintain LiveIns.
792 /// PredicateBlock - Predicate every instruction in the block with the specified
793 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
794 void IfConverter::PredicateBlock(BBInfo &BBI,
795 std::vector<MachineOperand> &Cond,
797 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
799 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
801 if (TII->isPredicated(I))
803 if (!TII->PredicateInstruction(I, Cond)) {
804 cerr << "Unable to predicate " << *I << "!\n";
813 static MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
814 MachineFunction::iterator I = BB;
815 MachineFunction::iterator E = BB->getParent()->end();
821 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
823 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
824 ToBBI.BB->splice(ToBBI.BB->end(),
825 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
827 // Redirect all branches to FromBB to ToBB.
828 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
829 FromBBI.BB->pred_end());
830 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
831 MachineBasicBlock *Pred = Preds[i];
832 if (Pred == ToBBI.BB)
834 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
837 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
838 FromBBI.BB->succ_end());
839 MachineBasicBlock *FallThrough = FromBBI.hasFallThrough
840 ? getNextBlock(FromBBI.BB) : NULL;
842 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
843 MachineBasicBlock *Succ = Succs[i];
844 if (Succ == FallThrough)
846 FromBBI.BB->removeSuccessor(Succ);
847 if (!ToBBI.BB->isSuccessor(Succ))
848 ToBBI.BB->addSuccessor(Succ);
851 ToBBI.NonPredSize += FromBBI.NonPredSize;
852 FromBBI.NonPredSize = 0;
854 ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
855 ToBBI.hasFallThrough = FromBBI.hasFallThrough;