1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "BranchFolding.h"
16 #include "llvm/Function.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
33 // Hidden options for help debugging.
34 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
35 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
36 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
37 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
38 cl::init(false), cl::Hidden);
39 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
40 cl::init(false), cl::Hidden);
41 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
42 cl::init(false), cl::Hidden);
43 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
44 cl::init(false), cl::Hidden);
45 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
46 cl::init(false), cl::Hidden);
47 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
48 cl::init(false), cl::Hidden);
49 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
50 cl::init(false), cl::Hidden);
51 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
52 cl::init(true), cl::Hidden);
54 STATISTIC(NumSimple, "Number of simple if-conversions performed");
55 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
56 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
57 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
58 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
59 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
60 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
61 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
62 STATISTIC(NumDupBBs, "Number of duplicated blocks");
65 class IfConverter : public MachineFunctionPass {
67 ICNotClassfied, // BB data valid, but not classified.
68 ICSimpleFalse, // Same as ICSimple, but on the false path.
69 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
70 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
71 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
72 ICTriangleFalse, // Same as ICTriangle, but on the false path.
73 ICTriangle, // BB is entry of a triangle sub-CFG.
74 ICDiamond // BB is entry of a diamond sub-CFG.
77 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
78 /// if-conversion feasibility analysis. This includes results from
79 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
80 /// classification, and common tail block of its successors (if it's a
81 /// diamond shape), its size, whether it's predicable, and whether any
82 /// instruction can clobber the 'would-be' predicate.
84 /// IsDone - True if BB is not to be considered for ifcvt.
85 /// IsBeingAnalyzed - True if BB is currently being analyzed.
86 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
87 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
88 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
89 /// HasFallThrough - True if BB may fallthrough to the following BB.
90 /// IsUnpredicable - True if BB is known to be unpredicable.
91 /// ClobbersPred - True if BB could modify predicates (e.g. has
93 /// NonPredSize - Number of non-predicated instructions.
94 /// BB - Corresponding MachineBasicBlock.
95 /// TrueBB / FalseBB- See AnalyzeBranch().
96 /// BrCond - Conditions for end of block conditional branches.
97 /// Predicate - Predicate used in the BB.
100 bool IsBeingAnalyzed : 1;
103 bool IsBrAnalyzable : 1;
104 bool HasFallThrough : 1;
105 bool IsUnpredicable : 1;
106 bool CannotBeCopied : 1;
107 bool ClobbersPred : 1;
108 unsigned NonPredSize;
109 MachineBasicBlock *BB;
110 MachineBasicBlock *TrueBB;
111 MachineBasicBlock *FalseBB;
112 SmallVector<MachineOperand, 4> BrCond;
113 SmallVector<MachineOperand, 4> Predicate;
114 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
115 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
116 HasFallThrough(false), IsUnpredicable(false),
117 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
118 BB(0), TrueBB(0), FalseBB(0) {}
121 /// IfcvtToken - Record information about pending if-conversions to attempt:
122 /// BBI - Corresponding BBInfo.
123 /// Kind - Type of block. See IfcvtKind.
124 /// NeedSubsumption - True if the to-be-predicated BB has already been
126 /// NumDups - Number of instructions that would be duplicated due
127 /// to this if-conversion. (For diamonds, the number of
128 /// identical instructions at the beginnings of both
130 /// NumDups2 - For diamonds, the number of identical instructions
131 /// at the ends of both paths.
135 bool NeedSubsumption;
138 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
139 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
142 /// Roots - Basic blocks that do not have successors. These are the starting
143 /// points of Graph traversal.
144 std::vector<MachineBasicBlock*> Roots;
146 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
147 /// basic block number.
148 std::vector<BBInfo> BBAnalysis;
150 const TargetLowering *TLI;
151 const TargetInstrInfo *TII;
152 const TargetRegisterInfo *TRI;
157 IfConverter() : MachineFunctionPass(&ID), FnNum(-1) {}
159 virtual bool runOnMachineFunction(MachineFunction &MF);
160 virtual const char *getPassName() const { return "If Converter"; }
163 bool ReverseBranchCondition(BBInfo &BBI);
164 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
165 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
166 bool FalseBranch, unsigned &Dups) const;
167 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
168 unsigned &Dups1, unsigned &Dups2) const;
169 void ScanInstructions(BBInfo &BBI);
170 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
171 std::vector<IfcvtToken*> &Tokens);
172 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
173 bool isTriangle = false, bool RevBranch = false);
174 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
175 void InvalidatePreds(MachineBasicBlock *BB);
176 void RemoveExtraEdges(BBInfo &BBI);
177 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
178 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
179 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
180 unsigned NumDups1, unsigned NumDups2);
181 void PredicateBlock(BBInfo &BBI,
182 MachineBasicBlock::iterator E,
183 SmallVectorImpl<MachineOperand> &Cond,
184 SmallSet<unsigned, 4> &Redefs);
185 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
186 SmallVectorImpl<MachineOperand> &Cond,
187 SmallSet<unsigned, 4> &Redefs,
188 bool IgnoreBr = false);
189 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
191 bool MeetIfcvtSizeLimit(unsigned Size) const {
192 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit();
195 // blockAlwaysFallThrough - Block ends without a terminator.
196 bool blockAlwaysFallThrough(BBInfo &BBI) const {
197 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
200 // IfcvtTokenCmp - Used to sort if-conversion candidates.
201 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
202 int Incr1 = (C1->Kind == ICDiamond)
203 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
204 int Incr2 = (C2->Kind == ICDiamond)
205 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
208 else if (Incr1 == Incr2) {
209 // Favors subsumption.
210 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
212 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
213 // Favors diamond over triangle, etc.
214 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
216 else if (C1->Kind == C2->Kind)
217 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
224 char IfConverter::ID = 0;
227 static RegisterPass<IfConverter>
228 X("if-converter", "If Converter");
230 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
232 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
233 TLI = MF.getTarget().getTargetLowering();
234 TII = MF.getTarget().getInstrInfo();
235 TRI = MF.getTarget().getRegisterInfo();
236 if (!TII) return false;
238 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
239 << MF.getFunction()->getName() << "\'");
241 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
242 DEBUG(dbgs() << " skipped\n");
245 DEBUG(dbgs() << "\n");
248 BBAnalysis.resize(MF.getNumBlockIDs());
250 // Look for root nodes, i.e. blocks without successors.
251 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
255 std::vector<IfcvtToken*> Tokens;
257 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
258 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
259 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
260 // Do an initial analysis for each basic block and find all the potential
261 // candidates to perform if-conversion.
263 AnalyzeBlocks(MF, Tokens);
264 while (!Tokens.empty()) {
265 IfcvtToken *Token = Tokens.back();
267 BBInfo &BBI = Token->BBI;
268 IfcvtKind Kind = Token->Kind;
269 unsigned NumDups = Token->NumDups;
270 unsigned NumDups2 = Token->NumDups2;
274 // If the block has been evicted out of the queue or it has already been
275 // marked dead (due to it being predicated), then skip it.
277 BBI.IsEnqueued = false;
281 BBI.IsEnqueued = false;
285 default: assert(false && "Unexpected!");
288 case ICSimpleFalse: {
289 bool isFalse = Kind == ICSimpleFalse;
290 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
291 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
293 << "): BB#" << BBI.BB->getNumber() << " ("
294 << ((Kind == ICSimpleFalse)
295 ? BBI.FalseBB->getNumber()
296 : BBI.TrueBB->getNumber()) << ") ");
297 RetVal = IfConvertSimple(BBI, Kind);
298 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
300 if (isFalse) NumSimpleFalse++;
307 case ICTriangleFalse:
308 case ICTriangleFRev: {
309 bool isFalse = Kind == ICTriangleFalse;
310 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
311 if (DisableTriangle && !isFalse && !isRev) break;
312 if (DisableTriangleR && !isFalse && isRev) break;
313 if (DisableTriangleF && isFalse && !isRev) break;
314 if (DisableTriangleFR && isFalse && isRev) break;
315 DEBUG(dbgs() << "Ifcvt (Triangle");
317 DEBUG(dbgs() << " false");
319 DEBUG(dbgs() << " rev");
320 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
321 << BBI.TrueBB->getNumber() << ",F:"
322 << BBI.FalseBB->getNumber() << ") ");
323 RetVal = IfConvertTriangle(BBI, Kind);
324 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
327 if (isRev) NumTriangleFRev++;
328 else NumTriangleFalse++;
330 if (isRev) NumTriangleRev++;
337 if (DisableDiamond) break;
338 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
339 << BBI.TrueBB->getNumber() << ",F:"
340 << BBI.FalseBB->getNumber() << ") ");
341 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
342 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
343 if (RetVal) NumDiamonds++;
350 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
351 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
352 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
358 MadeChange |= Change;
361 // Delete tokens in case of early exit.
362 while (!Tokens.empty()) {
363 IfcvtToken *Token = Tokens.back();
372 if (MadeChange && !IfCvtBranchFold) {
373 BranchFolder BF(false);
374 BF.OptimizeFunction(MF, TII,
375 MF.getTarget().getRegisterInfo(),
376 getAnalysisIfAvailable<MachineModuleInfo>());
382 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
383 /// its 'true' successor.
384 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
385 MachineBasicBlock *TrueBB) {
386 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
387 E = BB->succ_end(); SI != E; ++SI) {
388 MachineBasicBlock *SuccBB = *SI;
389 if (SuccBB != TrueBB)
395 /// ReverseBranchCondition - Reverse the condition of the end of the block
396 /// branch. Swap block's 'true' and 'false' successors.
397 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
398 DebugLoc dl; // FIXME: this is nowhere
399 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
400 TII->RemoveBranch(*BBI.BB);
401 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
402 std::swap(BBI.TrueBB, BBI.FalseBB);
408 /// getNextBlock - Returns the next block in the function blocks ordering. If
409 /// it is the end, returns NULL.
410 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
411 MachineFunction::iterator I = BB;
412 MachineFunction::iterator E = BB->getParent()->end();
418 /// ValidSimple - Returns true if the 'true' block (along with its
419 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
420 /// number of instructions that the ifcvt would need to duplicate if performed
422 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
424 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
427 if (TrueBBI.IsBrAnalyzable)
430 if (TrueBBI.BB->pred_size() > 1) {
431 if (TrueBBI.CannotBeCopied ||
432 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
434 Dups = TrueBBI.NonPredSize;
440 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
441 /// with their common predecessor) forms a valid triangle shape for ifcvt.
442 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
443 /// branches to the 'false' block rather than the other way around. It also
444 /// returns the number of instructions that the ifcvt would need to duplicate
445 /// if performed in 'Dups'.
446 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
447 bool FalseBranch, unsigned &Dups) const {
449 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
452 if (TrueBBI.BB->pred_size() > 1) {
453 if (TrueBBI.CannotBeCopied)
456 unsigned Size = TrueBBI.NonPredSize;
457 if (TrueBBI.IsBrAnalyzable) {
458 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
459 // Ends with an unconditional branch. It will be removed.
462 MachineBasicBlock *FExit = FalseBranch
463 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
465 // Require a conditional branch
469 if (Size > TLI->getIfCvtDupBlockSizeLimit())
474 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
475 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
476 MachineFunction::iterator I = TrueBBI.BB;
477 if (++I == TrueBBI.BB->getParent()->end())
481 return TExit && TExit == FalseBBI.BB;
485 MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
486 const TargetInstrInfo *TII) {
487 MachineBasicBlock::iterator I = BB->end();
488 while (I != BB->begin()) {
490 if (!I->getDesc().isBranch())
496 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
497 /// with their common predecessor) forms a valid diamond shape for ifcvt.
498 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
499 unsigned &Dups1, unsigned &Dups2) const {
501 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
502 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
505 MachineBasicBlock *TT = TrueBBI.TrueBB;
506 MachineBasicBlock *FT = FalseBBI.TrueBB;
508 if (!TT && blockAlwaysFallThrough(TrueBBI))
509 TT = getNextBlock(TrueBBI.BB);
510 if (!FT && blockAlwaysFallThrough(FalseBBI))
511 FT = getNextBlock(FalseBBI.BB);
514 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
516 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
519 // FIXME: Allow true block to have an early exit?
520 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
521 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
524 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
525 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
526 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
527 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
528 // Skip dbg_value instructions
529 while (TI != TIE && TI->isDebugValue())
531 while (FI != FIE && FI->isDebugValue())
533 while (TI != TIE && FI != FIE) {
534 if (!TI->isIdenticalTo(FI))
541 TI = firstNonBranchInst(TrueBBI.BB, TII);
542 FI = firstNonBranchInst(FalseBBI.BB, TII);
543 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
544 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
545 // Skip dbg_value instructions
546 while (TI != TIB && TI->isDebugValue())
548 while (FI != FIB && FI->isDebugValue())
550 while (TI != TIB && FI != FIB) {
551 if (!TI->isIdenticalTo(FI))
561 /// ScanInstructions - Scan all the instructions in the block to determine if
562 /// the block is predicable. In most cases, that means all the instructions
563 /// in the block are isPredicable(). Also checks if the block contains any
564 /// instruction which can clobber a predicate (e.g. condition code register).
565 /// If so, the block is not predicable unless it's the last instruction.
566 void IfConverter::ScanInstructions(BBInfo &BBI) {
570 bool AlreadyPredicated = BBI.Predicate.size() > 0;
571 // First analyze the end of BB branches.
572 BBI.TrueBB = BBI.FalseBB = NULL;
575 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
576 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
578 if (BBI.BrCond.size()) {
579 // No false branch. This BB must end with a conditional branch and a
582 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
584 // Malformed bcc? True and false blocks are the same?
585 BBI.IsUnpredicable = true;
590 // Then scan all the instructions.
592 BBI.ClobbersPred = false;
593 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
595 if (I->isDebugValue())
598 const TargetInstrDesc &TID = I->getDesc();
599 if (TID.isNotDuplicable())
600 BBI.CannotBeCopied = true;
602 bool isPredicated = TII->isPredicated(I);
603 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
608 else if (!AlreadyPredicated) {
609 // FIXME: This instruction is already predicated before the
610 // if-conversion pass. It's probably something like a conditional move.
611 // Mark this block unpredicable for now.
612 BBI.IsUnpredicable = true;
617 if (BBI.ClobbersPred && !isPredicated) {
618 // Predicate modification instruction should end the block (except for
619 // already predicated instructions and end of block branches).
621 // A conditional branch is not predicable, but it may be eliminated.
625 // Predicate may have been modified, the subsequent (currently)
626 // unpredicated instructions cannot be correctly predicated.
627 BBI.IsUnpredicable = true;
631 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
632 // still potentially predicable.
633 std::vector<MachineOperand> PredDefs;
634 if (TII->DefinesPredicate(I, PredDefs))
635 BBI.ClobbersPred = true;
637 if (!TII->isPredicable(I)) {
638 BBI.IsUnpredicable = true;
644 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
645 /// predicated by the specified predicate.
646 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
647 SmallVectorImpl<MachineOperand> &Pred,
648 bool isTriangle, bool RevBranch) {
649 // If the block is dead or unpredicable, then it cannot be predicated.
650 if (BBI.IsDone || BBI.IsUnpredicable)
653 // If it is already predicated, check if its predicate subsumes the new
655 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
658 if (BBI.BrCond.size()) {
662 // Test predicate subsumption.
663 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
664 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
666 if (TII->ReverseBranchCondition(Cond))
669 if (TII->ReverseBranchCondition(RevPred) ||
670 !TII->SubsumesPredicate(Cond, RevPred))
677 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
678 /// the specified block. Record its successors and whether it looks like an
679 /// if-conversion candidate.
680 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
681 std::vector<IfcvtToken*> &Tokens) {
682 BBInfo &BBI = BBAnalysis[BB->getNumber()];
684 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
688 BBI.IsBeingAnalyzed = true;
690 ScanInstructions(BBI);
692 // Unanalyzable or ends with fallthrough or unconditional branch.
693 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
694 BBI.IsBeingAnalyzed = false;
695 BBI.IsAnalyzed = true;
699 // Do not ifcvt if either path is a back edge to the entry block.
700 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
701 BBI.IsBeingAnalyzed = false;
702 BBI.IsAnalyzed = true;
706 // Do not ifcvt if true and false fallthrough blocks are the same.
708 BBI.IsBeingAnalyzed = false;
709 BBI.IsAnalyzed = true;
713 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
714 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
716 if (TrueBBI.IsDone && FalseBBI.IsDone) {
717 BBI.IsBeingAnalyzed = false;
718 BBI.IsAnalyzed = true;
722 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
723 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
727 bool TNeedSub = TrueBBI.Predicate.size() > 0;
728 bool FNeedSub = FalseBBI.Predicate.size() > 0;
729 bool Enqueued = false;
730 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
731 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
732 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
733 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
734 FeasibilityAnalysis(FalseBBI, RevCond)) {
742 // Note TailBB can be empty.
743 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
748 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
749 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
750 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
758 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
762 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
763 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
764 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
765 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
769 if (ValidSimple(TrueBBI, Dups) &&
770 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
771 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
772 // Simple (split, no rejoin):
779 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
784 // Try the other path...
785 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
786 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
787 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
788 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
792 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
793 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
794 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
795 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
799 if (ValidSimple(FalseBBI, Dups) &&
800 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
801 FeasibilityAnalysis(FalseBBI, RevCond)) {
802 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
807 BBI.IsEnqueued = Enqueued;
808 BBI.IsBeingAnalyzed = false;
809 BBI.IsAnalyzed = true;
813 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
815 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
816 std::vector<IfcvtToken*> &Tokens) {
817 std::set<MachineBasicBlock*> Visited;
818 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
819 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
820 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
821 MachineBasicBlock *BB = *I;
822 AnalyzeBlock(BB, Tokens);
826 // Sort to favor more complex ifcvt scheme.
827 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
830 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
831 /// that all the intervening blocks are empty (given BB can fall through to its
833 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
834 MachineFunction::iterator PI = BB;
835 MachineFunction::iterator I = llvm::next(PI);
836 MachineFunction::iterator TI = ToBB;
837 MachineFunction::iterator E = BB->getParent()->end();
839 // Check isSuccessor to avoid case where the next block is empty, but
840 // it's not a successor.
841 if (I == E || !I->empty() || !PI->isSuccessor(I))
848 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
849 /// to determine if it can be if-converted. If predecessor is already enqueued,
851 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
852 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
853 E = BB->pred_end(); PI != E; ++PI) {
854 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
855 if (PBBI.IsDone || PBBI.BB == BB)
857 PBBI.IsAnalyzed = false;
858 PBBI.IsEnqueued = false;
862 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
864 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
865 const TargetInstrInfo *TII) {
866 DebugLoc dl; // FIXME: this is nowhere
867 SmallVector<MachineOperand, 0> NoCond;
868 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
871 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
873 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
874 MachineBasicBlock *TBB = NULL, *FBB = NULL;
875 SmallVector<MachineOperand, 4> Cond;
876 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
877 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
880 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
881 /// modeled as read + write (sort like two-address instructions). These
882 /// routines track register liveness and add implicit uses to if-converted
883 /// instructions to conform to the model.
884 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
885 const TargetRegisterInfo *TRI) {
886 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
887 E = BB->livein_end(); I != E; ++I) {
890 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
892 Redefs.insert(*Subreg);
896 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
897 const TargetRegisterInfo *TRI,
898 bool AddImpUse = false) {
899 SmallVector<unsigned, 4> Defs;
900 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
901 const MachineOperand &MO = MI->getOperand(i);
904 unsigned Reg = MO.getReg();
909 else if (MO.isKill()) {
911 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
915 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
916 unsigned Reg = Defs[i];
917 if (Redefs.count(Reg)) {
919 // Treat predicated update as read + write.
920 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
921 true/*IsImp*/,false/*IsKill*/));
924 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
930 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
931 MachineBasicBlock::iterator E,
932 SmallSet<unsigned,4> &Redefs,
933 const TargetRegisterInfo *TRI) {
935 UpdatePredRedefs(I, Redefs, TRI);
940 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
942 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
943 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
944 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
945 BBInfo *CvtBBI = &TrueBBI;
946 BBInfo *NextBBI = &FalseBBI;
948 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
949 if (Kind == ICSimpleFalse)
950 std::swap(CvtBBI, NextBBI);
952 if (CvtBBI->IsDone ||
953 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
954 // Something has changed. It's no longer safe to predicate this block.
955 BBI.IsAnalyzed = false;
956 CvtBBI->IsAnalyzed = false;
960 if (Kind == ICSimpleFalse)
961 if (TII->ReverseBranchCondition(Cond))
962 assert(false && "Unable to reverse branch condition!");
964 // Initialize liveins to the first BB. These are potentiall re-defined by
965 // predicated instructions.
966 SmallSet<unsigned, 4> Redefs;
967 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
968 InitPredRedefs(NextBBI->BB, Redefs, TRI);
970 if (CvtBBI->BB->pred_size() > 1) {
971 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
972 // Copy instructions in the true block, predicate them, and add them to
974 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
976 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
978 // Merge converted block into entry block.
979 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
980 MergeBlocks(BBI, *CvtBBI);
983 bool IterIfcvt = true;
984 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
985 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
986 BBI.HasFallThrough = false;
987 // Now ifcvt'd block will look like this:
994 // We cannot further ifcvt this block because the unconditional branch
995 // will have to be predicated on the new condition, that will not be
996 // available if cmp executes.
1000 RemoveExtraEdges(BBI);
1002 // Update block info. BB can be iteratively if-converted.
1005 InvalidatePreds(BBI.BB);
1006 CvtBBI->IsDone = true;
1008 // FIXME: Must maintain LiveIns.
1012 /// IfConvertTriangle - If convert a triangle sub-CFG.
1014 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1015 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1016 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1017 BBInfo *CvtBBI = &TrueBBI;
1018 BBInfo *NextBBI = &FalseBBI;
1019 DebugLoc dl; // FIXME: this is nowhere
1021 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1022 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1023 std::swap(CvtBBI, NextBBI);
1025 if (CvtBBI->IsDone ||
1026 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1027 // Something has changed. It's no longer safe to predicate this block.
1028 BBI.IsAnalyzed = false;
1029 CvtBBI->IsAnalyzed = false;
1033 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1034 if (TII->ReverseBranchCondition(Cond))
1035 assert(false && "Unable to reverse branch condition!");
1037 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1038 if (ReverseBranchCondition(*CvtBBI)) {
1039 // BB has been changed, modify its predecessors (except for this
1040 // one) so they don't get ifcvt'ed based on bad intel.
1041 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1042 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1043 MachineBasicBlock *PBB = *PI;
1046 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1047 if (PBBI.IsEnqueued) {
1048 PBBI.IsAnalyzed = false;
1049 PBBI.IsEnqueued = false;
1055 // Initialize liveins to the first BB. These are potentiall re-defined by
1056 // predicated instructions.
1057 SmallSet<unsigned, 4> Redefs;
1058 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1059 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1061 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1062 bool DupBB = CvtBBI->BB->pred_size() > 1;
1064 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1065 // Copy instructions in the true block, predicate them, and add them to
1067 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1069 // Predicate the 'true' block after removing its branch.
1070 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1071 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1073 // Now merge the entry of the triangle with the true block.
1074 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1075 MergeBlocks(BBI, *CvtBBI);
1078 // If 'true' block has a 'false' successor, add an exit branch to it.
1080 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1081 CvtBBI->BrCond.end());
1082 if (TII->ReverseBranchCondition(RevCond))
1083 assert(false && "Unable to reverse branch condition!");
1084 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1085 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1088 // Merge in the 'false' block if the 'false' block has no other
1089 // predecessors. Otherwise, add an unconditional branch to 'false'.
1090 bool FalseBBDead = false;
1091 bool IterIfcvt = true;
1092 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1093 if (!isFallThrough) {
1094 // Only merge them if the true block does not fallthrough to the false
1095 // block. By not merging them, we make it possible to iteratively
1096 // ifcvt the blocks.
1097 if (!HasEarlyExit &&
1098 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1099 MergeBlocks(BBI, *NextBBI);
1102 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1103 BBI.HasFallThrough = false;
1105 // Mixed predicated and unpredicated code. This cannot be iteratively
1110 RemoveExtraEdges(BBI);
1112 // Update block info. BB can be iteratively if-converted.
1115 InvalidatePreds(BBI.BB);
1116 CvtBBI->IsDone = true;
1118 NextBBI->IsDone = true;
1120 // FIXME: Must maintain LiveIns.
1124 /// IfConvertDiamond - If convert a diamond sub-CFG.
1126 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1127 unsigned NumDups1, unsigned NumDups2) {
1128 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1129 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1130 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1131 // True block must fall through or end with an unanalyzable terminator.
1133 if (blockAlwaysFallThrough(TrueBBI))
1134 TailBB = FalseBBI.TrueBB;
1135 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1138 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1139 TrueBBI.BB->pred_size() > 1 ||
1140 FalseBBI.BB->pred_size() > 1) {
1141 // Something has changed. It's no longer safe to predicate these blocks.
1142 BBI.IsAnalyzed = false;
1143 TrueBBI.IsAnalyzed = false;
1144 FalseBBI.IsAnalyzed = false;
1148 // Merge the 'true' and 'false' blocks by copying the instructions
1149 // from the 'false' block to the 'true' block. That is, unless the true
1150 // block would clobber the predicate, in that case, do the opposite.
1151 BBInfo *BBI1 = &TrueBBI;
1152 BBInfo *BBI2 = &FalseBBI;
1153 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1154 if (TII->ReverseBranchCondition(RevCond))
1155 assert(false && "Unable to reverse branch condition!");
1156 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1157 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1159 // Figure out the more profitable ordering.
1160 bool DoSwap = false;
1161 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1163 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1164 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1168 std::swap(BBI1, BBI2);
1169 std::swap(Cond1, Cond2);
1172 // Remove the conditional branch from entry to the blocks.
1173 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1175 // Initialize liveins to the first BB. These are potentiall re-defined by
1176 // predicated instructions.
1177 SmallSet<unsigned, 4> Redefs;
1178 InitPredRedefs(BBI1->BB, Redefs, TRI);
1180 // Remove the duplicated instructions at the beginnings of both paths.
1181 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1182 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1183 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1184 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1185 // Skip dbg_value instructions
1186 while (DI1 != DIE1 && DI1->isDebugValue())
1188 while (DI2 != DIE2 && DI2->isDebugValue())
1190 BBI1->NonPredSize -= NumDups1;
1191 BBI2->NonPredSize -= NumDups1;
1192 while (NumDups1 != 0) {
1198 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1199 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1200 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1202 // Predicate the 'true' block after removing its branch.
1203 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1204 DI1 = BBI1->BB->end();
1205 for (unsigned i = 0; i != NumDups2; ) {
1206 // NumDups2 only counted non-dbg_value instructions, so this won't
1207 // run off the head of the list.
1208 assert (DI1 != BBI1->BB->begin());
1210 // skip dbg_value instructions
1211 if (!DI1->isDebugValue())
1214 BBI1->BB->erase(DI1, BBI1->BB->end());
1215 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
1217 // Predicate the 'false' block.
1218 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1219 DI2 = BBI2->BB->end();
1220 while (NumDups2 != 0) {
1221 // NumDups2 only counted non-dbg_value instructions, so this won't
1222 // run off the head of the list.
1223 assert (DI2 != BBI2->BB->begin());
1225 // skip dbg_value instructions
1226 if (!DI2->isDebugValue())
1229 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1231 // Merge the true block into the entry of the diamond.
1232 MergeBlocks(BBI, *BBI1);
1233 MergeBlocks(BBI, *BBI2);
1235 // If the if-converted block falls through or unconditionally branches into
1236 // the tail block, and the tail block does not have other predecessors, then
1237 // fold the tail block in as well. Otherwise, unless it falls through to the
1238 // tail, add a unconditional branch to it.
1240 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1241 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1242 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1243 MergeBlocks(BBI, TailBBI);
1244 TailBBI.IsDone = true;
1246 InsertUncondBranch(BBI.BB, TailBB, TII);
1247 BBI.HasFallThrough = false;
1251 RemoveExtraEdges(BBI);
1253 // Update block info.
1254 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1255 InvalidatePreds(BBI.BB);
1257 // FIXME: Must maintain LiveIns.
1261 /// PredicateBlock - Predicate instructions from the start of the block to the
1262 /// specified end with the specified condition.
1263 void IfConverter::PredicateBlock(BBInfo &BBI,
1264 MachineBasicBlock::iterator E,
1265 SmallVectorImpl<MachineOperand> &Cond,
1266 SmallSet<unsigned, 4> &Redefs) {
1267 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1268 if (I->isDebugValue() || TII->isPredicated(I))
1270 if (!TII->PredicateInstruction(I, Cond)) {
1272 dbgs() << "Unable to predicate " << *I << "!\n";
1274 llvm_unreachable(0);
1277 // If the predicated instruction now re-defines a register as the result of
1278 // if-conversion, add an implicit kill.
1279 UpdatePredRedefs(I, Redefs, TRI, true);
1282 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1284 BBI.IsAnalyzed = false;
1285 BBI.NonPredSize = 0;
1290 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1291 /// the destination block. Skip end of block branches if IgnoreBr is true.
1292 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1293 SmallVectorImpl<MachineOperand> &Cond,
1294 SmallSet<unsigned, 4> &Redefs,
1296 MachineFunction &MF = *ToBBI.BB->getParent();
1298 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1299 E = FromBBI.BB->end(); I != E; ++I) {
1300 const TargetInstrDesc &TID = I->getDesc();
1301 // Do not copy the end of the block branches.
1302 if (IgnoreBr && TID.isBranch())
1305 MachineInstr *MI = MF.CloneMachineInstr(I);
1306 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1307 ToBBI.NonPredSize++;
1309 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1310 if (!TII->PredicateInstruction(MI, Cond)) {
1312 dbgs() << "Unable to predicate " << *I << "!\n";
1314 llvm_unreachable(0);
1318 // If the predicated instruction now re-defines a register as the result of
1319 // if-conversion, add an implicit kill.
1320 UpdatePredRedefs(MI, Redefs, TRI, true);
1323 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1324 FromBBI.BB->succ_end());
1325 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1326 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1328 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1329 MachineBasicBlock *Succ = Succs[i];
1330 // Fallthrough edge can't be transferred.
1331 if (Succ == FallThrough)
1333 ToBBI.BB->addSuccessor(Succ);
1336 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1337 std::back_inserter(ToBBI.Predicate));
1338 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1340 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1341 ToBBI.IsAnalyzed = false;
1346 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1348 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1349 ToBBI.BB->splice(ToBBI.BB->end(),
1350 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1352 // Redirect all branches to FromBB to ToBB.
1353 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1354 FromBBI.BB->pred_end());
1355 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1356 MachineBasicBlock *Pred = Preds[i];
1357 if (Pred == ToBBI.BB)
1359 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1362 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1363 FromBBI.BB->succ_end());
1364 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1365 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1367 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1368 MachineBasicBlock *Succ = Succs[i];
1369 // Fallthrough edge can't be transferred.
1370 if (Succ == FallThrough)
1372 FromBBI.BB->removeSuccessor(Succ);
1373 ToBBI.BB->addSuccessor(Succ);
1376 // Now FromBBI always falls through to the next block!
1377 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1378 FromBBI.BB->addSuccessor(NBB);
1380 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1381 std::back_inserter(ToBBI.Predicate));
1382 FromBBI.Predicate.clear();
1384 ToBBI.NonPredSize += FromBBI.NonPredSize;
1385 FromBBI.NonPredSize = 0;
1387 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1388 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1389 ToBBI.IsAnalyzed = false;
1390 FromBBI.IsAnalyzed = false;