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> DisableTriangleR("disable-ifcvt-triangle-rev",
40 cl::init(false), cl::Hidden);
41 cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
42 cl::init(false), cl::Hidden);
43 cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
44 cl::init(false), cl::Hidden);
45 cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
46 cl::init(false), cl::Hidden);
49 STATISTIC(NumSimple, "Number of simple if-conversions performed");
50 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
51 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
52 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
53 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
54 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
55 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
56 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
57 STATISTIC(NumDupBBs, "Number of duplicated blocks");
60 class IfConverter : public MachineFunctionPass {
62 ICNotClassfied, // BB data valid, but not classified.
63 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
64 ICSimpleFalse, // Same as ICSimple, but on the false path.
65 ICTriangle, // BB is entry of a triangle sub-CFG.
66 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
67 ICTriangleFalse, // Same as ICTriangle, but on the false path.
68 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
69 ICDiamond // BB is entry of a diamond sub-CFG.
72 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
73 /// if-conversion feasibility analysis. This includes results from
74 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
75 /// classification, and common tail block of its successors (if it's a
76 /// diamond shape), its size, whether it's predicable, and whether any
77 /// instruction can clobber the 'would-be' predicate.
79 /// Kind - Type of block. See BBICKind.
80 /// IsDone - True if BB is not to be considered for ifcvt.
81 /// IsBeingAnalyzed - True if BB is currently being analyzed.
82 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
83 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
84 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
85 /// HasFallThrough - True if BB may fallthrough to the following BB.
86 /// IsUnpredicable - True if BB is known to be unpredicable.
87 /// ClobbersPredicate- True if BB would modify the predicate (e.g. has
89 /// NonPredSize - Number of non-predicated instructions.
90 /// BB - Corresponding MachineBasicBlock.
91 /// TrueBB / FalseBB- See AnalyzeBranch().
92 /// BrCond - Conditions for end of block conditional branches.
93 /// Predicate - Predicate used in the BB.
97 bool IsBeingAnalyzed : 1;
100 bool IsBrAnalyzable : 1;
101 bool HasFallThrough : 1;
102 bool IsUnpredicable : 1;
103 bool CannotBeCopied : 1;
104 bool ClobbersPred : 1;
105 unsigned NonPredSize;
106 MachineBasicBlock *BB;
107 MachineBasicBlock *TrueBB;
108 MachineBasicBlock *FalseBB;
109 MachineBasicBlock *TailBB;
110 std::vector<MachineOperand> BrCond;
111 std::vector<MachineOperand> Predicate;
112 BBInfo() : Kind(ICNotClassfied), IsDone(false), IsBeingAnalyzed(false),
113 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
114 HasFallThrough(false), IsUnpredicable(false),
115 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
116 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
119 /// Roots - Basic blocks that do not have successors. These are the starting
120 /// points of Graph traversal.
121 std::vector<MachineBasicBlock*> Roots;
123 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
124 /// basic block number.
125 std::vector<BBInfo> BBAnalysis;
127 const TargetLowering *TLI;
128 const TargetInstrInfo *TII;
132 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
134 virtual bool runOnMachineFunction(MachineFunction &MF);
135 virtual const char *getPassName() const { return "If converter"; }
138 bool ReverseBranchCondition(BBInfo &BBI);
139 bool ValidSimple(BBInfo &TrueBBI) const;
140 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
141 bool FalseBranch = false) const;
142 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
143 void ScanInstructions(BBInfo &BBI);
144 BBInfo &AnalyzeBlock(MachineBasicBlock *BB);
145 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
146 bool isTriangle = false, bool RevBranch = false);
147 bool AttemptRestructuring(BBInfo &BBI);
148 bool AnalyzeBlocks(MachineFunction &MF,
149 std::vector<BBInfo*> &Candidates);
150 void ReTryPreds(MachineBasicBlock *BB);
151 void RemoveExtraEdges(BBInfo &BBI);
152 bool IfConvertSimple(BBInfo &BBI);
153 bool IfConvertTriangle(BBInfo &BBI);
154 bool IfConvertDiamond(BBInfo &BBI);
155 void PredicateBlock(BBInfo &BBI,
156 std::vector<MachineOperand> &Cond,
157 bool IgnoreTerm = false);
158 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
159 std::vector<MachineOperand> &Cond,
160 bool IgnoreBr = false);
161 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
163 // blockAlwaysFallThrough - Block ends without a terminator.
164 bool blockAlwaysFallThrough(BBInfo &BBI) const {
165 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
168 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
169 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
170 // Favor diamond over triangle, etc.
171 return (unsigned)C1->Kind < (unsigned)C2->Kind;
174 char IfConverter::ID = 0;
177 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
179 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
180 TLI = MF.getTarget().getTargetLowering();
181 TII = MF.getTarget().getInstrInfo();
182 if (!TII) return false;
184 static int FnNum = -1;
185 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
186 << MF.getFunction()->getName() << "\'";
188 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
189 DOUT << " skipped\n";
195 BBAnalysis.resize(MF.getNumBlockIDs());
197 // Look for root nodes, i.e. blocks without successors.
198 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
199 if (I->succ_size() == 0)
202 std::vector<BBInfo*> Candidates;
204 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
205 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
206 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
207 // Do an intial analysis for each basic block and finding all the potential
208 // candidates to perform if-convesion.
209 bool Change = AnalyzeBlocks(MF, Candidates);
210 while (!Candidates.empty()) {
211 BBInfo &BBI = *Candidates.back();
212 Candidates.pop_back();
214 // If the block has been evicted out of the queue or it has already been
215 // marked dead (due to it being predicated), then skip it.
216 if (!BBI.IsEnqueued || BBI.IsDone)
218 BBI.IsEnqueued = false;
222 default: assert(false && "Unexpected!");
225 case ICSimpleFalse: {
226 bool isFalse = BBI.Kind == ICSimpleFalse;
227 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
228 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
229 << "): BB#" << BBI.BB->getNumber() << " ("
230 << ((BBI.Kind == ICSimpleFalse)
231 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
232 RetVal = IfConvertSimple(BBI);
233 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
235 if (isFalse) NumSimpleFalse++;
241 case ICTriangleFalse:
242 case ICTriangleFRev: {
243 bool isFalse = BBI.Kind == ICTriangleFalse;
244 bool isRev = (BBI.Kind == ICTriangleRev || BBI.Kind == ICTriangleFRev);
245 if (DisableTriangle && !isFalse && !isRev) break;
246 if (DisableTriangleR && !isFalse && isRev) break;
247 if (DisableTriangleF && isFalse && !isRev) break;
248 if (DisableTriangleFR && isFalse && isRev) break;
249 DOUT << "Ifcvt (Triangle";
254 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
255 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
257 RetVal = IfConvertTriangle(BBI);
258 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
261 if (isRev) NumTriangleFRev++;
262 else NumTriangleFalse++;
264 if (isRev) NumTriangleRev++;
271 if (DisableDiamond) break;
272 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
273 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
275 DOUT << "," << BBI.TailBB->getNumber() ;
277 RetVal = IfConvertDiamond(BBI);
278 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
279 if (RetVal) NumDiamonds++;
284 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
285 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
286 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
292 MadeChange |= Change;
301 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
302 MachineBasicBlock *TrueBB) {
303 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
304 E = BB->succ_end(); SI != E; ++SI) {
305 MachineBasicBlock *SuccBB = *SI;
306 if (SuccBB != TrueBB)
312 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
313 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
314 TII->RemoveBranch(*BBI.BB);
315 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
316 std::swap(BBI.TrueBB, BBI.FalseBB);
322 /// getNextBlock - Returns the next block in the function blocks ordering. If
323 /// it is the end, returns NULL.
324 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
325 MachineFunction::iterator I = BB;
326 MachineFunction::iterator E = BB->getParent()->end();
332 /// ValidSimple - Returns true if the 'true' block (along with its
333 /// predecessor) forms a valid simple shape for ifcvt.
334 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
335 if (TrueBBI.IsBeingAnalyzed)
338 if (TrueBBI.BB->pred_size() > 1) {
339 if (TrueBBI.CannotBeCopied ||
340 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
344 return !blockAlwaysFallThrough(TrueBBI) && TrueBBI.BrCond.size() == 0;
347 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
348 /// with their common predecessor) forms a valid triangle shape for ifcvt.
349 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
350 bool FalseBranch) const {
351 if (TrueBBI.IsBeingAnalyzed)
354 if (TrueBBI.BB->pred_size() > 1) {
355 if (TrueBBI.CannotBeCopied)
358 unsigned Size = TrueBBI.NonPredSize;
361 if (Size > TLI->getIfCvtDupBlockSizeLimit())
365 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
366 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
367 MachineFunction::iterator I = TrueBBI.BB;
368 if (++I == TrueBBI.BB->getParent()->end())
372 return TExit && TExit == FalseBBI.BB;
375 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
376 /// with their common predecessor) forms a valid diamond shape for ifcvt.
377 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
378 if (TrueBBI.IsBeingAnalyzed || FalseBBI.IsBeingAnalyzed)
381 MachineBasicBlock *TT = TrueBBI.TrueBB;
382 MachineBasicBlock *FT = FalseBBI.TrueBB;
384 if (!TT && blockAlwaysFallThrough(TrueBBI))
385 TT = getNextBlock(TrueBBI.BB);
386 if (!FT && blockAlwaysFallThrough(FalseBBI))
387 FT = getNextBlock(FalseBBI.BB);
390 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
392 // FIXME: Allow false block to have an early exit?
393 return (TrueBBI.BB->pred_size() == 1 &&
394 FalseBBI.BB->pred_size() == 1 &&
395 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
398 /// ScanInstructions - Scan all the instructions in the block to determine if
399 /// the block is predicable. In most cases, that means all the instructions
400 /// in the block has M_PREDICABLE flag. Also checks if the block contains any
401 /// instruction which can clobber a predicate (e.g. condition code register).
402 /// If so, the block is not predicable unless it's the last instruction.
403 void IfConverter::ScanInstructions(BBInfo &BBI) {
407 // First analyze the end of BB branches.
408 BBI.TrueBB = BBI.FalseBB = NULL;
411 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
412 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
414 if (BBI.BrCond.size()) {
415 // No false branch. This BB must end with a conditional branch and a
418 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
419 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
422 // Then scan all the instructions.
424 BBI.ClobbersPred = false;
425 bool SeenCondBr = false;
426 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
428 if (!BBI.CannotBeCopied && !TII->CanBeDuplicated(I))
429 BBI.CannotBeCopied = true;
431 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
432 bool isPredicated = TII->isPredicated(I);
433 bool isCondBr = BBI.IsBrAnalyzable &&
434 (TID->Flags & M_BRANCH_FLAG) != 0 && (TID->Flags & M_BARRIER_FLAG) == 0;
436 if (!isPredicated && !isCondBr)
439 if (BBI.ClobbersPred && !isPredicated) {
440 // Predicate modification instruction should end the block (except for
441 // already predicated instructions and end of block branches).
445 // Conditional branches is not predicable. But it may be eliminated.
449 // Predicate may have been modified, the subsequent (currently)
450 // unpredocated instructions cannot be correctly predicated.
451 BBI.IsUnpredicable = true;
455 if (TID->Flags & M_CLOBBERS_PRED)
456 BBI.ClobbersPred = true;
458 if ((TID->Flags & M_PREDICABLE) == 0) {
459 BBI.IsUnpredicable = true;
465 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
466 /// predicated by the specified predicate.
467 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
468 std::vector<MachineOperand> &Pred,
469 bool isTriangle, bool RevBranch) {
470 // Forget about it if it's unpredicable.
471 if (BBI.IsUnpredicable)
474 // If the block is dead, or it is going to be the entry block of a sub-CFG
475 // that will be if-converted, then it cannot be predicated.
476 if (BBI.IsDone || BBI.IsEnqueued)
479 // Check predication threshold.
480 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
483 // If it is already predicated, check if its predicate subsumes the new
485 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
488 if (BBI.BrCond.size()) {
492 // Test predicate subsumsion.
493 std::vector<MachineOperand> RevPred(Pred);
494 std::vector<MachineOperand> Cond(BBI.BrCond);
496 if (TII->ReverseBranchCondition(Cond))
499 if (TII->ReverseBranchCondition(RevPred) ||
500 !TII->SubsumesPredicate(Cond, RevPred))
507 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
508 /// the specified block. Record its successors and whether it looks like an
509 /// if-conversion candidate.
510 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
511 BBInfo &BBI = BBAnalysis[BB->getNumber()];
513 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
517 BBI.IsBeingAnalyzed = true;
518 BBI.Kind = ICNotClassfied;
520 ScanInstructions(BBI);
522 // Unanalyable or ends with fallthrough or unconditional branch.
523 if (!BBI.IsBrAnalyzable || BBI.BrCond.size() == 0) {
524 BBI.IsBeingAnalyzed = false;
525 BBI.IsAnalyzed = true;
529 // Do not ifcvt if either path is a back edge to the entry block.
530 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
531 BBI.IsBeingAnalyzed = false;
532 BBI.IsAnalyzed = true;
536 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB);
537 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB);
539 if (TrueBBI.IsDone && FalseBBI.IsDone) {
540 BBI.IsBeingAnalyzed = false;
541 BBI.IsAnalyzed = true;
545 std::vector<MachineOperand> RevCond(BBI.BrCond);
546 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
548 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
549 !(TrueBBI.ClobbersPred && FalseBBI.ClobbersPred) &&
550 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
551 FeasibilityAnalysis(FalseBBI, RevCond)) {
559 // Note TailBB can be empty.
560 BBI.Kind = ICDiamond;
561 BBI.TailBB = TrueBBI.TrueBB;
563 // FIXME: Consider duplicating if BB is small.
564 if (ValidTriangle(TrueBBI, FalseBBI) &&
565 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
573 BBI.Kind = ICTriangle;
574 } else if (ValidTriangle(TrueBBI, FalseBBI, true) &&
575 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
576 BBI.Kind = ICTriangleRev;
577 } else if (ValidSimple(TrueBBI) &&
578 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
579 // Simple (split, no rejoin):
587 } else if (CanRevCond) {
588 // Try the other path...
589 if (ValidTriangle(FalseBBI, TrueBBI) &&
590 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
591 BBI.Kind = ICTriangleFalse;
592 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
593 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
594 BBI.Kind = ICTriangleFRev;
595 } else if (ValidSimple(FalseBBI) &&
596 FeasibilityAnalysis(FalseBBI, RevCond)) {
597 BBI.Kind = ICSimpleFalse;
602 BBI.IsBeingAnalyzed = false;
603 BBI.IsAnalyzed = true;
607 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
608 /// expose more if-conversion opportunities. e.g.
630 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
634 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
635 /// candidates. It returns true if any CFG restructuring is done to expose more
636 /// if-conversion opportunities.
637 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
638 std::vector<BBInfo*> &Candidates) {
640 std::set<MachineBasicBlock*> Visited;
641 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
642 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
643 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
644 MachineBasicBlock *BB = *I;
645 BBInfo &BBI = AnalyzeBlock(BB);
651 case ICTriangleFalse:
654 BBI.IsEnqueued = true;
655 Candidates.push_back(&BBI);
658 Change |= AttemptRestructuring(BBI);
664 // Sort to favor more complex ifcvt scheme.
665 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
670 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
671 /// that all the intervening blocks are empty (given BB can fall through to its
673 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
674 MachineFunction::iterator I = BB;
675 MachineFunction::iterator TI = ToBB;
676 MachineFunction::iterator E = BB->getParent()->end();
678 if (I == E || !I->empty())
683 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
684 /// to determine if it can be if-converted. If predecessor is already
685 /// enqueud, dequeue it!
686 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
687 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
688 E = BB->pred_end(); PI != E; ++PI) {
689 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
690 if (PBBI.IsDone || PBBI.BB == BB)
692 PBBI.Kind = ICNotClassfied;
693 PBBI.IsAnalyzed = false;
694 PBBI.IsEnqueued = false;
698 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
700 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
701 const TargetInstrInfo *TII) {
702 std::vector<MachineOperand> NoCond;
703 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
706 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
708 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
709 MachineBasicBlock *TBB = NULL, *FBB = NULL;
710 std::vector<MachineOperand> Cond;
711 bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
712 bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
713 if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
714 if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
715 (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
716 BBI.BB->removeSuccessor(BBI.TrueBB);
717 if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
718 if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
719 (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
720 BBI.BB->removeSuccessor(BBI.FalseBB);
723 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
725 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
726 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
727 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
728 BBInfo *CvtBBI = &TrueBBI;
729 BBInfo *NextBBI = &FalseBBI;
731 std::vector<MachineOperand> Cond(BBI.BrCond);
732 if (BBI.Kind == ICSimpleFalse)
733 std::swap(CvtBBI, NextBBI);
735 if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
736 // Something has changed. It's no longer safe to predicate this block.
737 BBI.Kind = ICNotClassfied;
738 BBI.IsAnalyzed = false;
739 CvtBBI->IsAnalyzed = false;
743 if (BBI.Kind == ICSimpleFalse)
744 TII->ReverseBranchCondition(Cond);
746 if (CvtBBI->BB->pred_size() > 1) {
747 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
748 // Copy instructions in the true block, predicate them add them to
750 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
752 PredicateBlock(*CvtBBI, Cond);
754 // Merge converted block into entry block.
755 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
756 MergeBlocks(BBI, *CvtBBI);
759 bool IterIfcvt = true;
760 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
761 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
762 BBI.HasFallThrough = false;
763 // Now ifcvt'd block will look like this:
770 // We cannot further ifcvt this block because the unconditional branch
771 // will have to be predicated on the new condition, that will not be
772 // available if cmp executes.
776 RemoveExtraEdges(BBI);
778 // Update block info. BB can be iteratively if-converted.
782 CvtBBI->IsDone = true;
784 // FIXME: Must maintain LiveIns.
788 /// IfConvertTriangle - If convert a triangle sub-CFG.
790 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
791 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
792 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
793 BBInfo *CvtBBI = &TrueBBI;
794 BBInfo *NextBBI = &FalseBBI;
796 std::vector<MachineOperand> Cond(BBI.BrCond);
797 if (BBI.Kind == ICTriangleFalse || BBI.Kind == ICTriangleFRev)
798 std::swap(CvtBBI, NextBBI);
800 if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
801 // Something has changed. It's no longer safe to predicate this block.
802 BBI.Kind = ICNotClassfied;
803 BBI.IsAnalyzed = false;
804 CvtBBI->IsAnalyzed = false;
808 if (BBI.Kind == ICTriangleFalse || BBI.Kind == ICTriangleFRev)
809 TII->ReverseBranchCondition(Cond);
811 if (BBI.Kind == ICTriangleRev || BBI.Kind == ICTriangleFRev) {
812 ReverseBranchCondition(*CvtBBI);
813 // BB has been changed, modify its predecessors (except for this
814 // one) so they don't get ifcvt'ed based on bad intel.
815 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
816 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
817 MachineBasicBlock *PBB = *PI;
820 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
821 if (PBBI.IsEnqueued) {
822 PBBI.Kind = ICNotClassfied;
823 PBBI.IsAnalyzed = false;
824 PBBI.IsEnqueued = false;
829 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
830 bool DupBB = CvtBBI->BB->pred_size() > 1;
832 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
833 // Copy instructions in the true block, predicate them add them to
835 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
837 // Predicate the 'true' block after removing its branch.
838 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
839 PredicateBlock(*CvtBBI, Cond);
842 // If 'true' block has a 'false' successor, add an exit branch to it.
844 std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
845 if (TII->ReverseBranchCondition(RevCond))
846 assert(false && "Unable to reverse branch condition!");
848 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
849 BBI.BB->addSuccessor(CvtBBI->FalseBB);
851 TII->InsertBranch(*CvtBBI->BB, CvtBBI->FalseBB, NULL, RevCond);
856 // Now merge the entry of the triangle with the true block.
857 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
858 MergeBlocks(BBI, *CvtBBI);
861 // Merge in the 'false' block if the 'false' block has no other
862 // predecessors. Otherwise, add a unconditional branch from to 'false'.
863 bool FalseBBDead = false;
864 bool IterIfcvt = true;
865 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
866 if (!isFallThrough) {
867 // Only merge them if the true block does not fallthrough to the false
868 // block. By not merging them, we make it possible to iteratively
870 if (!HasEarlyExit && NextBBI->BB->pred_size() == 1) {
871 MergeBlocks(BBI, *NextBBI);
874 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
875 BBI.HasFallThrough = false;
877 // Mixed predicated and unpredicated code. This cannot be iteratively
882 RemoveExtraEdges(BBI);
884 // Update block info. BB can be iteratively if-converted.
888 CvtBBI->IsDone = true;
890 NextBBI->IsDone = true;
892 // FIXME: Must maintain LiveIns.
896 /// IfConvertDiamond - If convert a diamond sub-CFG.
898 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
899 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
900 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
902 SmallVector<MachineInstr*, 2> Dups;
904 // No common merge block. Check if the terminators (e.g. return) are
905 // the same or predicable.
906 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
907 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
908 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
909 if (TT->isIdenticalTo(FT))
910 Dups.push_back(TT); // Will erase these later.
911 else if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0 ||
912 (FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
913 return false; // Can't if-convert. Abort!
918 // One of the two pathes have more terminators, make sure they are
920 while (TT != BBI.TrueBB->end()) {
921 if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
922 return false; // Can't if-convert. Abort!
925 while (FT != BBI.FalseBB->end()) {
926 if ((FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
927 return false; // Can't if-convert. Abort!
932 // Remove the duplicated instructions from the 'true' block.
933 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
934 Dups[i]->eraseFromParent();
935 --TrueBBI.NonPredSize;
938 // Merge the 'true' and 'false' blocks by copying the instructions
939 // from the 'false' block to the 'true' block. That is, unless the true
940 // block would clobber the predicate, in that case, do the opposite.
941 BBInfo *BBI1 = &TrueBBI;
942 BBInfo *BBI2 = &FalseBBI;
943 std::vector<MachineOperand> RevCond(BBI.BrCond);
944 TII->ReverseBranchCondition(RevCond);
945 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
946 std::vector<MachineOperand> *Cond2 = &RevCond;
947 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
948 // Either the block fallthrough to another block or it ends with a
949 // return. If it's the former, add a branch to its successor.
950 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
951 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
953 if ((TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred) ||
954 (!TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred &&
955 NeedBr1 && !NeedBr2)) {
956 std::swap(BBI1, BBI2);
957 std::swap(Cond1, Cond2);
958 std::swap(NeedBr1, NeedBr2);
961 // Predicate the 'true' block after removing its branch.
962 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
963 PredicateBlock(*BBI1, *Cond1);
965 // Add an early exit branch if needed.
967 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
969 // Predicate the 'false' block.
970 PredicateBlock(*BBI2, *Cond2, true);
972 // Add an unconditional branch from 'false' to to 'false' successor if it
973 // will not be the fallthrough block.
974 if (NeedBr2 && !NeedBr1) {
975 // If BBI2 isn't going to be merged in, then the existing fallthrough
976 // or branch is fine.
977 if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
978 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
979 BBI2->HasFallThrough = false;
983 // Keep them as two separate blocks if there is an early exit.
985 MergeBlocks(*BBI1, *BBI2);
987 // Remove the conditional branch from entry to the blocks.
988 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
990 // Merge the combined block into the entry of the diamond.
991 MergeBlocks(BBI, *BBI1);
993 // 'True' and 'false' aren't combined, see if we need to add a unconditional
994 // branch to the 'false' block.
995 if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
996 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
997 BBI1->HasFallThrough = false;
1000 // If the if-converted block fallthrough or unconditionally branch into the
1001 // tail block, and the tail block does not have other predecessors, then
1002 // fold the tail block in as well.
1003 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
1005 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
1006 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1007 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
1008 MergeBlocks(*CvtBBI, TailBBI);
1009 TailBBI.IsDone = true;
1012 RemoveExtraEdges(BBI);
1014 // Update block info.
1015 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1017 // FIXME: Must maintain LiveIns.
1021 /// PredicateBlock - Predicate every instruction in the block with the specified
1022 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
1023 void IfConverter::PredicateBlock(BBInfo &BBI,
1024 std::vector<MachineOperand> &Cond,
1026 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
1028 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
1030 if (TII->isPredicated(I))
1032 if (!TII->PredicateInstruction(I, Cond)) {
1033 cerr << "Unable to predicate " << *I << "!\n";
1038 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1040 BBI.IsAnalyzed = false;
1041 BBI.NonPredSize = 0;
1046 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1047 /// the destination block. Skip end of block branches if IgnoreBr is true.
1048 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1049 std::vector<MachineOperand> &Cond,
1051 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1052 E = FromBBI.BB->end(); I != E; ++I) {
1053 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
1054 bool isPredicated = TII->isPredicated(I);
1055 // Do not copy the end of the block branches.
1056 if (IgnoreBr && !isPredicated && (TID->Flags & M_BRANCH_FLAG) != 0)
1059 MachineInstr *MI = I->clone();
1060 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1061 ToBBI.NonPredSize++;
1064 if (!TII->PredicateInstruction(MI, Cond)) {
1065 cerr << "Unable to predicate " << *MI << "!\n";
1070 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1071 std::back_inserter(ToBBI.Predicate));
1072 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1074 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1075 ToBBI.IsAnalyzed = false;
1080 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1082 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1083 ToBBI.BB->splice(ToBBI.BB->end(),
1084 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1086 // Redirect all branches to FromBB to ToBB.
1087 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1088 FromBBI.BB->pred_end());
1089 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1090 MachineBasicBlock *Pred = Preds[i];
1091 if (Pred == ToBBI.BB)
1093 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1096 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1097 FromBBI.BB->succ_end());
1098 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1099 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1101 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1102 MachineBasicBlock *Succ = Succs[i];
1103 // Fallthrough edge can't be transferred.
1104 if (Succ == FallThrough)
1106 FromBBI.BB->removeSuccessor(Succ);
1107 if (!ToBBI.BB->isSuccessor(Succ))
1108 ToBBI.BB->addSuccessor(Succ);
1111 // Now FromBBI always fall through to the next block!
1113 FromBBI.BB->addSuccessor(NBB);
1115 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1116 std::back_inserter(ToBBI.Predicate));
1117 FromBBI.Predicate.clear();
1119 ToBBI.NonPredSize += FromBBI.NonPredSize;
1120 FromBBI.NonPredSize = 0;
1122 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1123 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1124 ToBBI.IsAnalyzed = false;
1125 FromBBI.IsAnalyzed = false;