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 ICSimpleFalse, // Same as ICSimple, but on the false path.
64 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
65 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
66 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
67 ICTriangleFalse, // Same as ICTriangle, but on the false path.
68 ICTriangle, // BB is entry of a triangle sub-CFG.
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 /// IsDone - True if BB is not to be considered for ifcvt.
80 /// IsBeingAnalyzed - True if BB is currently being analyzed.
81 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
82 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
83 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
84 /// HasFallThrough - True if BB may fallthrough to the following BB.
85 /// IsUnpredicable - True if BB is known to be unpredicable.
86 /// ClobbersPredicate- True if BB would modify the predicate (e.g. has
88 /// NonPredSize - Number of non-predicated instructions.
89 /// BB - Corresponding MachineBasicBlock.
90 /// TrueBB / FalseBB- See AnalyzeBranch().
91 /// BrCond - Conditions for end of block conditional branches.
92 /// Predicate - Predicate used in the BB.
95 bool IsBeingAnalyzed : 1;
98 bool IsBrAnalyzable : 1;
99 bool HasFallThrough : 1;
100 bool IsUnpredicable : 1;
101 bool CannotBeCopied : 1;
102 bool ClobbersPred : 1;
103 unsigned NonPredSize;
104 MachineBasicBlock *BB;
105 MachineBasicBlock *TrueBB;
106 MachineBasicBlock *FalseBB;
107 std::vector<MachineOperand> BrCond;
108 std::vector<MachineOperand> Predicate;
109 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
110 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
111 HasFallThrough(false), IsUnpredicable(false),
112 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
113 BB(0), TrueBB(0), FalseBB(0) {}
116 /// IfcvtToken - Record information about pending if-conversions to attemp:
117 /// BBI - Corresponding BBInfo.
118 /// Kind - Type of block. See IfcvtKind.
119 /// NeedSubsumsion - True if the to be predicated BB has already been
121 /// Duplicates - Number of instructions that would be duplicated due
122 /// to this if-conversion.
128 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d)
129 : BBI(b), Kind(k), NeedSubsumsion(s), Duplicates(d) {}
132 /// Roots - Basic blocks that do not have successors. These are the starting
133 /// points of Graph traversal.
134 std::vector<MachineBasicBlock*> Roots;
136 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
137 /// basic block number.
138 std::vector<BBInfo> BBAnalysis;
140 const TargetLowering *TLI;
141 const TargetInstrInfo *TII;
145 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
147 virtual bool runOnMachineFunction(MachineFunction &MF);
148 virtual const char *getPassName() const { return "If converter"; }
151 bool ReverseBranchCondition(BBInfo &BBI);
152 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
153 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
154 bool FalseBranch, unsigned &Dups) const;
155 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
156 void ScanInstructions(BBInfo &BBI);
157 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
158 std::vector<IfcvtToken*> &Tokens);
159 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
160 bool isTriangle = false, bool RevBranch = false);
161 bool AnalyzeBlocks(MachineFunction &MF,
162 std::vector<IfcvtToken*> &Tokens);
163 void ReTryPreds(MachineBasicBlock *BB);
164 void RemoveExtraEdges(BBInfo &BBI);
165 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
166 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
167 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind);
168 void PredicateBlock(BBInfo &BBI,
169 std::vector<MachineOperand> &Cond,
170 bool IgnoreTerm = false);
171 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
172 std::vector<MachineOperand> &Cond,
173 bool IgnoreBr = false);
174 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
176 // blockAlwaysFallThrough - Block ends without a terminator.
177 bool blockAlwaysFallThrough(BBInfo &BBI) const {
178 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
181 // IfcvtTokenCmp - Used to sort if-conversion candidates.
182 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
183 // Favors subsumsion.
184 if (C1->NeedSubsumsion == false && C2->NeedSubsumsion == true)
186 else if (C1->NeedSubsumsion == C2->NeedSubsumsion) {
187 if (C1->Duplicates > C2->Duplicates)
189 else if (C1->Duplicates == C2->Duplicates) {
190 // Favors diamond over triangle, etc.
191 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
193 else if (C1->Kind == C2->Kind)
194 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
201 char IfConverter::ID = 0;
204 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
206 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
207 TLI = MF.getTarget().getTargetLowering();
208 TII = MF.getTarget().getInstrInfo();
209 if (!TII) return false;
211 static int FnNum = -1;
212 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
213 << MF.getFunction()->getName() << "\'";
215 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
216 DOUT << " skipped\n";
222 BBAnalysis.resize(MF.getNumBlockIDs());
224 // Look for root nodes, i.e. blocks without successors.
225 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
226 if (I->succ_size() == 0)
229 std::vector<IfcvtToken*> Tokens;
231 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
232 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
233 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
234 // Do an intial analysis for each basic block and finding all the potential
235 // candidates to perform if-convesion.
236 bool Change = AnalyzeBlocks(MF, Tokens);
237 while (!Tokens.empty()) {
238 IfcvtToken *Token = Tokens.back();
240 BBInfo &BBI = Token->BBI;
241 IfcvtKind Kind = Token->Kind;
243 // If the block has been evicted out of the queue or it has already been
244 // marked dead (due to it being predicated), then skip it.
246 BBI.IsEnqueued = false;
250 BBI.IsEnqueued = false;
254 default: assert(false && "Unexpected!");
257 case ICSimpleFalse: {
258 bool isFalse = Kind == ICSimpleFalse;
259 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
260 DOUT << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"")
261 << "): BB#" << BBI.BB->getNumber() << " ("
262 << ((Kind == ICSimpleFalse)
263 ? BBI.FalseBB->getNumber()
264 : BBI.TrueBB->getNumber()) << ") ";
265 RetVal = IfConvertSimple(BBI, Kind);
266 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
268 if (isFalse) NumSimpleFalse++;
274 case ICTriangleFalse:
275 case ICTriangleFRev: {
276 bool isFalse = Kind == ICTriangleFalse;
277 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
278 if (DisableTriangle && !isFalse && !isRev) break;
279 if (DisableTriangleR && !isFalse && isRev) break;
280 if (DisableTriangleF && isFalse && !isRev) break;
281 if (DisableTriangleFR && isFalse && isRev) break;
282 DOUT << "Ifcvt (Triangle";
287 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
288 << BBI.TrueBB->getNumber() << ",F:"
289 << BBI.FalseBB->getNumber() << ") ";
290 RetVal = IfConvertTriangle(BBI, Kind);
291 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
294 if (isRev) NumTriangleFRev++;
295 else NumTriangleFalse++;
297 if (isRev) NumTriangleRev++;
304 if (DisableDiamond) break;
305 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
306 << BBI.TrueBB->getNumber() << ",F:"
307 << BBI.FalseBB->getNumber() << ") ";
308 RetVal = IfConvertDiamond(BBI, Kind);
309 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
310 if (RetVal) NumDiamonds++;
317 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
318 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
319 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
325 MadeChange |= Change;
328 // Delete tokens in case of early exit.
329 while (!Tokens.empty()) {
330 IfcvtToken *Token = Tokens.back();
342 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
343 /// its 'true' successor.
344 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
345 MachineBasicBlock *TrueBB) {
346 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
347 E = BB->succ_end(); SI != E; ++SI) {
348 MachineBasicBlock *SuccBB = *SI;
349 if (SuccBB != TrueBB)
355 /// ReverseBranchCondition - Reverse the condition of the end of the block
356 /// branchs. Swap block's 'true' and 'false' successors.
357 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
358 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
359 TII->RemoveBranch(*BBI.BB);
360 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
361 std::swap(BBI.TrueBB, BBI.FalseBB);
367 /// getNextBlock - Returns the next block in the function blocks ordering. If
368 /// it is the end, returns NULL.
369 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
370 MachineFunction::iterator I = BB;
371 MachineFunction::iterator E = BB->getParent()->end();
377 /// ValidSimple - Returns true if the 'true' block (along with its
378 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
379 /// number of instructions that the ifcvt would need to duplicate if performed
381 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
383 if (TrueBBI.IsBeingAnalyzed)
386 if (TrueBBI.BB->pred_size() > 1) {
387 if (TrueBBI.CannotBeCopied ||
388 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
390 Dups = TrueBBI.NonPredSize;
393 return !blockAlwaysFallThrough(TrueBBI) && TrueBBI.BrCond.size() == 0;
396 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
397 /// with their common predecessor) forms a valid triangle shape for ifcvt.
398 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
399 /// branches to the false branch rather than the other way around. It also
400 /// returns the number of instructions that the ifcvt would need to duplicate
401 /// if performed in 'Dups'.
402 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
403 bool FalseBranch, unsigned &Dups) const {
405 if (TrueBBI.IsBeingAnalyzed)
408 if (TrueBBI.BB->pred_size() > 1) {
409 if (TrueBBI.CannotBeCopied)
412 unsigned Size = TrueBBI.NonPredSize;
413 if (TrueBBI.IsBrAnalyzable) {
414 if (TrueBBI.TrueBB && TrueBBI.BrCond.size() == 0)
415 // End with an unconditional branch. It will be removed.
418 MachineBasicBlock *FExit = FalseBranch
419 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
421 // Require a conditional branch
425 if (Size > TLI->getIfCvtDupBlockSizeLimit())
430 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
431 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
432 MachineFunction::iterator I = TrueBBI.BB;
433 if (++I == TrueBBI.BB->getParent()->end())
437 return TExit && TExit == FalseBBI.BB;
440 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
441 /// with their common predecessor) forms a valid diamond shape for ifcvt.
442 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
443 if (TrueBBI.IsBeingAnalyzed || FalseBBI.IsBeingAnalyzed)
446 MachineBasicBlock *TT = TrueBBI.TrueBB;
447 MachineBasicBlock *FT = FalseBBI.TrueBB;
449 if (!TT && blockAlwaysFallThrough(TrueBBI))
450 TT = getNextBlock(TrueBBI.BB);
451 if (!FT && blockAlwaysFallThrough(FalseBBI))
452 FT = getNextBlock(FalseBBI.BB);
455 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
457 // FIXME: Allow false block to have an early exit?
458 return (TrueBBI.BB->pred_size() == 1 &&
459 FalseBBI.BB->pred_size() == 1 &&
460 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
463 /// ScanInstructions - Scan all the instructions in the block to determine if
464 /// the block is predicable. In most cases, that means all the instructions
465 /// in the block has M_PREDICABLE flag. Also checks if the block contains any
466 /// instruction which can clobber a predicate (e.g. condition code register).
467 /// If so, the block is not predicable unless it's the last instruction.
468 void IfConverter::ScanInstructions(BBInfo &BBI) {
472 // First analyze the end of BB branches.
473 BBI.TrueBB = BBI.FalseBB = NULL;
476 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
477 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
479 if (BBI.BrCond.size()) {
480 // No false branch. This BB must end with a conditional branch and a
483 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
484 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
487 // Then scan all the instructions.
489 BBI.ClobbersPred = false;
490 bool SeenCondBr = false;
491 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
493 if (!BBI.CannotBeCopied && !TII->CanBeDuplicated(I))
494 BBI.CannotBeCopied = true;
496 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
497 bool isPredicated = TII->isPredicated(I);
498 bool isCondBr = BBI.IsBrAnalyzable &&
499 (TID->Flags & M_BRANCH_FLAG) != 0 && (TID->Flags & M_BARRIER_FLAG) == 0;
501 if (!isPredicated && !isCondBr)
504 if (BBI.ClobbersPred && !isPredicated) {
505 // Predicate modification instruction should end the block (except for
506 // already predicated instructions and end of block branches).
510 // Conditional branches is not predicable. But it may be eliminated.
514 // Predicate may have been modified, the subsequent (currently)
515 // unpredocated instructions cannot be correctly predicated.
516 BBI.IsUnpredicable = true;
520 if (TID->Flags & M_CLOBBERS_PRED)
521 BBI.ClobbersPred = true;
523 if ((TID->Flags & M_PREDICABLE) == 0) {
524 BBI.IsUnpredicable = true;
530 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
531 /// predicated by the specified predicate.
532 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
533 std::vector<MachineOperand> &Pred,
534 bool isTriangle, bool RevBranch) {
535 // If the block is dead or unpredicable, then it cannot be predicated.
536 if (BBI.IsDone || BBI.IsUnpredicable)
539 // Check predication threshold.
540 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
543 // If it is already predicated, check if its predicate subsumes the new
545 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
548 if (BBI.BrCond.size()) {
552 // Test predicate subsumsion.
553 std::vector<MachineOperand> RevPred(Pred);
554 std::vector<MachineOperand> Cond(BBI.BrCond);
556 if (TII->ReverseBranchCondition(Cond))
559 if (TII->ReverseBranchCondition(RevPred) ||
560 !TII->SubsumesPredicate(Cond, RevPred))
567 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
568 /// the specified block. Record its successors and whether it looks like an
569 /// if-conversion candidate.
570 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
571 std::vector<IfcvtToken*> &Tokens) {
572 BBInfo &BBI = BBAnalysis[BB->getNumber()];
574 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
578 BBI.IsBeingAnalyzed = true;
580 ScanInstructions(BBI);
582 // Unanalyable or ends with fallthrough or unconditional branch.
583 if (!BBI.IsBrAnalyzable || BBI.BrCond.size() == 0) {
584 BBI.IsBeingAnalyzed = false;
585 BBI.IsAnalyzed = true;
589 // Do not ifcvt if either path is a back edge to the entry block.
590 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
591 BBI.IsBeingAnalyzed = false;
592 BBI.IsAnalyzed = true;
596 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
597 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
599 if (TrueBBI.IsDone && FalseBBI.IsDone) {
600 BBI.IsBeingAnalyzed = false;
601 BBI.IsAnalyzed = true;
605 std::vector<MachineOperand> RevCond(BBI.BrCond);
606 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
609 bool TNeedSub = TrueBBI.Predicate.size() > 0;
610 bool FNeedSub = FalseBBI.Predicate.size() > 0;
611 bool Enqueued = false;
612 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
613 !(TrueBBI.ClobbersPred && FalseBBI.ClobbersPred) &&
614 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
615 FeasibilityAnalysis(FalseBBI, RevCond)) {
623 // Note TailBB can be empty.
624 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups));
628 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
629 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
637 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
641 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
642 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
643 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
647 if (ValidSimple(TrueBBI, Dups) &&
648 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
649 // Simple (split, no rejoin):
656 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
661 // Try the other path...
662 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
663 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
664 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
668 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
669 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
670 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
674 if (ValidSimple(FalseBBI, Dups) &&
675 FeasibilityAnalysis(FalseBBI, RevCond)) {
676 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
681 BBI.IsEnqueued = Enqueued;
682 BBI.IsBeingAnalyzed = false;
683 BBI.IsAnalyzed = true;
687 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
688 /// candidates. It returns true if any CFG restructuring is done to expose more
689 /// if-conversion opportunities.
690 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
691 std::vector<IfcvtToken*> &Tokens) {
693 std::set<MachineBasicBlock*> Visited;
694 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
695 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
696 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
697 MachineBasicBlock *BB = *I;
698 AnalyzeBlock(BB, Tokens);
702 // Sort to favor more complex ifcvt scheme.
703 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
708 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
709 /// that all the intervening blocks are empty (given BB can fall through to its
711 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
712 MachineFunction::iterator I = BB;
713 MachineFunction::iterator TI = ToBB;
714 MachineFunction::iterator E = BB->getParent()->end();
716 if (I == E || !I->empty())
721 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
722 /// to determine if it can be if-converted. If predecessor is already
723 /// enqueud, dequeue it!
724 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
725 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
726 E = BB->pred_end(); PI != E; ++PI) {
727 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
728 if (PBBI.IsDone || PBBI.BB == BB)
730 PBBI.IsAnalyzed = false;
731 PBBI.IsEnqueued = false;
735 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
737 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
738 const TargetInstrInfo *TII) {
739 std::vector<MachineOperand> NoCond;
740 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
743 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
745 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
746 MachineBasicBlock *TBB = NULL, *FBB = NULL;
747 std::vector<MachineOperand> Cond;
748 bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
749 bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
750 if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
751 if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
752 (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
753 BBI.BB->removeSuccessor(BBI.TrueBB);
754 if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
755 if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
756 (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
757 BBI.BB->removeSuccessor(BBI.FalseBB);
760 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
762 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
763 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
764 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
765 BBInfo *CvtBBI = &TrueBBI;
766 BBInfo *NextBBI = &FalseBBI;
768 std::vector<MachineOperand> Cond(BBI.BrCond);
769 if (Kind == ICSimpleFalse)
770 std::swap(CvtBBI, NextBBI);
772 if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
773 // Something has changed. It's no longer safe to predicate this block.
774 BBI.IsAnalyzed = false;
775 CvtBBI->IsAnalyzed = false;
779 if (Kind == ICSimpleFalse)
780 TII->ReverseBranchCondition(Cond);
782 if (CvtBBI->BB->pred_size() > 1) {
783 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
784 // Copy instructions in the true block, predicate them add them to
786 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
788 PredicateBlock(*CvtBBI, Cond);
790 // Merge converted block into entry block.
791 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
792 MergeBlocks(BBI, *CvtBBI);
795 bool IterIfcvt = true;
796 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
797 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
798 BBI.HasFallThrough = false;
799 // Now ifcvt'd block will look like this:
806 // We cannot further ifcvt this block because the unconditional branch
807 // will have to be predicated on the new condition, that will not be
808 // available if cmp executes.
812 RemoveExtraEdges(BBI);
814 // Update block info. BB can be iteratively if-converted.
818 CvtBBI->IsDone = true;
820 // FIXME: Must maintain LiveIns.
824 /// IfConvertTriangle - If convert a triangle sub-CFG.
826 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
827 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
828 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
829 BBInfo *CvtBBI = &TrueBBI;
830 BBInfo *NextBBI = &FalseBBI;
832 std::vector<MachineOperand> Cond(BBI.BrCond);
833 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
834 std::swap(CvtBBI, NextBBI);
836 if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
837 // Something has changed. It's no longer safe to predicate this block.
838 BBI.IsAnalyzed = false;
839 CvtBBI->IsAnalyzed = false;
843 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
844 TII->ReverseBranchCondition(Cond);
846 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
847 ReverseBranchCondition(*CvtBBI);
848 // BB has been changed, modify its predecessors (except for this
849 // one) so they don't get ifcvt'ed based on bad intel.
850 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
851 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
852 MachineBasicBlock *PBB = *PI;
855 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
856 if (PBBI.IsEnqueued) {
857 PBBI.IsAnalyzed = false;
858 PBBI.IsEnqueued = false;
863 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
864 bool DupBB = CvtBBI->BB->pred_size() > 1;
866 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
867 // Copy instructions in the true block, predicate them add them to
869 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
871 // Predicate the 'true' block after removing its branch.
872 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
873 PredicateBlock(*CvtBBI, Cond);
876 // If 'true' block has a 'false' successor, add an exit branch to it.
878 std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
879 if (TII->ReverseBranchCondition(RevCond))
880 assert(false && "Unable to reverse branch condition!");
882 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
883 BBI.BB->addSuccessor(CvtBBI->FalseBB);
885 TII->InsertBranch(*CvtBBI->BB, CvtBBI->FalseBB, NULL, RevCond);
890 // Now merge the entry of the triangle with the true block.
891 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
892 MergeBlocks(BBI, *CvtBBI);
895 // Merge in the 'false' block if the 'false' block has no other
896 // predecessors. Otherwise, add a unconditional branch from to 'false'.
897 bool FalseBBDead = false;
898 bool IterIfcvt = true;
899 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
900 if (!isFallThrough) {
901 // Only merge them if the true block does not fallthrough to the false
902 // block. By not merging them, we make it possible to iteratively
904 if (!HasEarlyExit && NextBBI->BB->pred_size() == 1) {
905 MergeBlocks(BBI, *NextBBI);
908 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
909 BBI.HasFallThrough = false;
911 // Mixed predicated and unpredicated code. This cannot be iteratively
916 RemoveExtraEdges(BBI);
918 // Update block info. BB can be iteratively if-converted.
922 CvtBBI->IsDone = true;
924 NextBBI->IsDone = true;
926 // FIXME: Must maintain LiveIns.
930 /// IfConvertDiamond - If convert a diamond sub-CFG.
932 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind) {
933 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
934 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
935 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
937 SmallVector<MachineInstr*, 2> Dups;
939 // No common merge block. Check if the terminators (e.g. return) are
940 // the same or predicable.
941 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
942 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
943 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
944 if (TT->isIdenticalTo(FT))
945 Dups.push_back(TT); // Will erase these later.
946 else if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0 ||
947 (FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
948 return false; // Can't if-convert. Abort!
953 // One of the two pathes have more terminators, make sure they are
955 while (TT != BBI.TrueBB->end()) {
956 if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
957 return false; // Can't if-convert. Abort!
960 while (FT != BBI.FalseBB->end()) {
961 if ((FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
962 return false; // Can't if-convert. Abort!
967 // Remove the duplicated instructions from the 'true' block.
968 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
969 Dups[i]->eraseFromParent();
970 --TrueBBI.NonPredSize;
973 // Merge the 'true' and 'false' blocks by copying the instructions
974 // from the 'false' block to the 'true' block. That is, unless the true
975 // block would clobber the predicate, in that case, do the opposite.
976 BBInfo *BBI1 = &TrueBBI;
977 BBInfo *BBI2 = &FalseBBI;
978 std::vector<MachineOperand> RevCond(BBI.BrCond);
979 TII->ReverseBranchCondition(RevCond);
980 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
981 std::vector<MachineOperand> *Cond2 = &RevCond;
982 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
983 // Either the block fallthrough to another block or it ends with a
984 // return. If it's the former, add a branch to its successor.
985 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size() > 0;
986 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size() > 0;
988 // Figure out the more profitable ordering.
990 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
992 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
993 if (!NeedBr1 && NeedBr2)
995 else if (NeedBr1 == NeedBr2) {
996 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1001 std::swap(BBI1, BBI2);
1002 std::swap(Cond1, Cond2);
1003 std::swap(NeedBr1, NeedBr2);
1006 // Predicate the 'true' block after removing its branch.
1007 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1008 PredicateBlock(*BBI1, *Cond1);
1010 // Add an early exit branch if needed.
1012 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
1014 // Predicate the 'false' block.
1015 PredicateBlock(*BBI2, *Cond2, true);
1017 // Add an unconditional branch from 'false' to to 'false' successor if it
1018 // will not be the fallthrough block.
1019 if (NeedBr2 && !NeedBr1) {
1020 // If BBI2 isn't going to be merged in, then the existing fallthrough
1021 // or branch is fine.
1022 if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
1023 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
1024 BBI2->HasFallThrough = false;
1028 // Keep them as two separate blocks if there is an early exit.
1030 MergeBlocks(*BBI1, *BBI2);
1032 // Remove the conditional branch from entry to the blocks.
1033 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1035 // Merge the combined block into the entry of the diamond.
1036 MergeBlocks(BBI, *BBI1);
1038 // 'True' and 'false' aren't combined, see if we need to add a unconditional
1039 // branch to the 'false' block.
1040 if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
1041 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
1042 BBI1->HasFallThrough = false;
1045 // If the if-converted block fallthrough or unconditionally branch into the
1046 // tail block, and the tail block does not have other predecessors, then
1047 // fold the tail block in as well.
1048 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
1050 TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
1051 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1052 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1053 MergeBlocks(*CvtBBI, TailBBI);
1054 TailBBI.IsDone = true;
1057 RemoveExtraEdges(BBI);
1059 // Update block info.
1060 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1062 // FIXME: Must maintain LiveIns.
1066 /// PredicateBlock - Predicate every instruction in the block with the specified
1067 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
1068 void IfConverter::PredicateBlock(BBInfo &BBI,
1069 std::vector<MachineOperand> &Cond,
1071 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
1073 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
1075 if (TII->isPredicated(I))
1077 if (!TII->PredicateInstruction(I, Cond)) {
1078 cerr << "Unable to predicate " << *I << "!\n";
1083 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1085 BBI.IsAnalyzed = false;
1086 BBI.NonPredSize = 0;
1091 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1092 /// the destination block. Skip end of block branches if IgnoreBr is true.
1093 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1094 std::vector<MachineOperand> &Cond,
1096 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1097 E = FromBBI.BB->end(); I != E; ++I) {
1098 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
1099 bool isPredicated = TII->isPredicated(I);
1100 // Do not copy the end of the block branches.
1101 if (IgnoreBr && !isPredicated && (TID->Flags & M_BRANCH_FLAG) != 0)
1104 MachineInstr *MI = I->clone();
1105 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1106 ToBBI.NonPredSize++;
1109 if (!TII->PredicateInstruction(MI, Cond)) {
1110 cerr << "Unable to predicate " << *MI << "!\n";
1115 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1116 std::back_inserter(ToBBI.Predicate));
1117 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1119 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1120 ToBBI.IsAnalyzed = false;
1125 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1127 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1128 ToBBI.BB->splice(ToBBI.BB->end(),
1129 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1131 // Redirect all branches to FromBB to ToBB.
1132 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1133 FromBBI.BB->pred_end());
1134 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1135 MachineBasicBlock *Pred = Preds[i];
1136 if (Pred == ToBBI.BB)
1138 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1141 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1142 FromBBI.BB->succ_end());
1143 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1144 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1146 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1147 MachineBasicBlock *Succ = Succs[i];
1148 // Fallthrough edge can't be transferred.
1149 if (Succ == FallThrough)
1151 FromBBI.BB->removeSuccessor(Succ);
1152 if (!ToBBI.BB->isSuccessor(Succ))
1153 ToBBI.BB->addSuccessor(Succ);
1156 // Now FromBBI always fall through to the next block!
1158 FromBBI.BB->addSuccessor(NBB);
1160 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1161 std::back_inserter(ToBBI.Predicate));
1162 FromBBI.Predicate.clear();
1164 ToBBI.NonPredSize += FromBBI.NonPredSize;
1165 FromBBI.NonPredSize = 0;
1167 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1168 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1169 ToBBI.IsAnalyzed = false;
1170 FromBBI.IsAnalyzed = false;