LLVM API Documentation
00001 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the machine instruction level if-conversion pass. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #define DEBUG_TYPE "ifcvt" 00015 #include "llvm/Function.h" 00016 #include "llvm/CodeGen/Passes.h" 00017 #include "llvm/CodeGen/MachineModuleInfo.h" 00018 #include "llvm/CodeGen/MachineFunctionPass.h" 00019 #include "llvm/Target/TargetInstrInfo.h" 00020 #include "llvm/Target/TargetLowering.h" 00021 #include "llvm/Target/TargetMachine.h" 00022 #include "llvm/Support/CommandLine.h" 00023 #include "llvm/Support/Debug.h" 00024 #include "llvm/ADT/DepthFirstIterator.h" 00025 #include "llvm/ADT/Statistic.h" 00026 #include "llvm/ADT/STLExtras.h" 00027 using namespace llvm; 00028 00029 // Hidden options for help debugging. 00030 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden); 00031 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden); 00032 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden); 00033 static cl::opt<bool> DisableSimple("disable-ifcvt-simple", 00034 cl::init(false), cl::Hidden); 00035 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false", 00036 cl::init(false), cl::Hidden); 00037 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle", 00038 cl::init(false), cl::Hidden); 00039 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev", 00040 cl::init(false), cl::Hidden); 00041 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false", 00042 cl::init(false), cl::Hidden); 00043 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev", 00044 cl::init(false), cl::Hidden); 00045 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond", 00046 cl::init(false), cl::Hidden); 00047 00048 STATISTIC(NumSimple, "Number of simple if-conversions performed"); 00049 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed"); 00050 STATISTIC(NumTriangle, "Number of triangle if-conversions performed"); 00051 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed"); 00052 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed"); 00053 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed"); 00054 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed"); 00055 STATISTIC(NumIfConvBBs, "Number of if-converted blocks"); 00056 STATISTIC(NumDupBBs, "Number of duplicated blocks"); 00057 00058 namespace { 00059 class VISIBILITY_HIDDEN IfConverter : public MachineFunctionPass { 00060 enum IfcvtKind { 00061 ICNotClassfied, // BB data valid, but not classified. 00062 ICSimpleFalse, // Same as ICSimple, but on the false path. 00063 ICSimple, // BB is entry of an one split, no rejoin sub-CFG. 00064 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition. 00065 ICTriangleRev, // Same as ICTriangle, but true path rev condition. 00066 ICTriangleFalse, // Same as ICTriangle, but on the false path. 00067 ICTriangle, // BB is entry of a triangle sub-CFG. 00068 ICDiamond // BB is entry of a diamond sub-CFG. 00069 }; 00070 00071 /// BBInfo - One per MachineBasicBlock, this is used to cache the result 00072 /// if-conversion feasibility analysis. This includes results from 00073 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its 00074 /// classification, and common tail block of its successors (if it's a 00075 /// diamond shape), its size, whether it's predicable, and whether any 00076 /// instruction can clobber the 'would-be' predicate. 00077 /// 00078 /// IsDone - True if BB is not to be considered for ifcvt. 00079 /// IsBeingAnalyzed - True if BB is currently being analyzed. 00080 /// IsAnalyzed - True if BB has been analyzed (info is still valid). 00081 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed. 00082 /// IsBrAnalyzable - True if AnalyzeBranch() returns false. 00083 /// HasFallThrough - True if BB may fallthrough to the following BB. 00084 /// IsUnpredicable - True if BB is known to be unpredicable. 00085 /// ClobbersPred - True if BB could modify predicates (e.g. has 00086 /// cmp, call, etc.) 00087 /// NonPredSize - Number of non-predicated instructions. 00088 /// BB - Corresponding MachineBasicBlock. 00089 /// TrueBB / FalseBB- See AnalyzeBranch(). 00090 /// BrCond - Conditions for end of block conditional branches. 00091 /// Predicate - Predicate used in the BB. 00092 struct BBInfo { 00093 bool IsDone : 1; 00094 bool IsBeingAnalyzed : 1; 00095 bool IsAnalyzed : 1; 00096 bool IsEnqueued : 1; 00097 bool IsBrAnalyzable : 1; 00098 bool HasFallThrough : 1; 00099 bool IsUnpredicable : 1; 00100 bool CannotBeCopied : 1; 00101 bool ClobbersPred : 1; 00102 unsigned NonPredSize; 00103 MachineBasicBlock *BB; 00104 MachineBasicBlock *TrueBB; 00105 MachineBasicBlock *FalseBB; 00106 SmallVector<MachineOperand, 4> BrCond; 00107 SmallVector<MachineOperand, 4> Predicate; 00108 BBInfo() : IsDone(false), IsBeingAnalyzed(false), 00109 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false), 00110 HasFallThrough(false), IsUnpredicable(false), 00111 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0), 00112 BB(0), TrueBB(0), FalseBB(0) {} 00113 }; 00114 00115 /// IfcvtToken - Record information about pending if-conversions to attemp: 00116 /// BBI - Corresponding BBInfo. 00117 /// Kind - Type of block. See IfcvtKind. 00118 /// NeedSubsumsion - True if the to be predicated BB has already been 00119 /// predicated. 00120 /// NumDups - Number of instructions that would be duplicated due 00121 /// to this if-conversion. (For diamonds, the number of 00122 /// identical instructions at the beginnings of both 00123 /// paths). 00124 /// NumDups2 - For diamonds, the number of identical instructions 00125 /// at the ends of both paths. 00126 struct IfcvtToken { 00127 BBInfo &BBI; 00128 IfcvtKind Kind; 00129 bool NeedSubsumsion; 00130 unsigned NumDups; 00131 unsigned NumDups2; 00132 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0) 00133 : BBI(b), Kind(k), NeedSubsumsion(s), NumDups(d), NumDups2(d2) {} 00134 }; 00135 00136 /// Roots - Basic blocks that do not have successors. These are the starting 00137 /// points of Graph traversal. 00138 std::vector<MachineBasicBlock*> Roots; 00139 00140 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by 00141 /// basic block number. 00142 std::vector<BBInfo> BBAnalysis; 00143 00144 const TargetLowering *TLI; 00145 const TargetInstrInfo *TII; 00146 bool MadeChange; 00147 public: 00148 static char ID; 00149 IfConverter() : MachineFunctionPass(&ID) {} 00150 00151 virtual bool runOnMachineFunction(MachineFunction &MF); 00152 virtual const char *getPassName() const { return "If Converter"; } 00153 00154 private: 00155 bool ReverseBranchCondition(BBInfo &BBI); 00156 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const; 00157 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 00158 bool FalseBranch, unsigned &Dups) const; 00159 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 00160 unsigned &Dups1, unsigned &Dups2) const; 00161 void ScanInstructions(BBInfo &BBI); 00162 BBInfo &AnalyzeBlock(MachineBasicBlock *BB, 00163 std::vector<IfcvtToken*> &Tokens); 00164 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond, 00165 bool isTriangle = false, bool RevBranch = false); 00166 bool AnalyzeBlocks(MachineFunction &MF, 00167 std::vector<IfcvtToken*> &Tokens); 00168 void InvalidatePreds(MachineBasicBlock *BB); 00169 void RemoveExtraEdges(BBInfo &BBI); 00170 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind); 00171 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind); 00172 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 00173 unsigned NumDups1, unsigned NumDups2); 00174 void PredicateBlock(BBInfo &BBI, 00175 MachineBasicBlock::iterator E, 00176 SmallVectorImpl<MachineOperand> &Cond); 00177 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 00178 SmallVectorImpl<MachineOperand> &Cond, 00179 bool IgnoreBr = false); 00180 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI); 00181 00182 bool MeetIfcvtSizeLimit(unsigned Size) const { 00183 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit(); 00184 } 00185 00186 // blockAlwaysFallThrough - Block ends without a terminator. 00187 bool blockAlwaysFallThrough(BBInfo &BBI) const { 00188 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL; 00189 } 00190 00191 // IfcvtTokenCmp - Used to sort if-conversion candidates. 00192 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) { 00193 int Incr1 = (C1->Kind == ICDiamond) 00194 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups; 00195 int Incr2 = (C2->Kind == ICDiamond) 00196 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups; 00197 if (Incr1 > Incr2) 00198 return true; 00199 else if (Incr1 == Incr2) { 00200 // Favors subsumsion. 00201 if (C1->NeedSubsumsion == false && C2->NeedSubsumsion == true) 00202 return true; 00203 else if (C1->NeedSubsumsion == C2->NeedSubsumsion) { 00204 // Favors diamond over triangle, etc. 00205 if ((unsigned)C1->Kind < (unsigned)C2->Kind) 00206 return true; 00207 else if (C1->Kind == C2->Kind) 00208 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber(); 00209 } 00210 } 00211 return false; 00212 } 00213 }; 00214 00215 char IfConverter::ID = 0; 00216 } 00217 00218 static RegisterPass<IfConverter> 00219 X("if-converter", "If Converter"); 00220 00221 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); } 00222 00223 bool IfConverter::runOnMachineFunction(MachineFunction &MF) { 00224 TLI = MF.getTarget().getTargetLowering(); 00225 TII = MF.getTarget().getInstrInfo(); 00226 if (!TII) return false; 00227 00228 static int FnNum = -1; 00229 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'" 00230 << MF.getFunction()->getName() << "\'"; 00231 00232 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) { 00233 DOUT << " skipped\n"; 00234 return false; 00235 } 00236 DOUT << "\n"; 00237 00238 MF.RenumberBlocks(); 00239 BBAnalysis.resize(MF.getNumBlockIDs()); 00240 00241 // Look for root nodes, i.e. blocks without successors. 00242 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) 00243 if (I->succ_empty()) 00244 Roots.push_back(I); 00245 00246 std::vector<IfcvtToken*> Tokens; 00247 MadeChange = false; 00248 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + 00249 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds; 00250 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) { 00251 // Do an intial analysis for each basic block and finding all the potential 00252 // candidates to perform if-convesion. 00253 bool Change = AnalyzeBlocks(MF, Tokens); 00254 while (!Tokens.empty()) { 00255 IfcvtToken *Token = Tokens.back(); 00256 Tokens.pop_back(); 00257 BBInfo &BBI = Token->BBI; 00258 IfcvtKind Kind = Token->Kind; 00259 unsigned NumDups = Token->NumDups; 00260 unsigned NumDups2 = Token->NumDups2; 00261 00262 delete Token; 00263 00264 // If the block has been evicted out of the queue or it has already been 00265 // marked dead (due to it being predicated), then skip it. 00266 if (BBI.IsDone) 00267 BBI.IsEnqueued = false; 00268 if (!BBI.IsEnqueued) 00269 continue; 00270 00271 BBI.IsEnqueued = false; 00272 00273 bool RetVal = false; 00274 switch (Kind) { 00275 default: assert(false && "Unexpected!"); 00276 break; 00277 case ICSimple: 00278 case ICSimpleFalse: { 00279 bool isFalse = Kind == ICSimpleFalse; 00280 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break; 00281 DOUT << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"") 00282 << "): BB#" << BBI.BB->getNumber() << " (" 00283 << ((Kind == ICSimpleFalse) 00284 ? BBI.FalseBB->getNumber() 00285 : BBI.TrueBB->getNumber()) << ") "; 00286 RetVal = IfConvertSimple(BBI, Kind); 00287 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n"; 00288 if (RetVal) { 00289 if (isFalse) NumSimpleFalse++; 00290 else NumSimple++; 00291 } 00292 break; 00293 } 00294 case ICTriangle: 00295 case ICTriangleRev: 00296 case ICTriangleFalse: 00297 case ICTriangleFRev: { 00298 bool isFalse = Kind == ICTriangleFalse; 00299 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev); 00300 if (DisableTriangle && !isFalse && !isRev) break; 00301 if (DisableTriangleR && !isFalse && isRev) break; 00302 if (DisableTriangleF && isFalse && !isRev) break; 00303 if (DisableTriangleFR && isFalse && isRev) break; 00304 DOUT << "Ifcvt (Triangle"; 00305 if (isFalse) 00306 DOUT << " false"; 00307 if (isRev) 00308 DOUT << " rev"; 00309 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:" 00310 << BBI.TrueBB->getNumber() << ",F:" 00311 << BBI.FalseBB->getNumber() << ") "; 00312 RetVal = IfConvertTriangle(BBI, Kind); 00313 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n"; 00314 if (RetVal) { 00315 if (isFalse) { 00316 if (isRev) NumTriangleFRev++; 00317 else NumTriangleFalse++; 00318 } else { 00319 if (isRev) NumTriangleRev++; 00320 else NumTriangle++; 00321 } 00322 } 00323 break; 00324 } 00325 case ICDiamond: { 00326 if (DisableDiamond) break; 00327 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:" 00328 << BBI.TrueBB->getNumber() << ",F:" 00329 << BBI.FalseBB->getNumber() << ") "; 00330 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2); 00331 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n"; 00332 if (RetVal) NumDiamonds++; 00333 break; 00334 } 00335 } 00336 00337 Change |= RetVal; 00338 00339 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev + 00340 NumTriangleFalse + NumTriangleFRev + NumDiamonds; 00341 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit) 00342 break; 00343 } 00344 00345 if (!Change) 00346 break; 00347 MadeChange |= Change; 00348 } 00349 00350 // Delete tokens in case of early exit. 00351 while (!Tokens.empty()) { 00352 IfcvtToken *Token = Tokens.back(); 00353 Tokens.pop_back(); 00354 delete Token; 00355 } 00356 00357 Tokens.clear(); 00358 Roots.clear(); 00359 BBAnalysis.clear(); 00360 00361 return MadeChange; 00362 } 00363 00364 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given 00365 /// its 'true' successor. 00366 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, 00367 MachineBasicBlock *TrueBB) { 00368 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 00369 E = BB->succ_end(); SI != E; ++SI) { 00370 MachineBasicBlock *SuccBB = *SI; 00371 if (SuccBB != TrueBB) 00372 return SuccBB; 00373 } 00374 return NULL; 00375 } 00376 00377 /// ReverseBranchCondition - Reverse the condition of the end of the block 00378 /// branchs. Swap block's 'true' and 'false' successors. 00379 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) { 00380 if (!TII->ReverseBranchCondition(BBI.BrCond)) { 00381 TII->RemoveBranch(*BBI.BB); 00382 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond); 00383 std::swap(BBI.TrueBB, BBI.FalseBB); 00384 return true; 00385 } 00386 return false; 00387 } 00388 00389 /// getNextBlock - Returns the next block in the function blocks ordering. If 00390 /// it is the end, returns NULL. 00391 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) { 00392 MachineFunction::iterator I = BB; 00393 MachineFunction::iterator E = BB->getParent()->end(); 00394 if (++I == E) 00395 return NULL; 00396 return I; 00397 } 00398 00399 /// ValidSimple - Returns true if the 'true' block (along with its 00400 /// predecessor) forms a valid simple shape for ifcvt. It also returns the 00401 /// number of instructions that the ifcvt would need to duplicate if performed 00402 /// in Dups. 00403 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const { 00404 Dups = 0; 00405 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 00406 return false; 00407 00408 if (TrueBBI.IsBrAnalyzable) 00409 return false; 00410 00411 if (TrueBBI.BB->pred_size() > 1) { 00412 if (TrueBBI.CannotBeCopied || 00413 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit()) 00414 return false; 00415 Dups = TrueBBI.NonPredSize; 00416 } 00417 00418 return true; 00419 } 00420 00421 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along 00422 /// with their common predecessor) forms a valid triangle shape for ifcvt. 00423 /// If 'FalseBranch' is true, it checks if 'true' block's false branch 00424 /// branches to the false branch rather than the other way around. It also 00425 /// returns the number of instructions that the ifcvt would need to duplicate 00426 /// if performed in 'Dups'. 00427 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 00428 bool FalseBranch, unsigned &Dups) const { 00429 Dups = 0; 00430 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 00431 return false; 00432 00433 if (TrueBBI.BB->pred_size() > 1) { 00434 if (TrueBBI.CannotBeCopied) 00435 return false; 00436 00437 unsigned Size = TrueBBI.NonPredSize; 00438 if (TrueBBI.IsBrAnalyzable) { 00439 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty()) 00440 // End with an unconditional branch. It will be removed. 00441 --Size; 00442 else { 00443 MachineBasicBlock *FExit = FalseBranch 00444 ? TrueBBI.TrueBB : TrueBBI.FalseBB; 00445 if (FExit) 00446 // Require a conditional branch 00447 ++Size; 00448 } 00449 } 00450 if (Size > TLI->getIfCvtDupBlockSizeLimit()) 00451 return false; 00452 Dups = Size; 00453 } 00454 00455 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB; 00456 if (!TExit && blockAlwaysFallThrough(TrueBBI)) { 00457 MachineFunction::iterator I = TrueBBI.BB; 00458 if (++I == TrueBBI.BB->getParent()->end()) 00459 return false; 00460 TExit = I; 00461 } 00462 return TExit && TExit == FalseBBI.BB; 00463 } 00464 00465 static 00466 MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB, 00467 const TargetInstrInfo *TII) { 00468 MachineBasicBlock::iterator I = BB->end(); 00469 while (I != BB->begin()) { 00470 --I; 00471 if (!I->getDesc().isBranch()) 00472 break; 00473 } 00474 return I; 00475 } 00476 00477 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along 00478 /// with their common predecessor) forms a valid diamond shape for ifcvt. 00479 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 00480 unsigned &Dups1, unsigned &Dups2) const { 00481 Dups1 = Dups2 = 0; 00482 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone || 00483 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone) 00484 return false; 00485 00486 MachineBasicBlock *TT = TrueBBI.TrueBB; 00487 MachineBasicBlock *FT = FalseBBI.TrueBB; 00488 00489 if (!TT && blockAlwaysFallThrough(TrueBBI)) 00490 TT = getNextBlock(TrueBBI.BB); 00491 if (!FT && blockAlwaysFallThrough(FalseBBI)) 00492 FT = getNextBlock(FalseBBI.BB); 00493 if (TT != FT) 00494 return false; 00495 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable)) 00496 return false; 00497 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) 00498 return false; 00499 00500 // FIXME: Allow true block to have an early exit? 00501 if (TrueBBI.FalseBB || FalseBBI.FalseBB || 00502 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)) 00503 return false; 00504 00505 MachineBasicBlock::iterator TI = TrueBBI.BB->begin(); 00506 MachineBasicBlock::iterator FI = FalseBBI.BB->begin(); 00507 while (TI != TrueBBI.BB->end() && FI != FalseBBI.BB->end()) { 00508 if (!TI->isIdenticalTo(FI)) 00509 break; 00510 ++Dups1; 00511 ++TI; 00512 ++FI; 00513 } 00514 00515 TI = firstNonBranchInst(TrueBBI.BB, TII); 00516 FI = firstNonBranchInst(FalseBBI.BB, TII); 00517 while (TI != TrueBBI.BB->begin() && FI != FalseBBI.BB->begin()) { 00518 if (!TI->isIdenticalTo(FI)) 00519 break; 00520 ++Dups2; 00521 --TI; 00522 --FI; 00523 } 00524 00525 return true; 00526 } 00527 00528 /// ScanInstructions - Scan all the instructions in the block to determine if 00529 /// the block is predicable. In most cases, that means all the instructions 00530 /// in the block are isPredicable(). Also checks if the block contains any 00531 /// instruction which can clobber a predicate (e.g. condition code register). 00532 /// If so, the block is not predicable unless it's the last instruction. 00533 void IfConverter::ScanInstructions(BBInfo &BBI) { 00534 if (BBI.IsDone) 00535 return; 00536 00537 bool AlreadyPredicated = BBI.Predicate.size() > 0; 00538 // First analyze the end of BB branches. 00539 BBI.TrueBB = BBI.FalseBB = NULL; 00540 BBI.BrCond.clear(); 00541 BBI.IsBrAnalyzable = 00542 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond); 00543 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL; 00544 00545 if (BBI.BrCond.size()) { 00546 // No false branch. This BB must end with a conditional branch and a 00547 // fallthrough. 00548 if (!BBI.FalseBB) 00549 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB); 00550 assert(BBI.FalseBB && "Expected to find the fallthrough block!"); 00551 } 00552 00553 // Then scan all the instructions. 00554 BBI.NonPredSize = 0; 00555 BBI.ClobbersPred = false; 00556 bool SeenCondBr = false; 00557 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end(); 00558 I != E; ++I) { 00559 const TargetInstrDesc &TID = I->getDesc(); 00560 if (TID.isNotDuplicable()) 00561 BBI.CannotBeCopied = true; 00562 00563 bool isPredicated = TII->isPredicated(I); 00564 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch(); 00565 00566 if (!isCondBr) { 00567 if (!isPredicated) 00568 BBI.NonPredSize++; 00569 else if (!AlreadyPredicated) { 00570 // FIXME: This instruction is already predicated before the 00571 // if-conversion pass. It's probably something like a conditional move. 00572 // Mark this block unpredicable for now. 00573 BBI.IsUnpredicable = true; 00574 return; 00575 } 00576 00577 } 00578 00579 if (BBI.ClobbersPred && !isPredicated) { 00580 // Predicate modification instruction should end the block (except for 00581 // already predicated instructions and end of block branches). 00582 if (isCondBr) { 00583 SeenCondBr = true; 00584 00585 // Conditional branches is not predicable. But it may be eliminated. 00586 continue; 00587 } 00588 00589 // Predicate may have been modified, the subsequent (currently) 00590 // unpredicated instructions cannot be correctly predicated. 00591 BBI.IsUnpredicable = true; 00592 return; 00593 } 00594 00595 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are 00596 // still potentially predicable. 00597 std::vector<MachineOperand> PredDefs; 00598 if (TII->DefinesPredicate(I, PredDefs)) 00599 BBI.ClobbersPred = true; 00600 00601 if (!TID.isPredicable()) { 00602 BBI.IsUnpredicable = true; 00603 return; 00604 } 00605 } 00606 } 00607 00608 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be 00609 /// predicated by the specified predicate. 00610 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI, 00611 SmallVectorImpl<MachineOperand> &Pred, 00612 bool isTriangle, bool RevBranch) { 00613 // If the block is dead or unpredicable, then it cannot be predicated. 00614 if (BBI.IsDone || BBI.IsUnpredicable) 00615 return false; 00616 00617 // If it is already predicated, check if its predicate subsumes the new 00618 // predicate. 00619 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred)) 00620 return false; 00621 00622 if (BBI.BrCond.size()) { 00623 if (!isTriangle) 00624 return false; 00625 00626 // Test predicate subsumsion. 00627 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end()); 00628 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 00629 if (RevBranch) { 00630 if (TII->ReverseBranchCondition(Cond)) 00631 return false; 00632 } 00633 if (TII->ReverseBranchCondition(RevPred) || 00634 !TII->SubsumesPredicate(Cond, RevPred)) 00635 return false; 00636 } 00637 00638 return true; 00639 } 00640 00641 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from 00642 /// the specified block. Record its successors and whether it looks like an 00643 /// if-conversion candidate. 00644 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB, 00645 std::vector<IfcvtToken*> &Tokens) { 00646 BBInfo &BBI = BBAnalysis[BB->getNumber()]; 00647 00648 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) 00649 return BBI; 00650 00651 BBI.BB = BB; 00652 BBI.IsBeingAnalyzed = true; 00653 00654 ScanInstructions(BBI); 00655 00656 // Unanalyable or ends with fallthrough or unconditional branch. 00657 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) { 00658 BBI.IsBeingAnalyzed = false; 00659 BBI.IsAnalyzed = true; 00660 return BBI; 00661 } 00662 00663 // Do not ifcvt if either path is a back edge to the entry block. 00664 if (BBI.TrueBB == BB || BBI.FalseBB == BB) { 00665 BBI.IsBeingAnalyzed = false; 00666 BBI.IsAnalyzed = true; 00667 return BBI; 00668 } 00669 00670 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens); 00671 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens); 00672 00673 if (TrueBBI.IsDone && FalseBBI.IsDone) { 00674 BBI.IsBeingAnalyzed = false; 00675 BBI.IsAnalyzed = true; 00676 return BBI; 00677 } 00678 00679 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 00680 bool CanRevCond = !TII->ReverseBranchCondition(RevCond); 00681 00682 unsigned Dups = 0; 00683 unsigned Dups2 = 0; 00684 bool TNeedSub = TrueBBI.Predicate.size() > 0; 00685 bool FNeedSub = FalseBBI.Predicate.size() > 0; 00686 bool Enqueued = false; 00687 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) && 00688 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) && 00689 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) && 00690 FeasibilityAnalysis(TrueBBI, BBI.BrCond) && 00691 FeasibilityAnalysis(FalseBBI, RevCond)) { 00692 // Diamond: 00693 // EBB 00694 // / \_ 00695 // | | 00696 // TBB FBB 00697 // \ / 00698 // TailBB 00699 // Note TailBB can be empty. 00700 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups, 00701 Dups2)); 00702 Enqueued = true; 00703 } 00704 00705 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) && 00706 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) && 00707 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) { 00708 // Triangle: 00709 // EBB 00710 // | \_ 00711 // | | 00712 // | TBB 00713 // | / 00714 // FBB 00715 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups)); 00716 Enqueued = true; 00717 } 00718 00719 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) && 00720 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) && 00721 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) { 00722 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups)); 00723 Enqueued = true; 00724 } 00725 00726 if (ValidSimple(TrueBBI, Dups) && 00727 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) && 00728 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) { 00729 // Simple (split, no rejoin): 00730 // EBB 00731 // | \_ 00732 // | | 00733 // | TBB---> exit 00734 // | 00735 // FBB 00736 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups)); 00737 Enqueued = true; 00738 } 00739 00740 if (CanRevCond) { 00741 // Try the other path... 00742 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) && 00743 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) && 00744 FeasibilityAnalysis(FalseBBI, RevCond, true)) { 00745 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups)); 00746 Enqueued = true; 00747 } 00748 00749 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) && 00750 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) && 00751 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) { 00752 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups)); 00753 Enqueued = true; 00754 } 00755 00756 if (ValidSimple(FalseBBI, Dups) && 00757 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) && 00758 FeasibilityAnalysis(FalseBBI, RevCond)) { 00759 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups)); 00760 Enqueued = true; 00761 } 00762 } 00763 00764 BBI.IsEnqueued = Enqueued; 00765 BBI.IsBeingAnalyzed = false; 00766 BBI.IsAnalyzed = true; 00767 return BBI; 00768 } 00769 00770 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion 00771 /// candidates. It returns true if any CFG restructuring is done to expose more 00772 /// if-conversion opportunities. 00773 bool IfConverter::AnalyzeBlocks(MachineFunction &MF, 00774 std::vector<IfcvtToken*> &Tokens) { 00775 bool Change = false; 00776 std::set<MachineBasicBlock*> Visited; 00777 for (unsigned i = 0, e = Roots.size(); i != e; ++i) { 00778 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited), 00779 E = idf_ext_end(Roots[i], Visited); I != E; ++I) { 00780 MachineBasicBlock *BB = *I; 00781 AnalyzeBlock(BB, Tokens); 00782 } 00783 } 00784 00785 // Sort to favor more complex ifcvt scheme. 00786 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp); 00787 00788 return Change; 00789 } 00790 00791 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or 00792 /// that all the intervening blocks are empty (given BB can fall through to its 00793 /// next block). 00794 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) { 00795 MachineFunction::iterator I = BB; 00796 MachineFunction::iterator TI = ToBB; 00797 MachineFunction::iterator E = BB->getParent()->end(); 00798 while (++I != TI) 00799 if (I == E || !I->empty()) 00800 return false; 00801 return true; 00802 } 00803 00804 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed 00805 /// to determine if it can be if-converted. If predecessor is already enqueued, 00806 /// dequeue it! 00807 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) { 00808 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(), 00809 E = BB->pred_end(); PI != E; ++PI) { 00810 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()]; 00811 if (PBBI.IsDone || PBBI.BB == BB) 00812 continue; 00813 PBBI.IsAnalyzed = false; 00814 PBBI.IsEnqueued = false; 00815 } 00816 } 00817 00818 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB. 00819 /// 00820 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB, 00821 const TargetInstrInfo *TII) { 00822 SmallVector<MachineOperand, 0> NoCond; 00823 TII->InsertBranch(*BB, ToBB, NULL, NoCond); 00824 } 00825 00826 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer 00827 /// successors. 00828 void IfConverter::RemoveExtraEdges(BBInfo &BBI) { 00829 MachineBasicBlock *TBB = NULL, *FBB = NULL; 00830 SmallVector<MachineOperand, 4> Cond; 00831 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond)) 00832 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty()); 00833 } 00834 00835 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG. 00836 /// 00837 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) { 00838 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 00839 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 00840 BBInfo *CvtBBI = &TrueBBI; 00841 BBInfo *NextBBI = &FalseBBI; 00842 00843 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 00844 if (Kind == ICSimpleFalse) 00845 std::swap(CvtBBI, NextBBI); 00846 00847 if (CvtBBI->IsDone || 00848 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 00849 // Something has changed. It's no longer safe to predicate this block. 00850 BBI.IsAnalyzed = false; 00851 CvtBBI->IsAnalyzed = false; 00852 return false; 00853 } 00854 00855 if (Kind == ICSimpleFalse) 00856 if (TII->ReverseBranchCondition(Cond)) 00857 assert(false && "Unable to reverse branch condition!"); 00858 00859 if (CvtBBI->BB->pred_size() > 1) { 00860 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 00861 // Copy instructions in the true block, predicate them add them to 00862 // the entry block. 00863 CopyAndPredicateBlock(BBI, *CvtBBI, Cond); 00864 } else { 00865 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 00866 00867 // Merge converted block into entry block. 00868 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 00869 MergeBlocks(BBI, *CvtBBI); 00870 } 00871 00872 bool IterIfcvt = true; 00873 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) { 00874 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 00875 BBI.HasFallThrough = false; 00876 // Now ifcvt'd block will look like this: 00877 // BB: 00878 // ... 00879 // t, f = cmp 00880 // if t op 00881 // b BBf 00882 // 00883 // We cannot further ifcvt this block because the unconditional branch 00884 // will have to be predicated on the new condition, that will not be 00885 // available if cmp executes. 00886 IterIfcvt = false; 00887 } 00888 00889 RemoveExtraEdges(BBI); 00890 00891 // Update block info. BB can be iteratively if-converted. 00892 if (!IterIfcvt) 00893 BBI.IsDone = true; 00894 InvalidatePreds(BBI.BB); 00895 CvtBBI->IsDone = true; 00896 00897 // FIXME: Must maintain LiveIns. 00898 return true; 00899 } 00900 00901 /// IfConvertTriangle - If convert a triangle sub-CFG. 00902 /// 00903 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) { 00904 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 00905 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 00906 BBInfo *CvtBBI = &TrueBBI; 00907 BBInfo *NextBBI = &FalseBBI; 00908 00909 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 00910 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 00911 std::swap(CvtBBI, NextBBI); 00912 00913 if (CvtBBI->IsDone || 00914 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 00915 // Something has changed. It's no longer safe to predicate this block. 00916 BBI.IsAnalyzed = false; 00917 CvtBBI->IsAnalyzed = false; 00918 return false; 00919 } 00920 00921 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 00922 if (TII->ReverseBranchCondition(Cond)) 00923 assert(false && "Unable to reverse branch condition!"); 00924 00925 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) { 00926 if (ReverseBranchCondition(*CvtBBI)) { 00927 // BB has been changed, modify its predecessors (except for this 00928 // one) so they don't get ifcvt'ed based on bad intel. 00929 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(), 00930 E = CvtBBI->BB->pred_end(); PI != E; ++PI) { 00931 MachineBasicBlock *PBB = *PI; 00932 if (PBB == BBI.BB) 00933 continue; 00934 BBInfo &PBBI = BBAnalysis[PBB->getNumber()]; 00935 if (PBBI.IsEnqueued) { 00936 PBBI.IsAnalyzed = false; 00937 PBBI.IsEnqueued = false; 00938 } 00939 } 00940 } 00941 } 00942 00943 bool HasEarlyExit = CvtBBI->FalseBB != NULL; 00944 bool DupBB = CvtBBI->BB->pred_size() > 1; 00945 if (DupBB) { 00946 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 00947 // Copy instructions in the true block, predicate them add them to 00948 // the entry block. 00949 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true); 00950 } else { 00951 // Predicate the 'true' block after removing its branch. 00952 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB); 00953 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 00954 } 00955 00956 if (!DupBB) { 00957 // Now merge the entry of the triangle with the true block. 00958 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 00959 MergeBlocks(BBI, *CvtBBI); 00960 } 00961 00962 // If 'true' block has a 'false' successor, add an exit branch to it. 00963 if (HasEarlyExit) { 00964 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(), 00965 CvtBBI->BrCond.end()); 00966 if (TII->ReverseBranchCondition(RevCond)) 00967 assert(false && "Unable to reverse branch condition!"); 00968 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond); 00969 BBI.BB->addSuccessor(CvtBBI->FalseBB); 00970 } 00971 00972 // Merge in the 'false' block if the 'false' block has no other 00973 // predecessors. Otherwise, add a unconditional branch from to 'false'. 00974 bool FalseBBDead = false; 00975 bool IterIfcvt = true; 00976 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB); 00977 if (!isFallThrough) { 00978 // Only merge them if the true block does not fallthrough to the false 00979 // block. By not merging them, we make it possible to iteratively 00980 // ifcvt the blocks. 00981 if (!HasEarlyExit && 00982 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) { 00983 MergeBlocks(BBI, *NextBBI); 00984 FalseBBDead = true; 00985 } else { 00986 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 00987 BBI.HasFallThrough = false; 00988 } 00989 // Mixed predicated and unpredicated code. This cannot be iteratively 00990 // predicated. 00991 IterIfcvt = false; 00992 } 00993 00994 RemoveExtraEdges(BBI); 00995 00996 // Update block info. BB can be iteratively if-converted. 00997 if (!IterIfcvt) 00998 BBI.IsDone = true; 00999 InvalidatePreds(BBI.BB); 01000 CvtBBI->IsDone = true; 01001 if (FalseBBDead) 01002 NextBBI->IsDone = true; 01003 01004 // FIXME: Must maintain LiveIns. 01005 return true; 01006 } 01007 01008 /// IfConvertDiamond - If convert a diamond sub-CFG. 01009 /// 01010 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 01011 unsigned NumDups1, unsigned NumDups2) { 01012 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 01013 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 01014 MachineBasicBlock *TailBB = TrueBBI.TrueBB; 01015 // True block must fall through or ended with unanalyzable terminator. 01016 if (!TailBB) { 01017 if (blockAlwaysFallThrough(TrueBBI)) 01018 TailBB = FalseBBI.TrueBB; 01019 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!"); 01020 } 01021 01022 if (TrueBBI.IsDone || FalseBBI.IsDone || 01023 TrueBBI.BB->pred_size() > 1 || 01024 FalseBBI.BB->pred_size() > 1) { 01025 // Something has changed. It's no longer safe to predicate these blocks. 01026 BBI.IsAnalyzed = false; 01027 TrueBBI.IsAnalyzed = false; 01028 FalseBBI.IsAnalyzed = false; 01029 return false; 01030 } 01031 01032 // Merge the 'true' and 'false' blocks by copying the instructions 01033 // from the 'false' block to the 'true' block. That is, unless the true 01034 // block would clobber the predicate, in that case, do the opposite. 01035 BBInfo *BBI1 = &TrueBBI; 01036 BBInfo *BBI2 = &FalseBBI; 01037 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 01038 if (TII->ReverseBranchCondition(RevCond)) 01039 assert(false && "Unable to reverse branch condition!"); 01040 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond; 01041 SmallVector<MachineOperand, 4> *Cond2 = &RevCond; 01042 01043 // Figure out the more profitable ordering. 01044 bool DoSwap = false; 01045 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred) 01046 DoSwap = true; 01047 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) { 01048 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize) 01049 DoSwap = true; 01050 } 01051 if (DoSwap) { 01052 std::swap(BBI1, BBI2); 01053 std::swap(Cond1, Cond2); 01054 } 01055 01056 // Remove the conditional branch from entry to the blocks. 01057 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 01058 01059 // Remove the duplicated instructions at the beginnings of both paths. 01060 MachineBasicBlock::iterator DI1 = BBI1->BB->begin(); 01061 MachineBasicBlock::iterator DI2 = BBI2->BB->begin(); 01062 BBI1->NonPredSize -= NumDups1; 01063 BBI2->NonPredSize -= NumDups1; 01064 while (NumDups1 != 0) { 01065 ++DI1; 01066 ++DI2; 01067 --NumDups1; 01068 } 01069 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1); 01070 BBI2->BB->erase(BBI2->BB->begin(), DI2); 01071 01072 // Predicate the 'true' block after removing its branch. 01073 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB); 01074 DI1 = BBI1->BB->end(); 01075 for (unsigned i = 0; i != NumDups2; ++i) 01076 --DI1; 01077 BBI1->BB->erase(DI1, BBI1->BB->end()); 01078 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1); 01079 01080 // Predicate the 'false' block. 01081 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB); 01082 DI2 = BBI2->BB->end(); 01083 while (NumDups2 != 0) { 01084 --DI2; 01085 --NumDups2; 01086 } 01087 PredicateBlock(*BBI2, DI2, *Cond2); 01088 01089 // Merge the true block into the entry of the diamond. 01090 MergeBlocks(BBI, *BBI1); 01091 MergeBlocks(BBI, *BBI2); 01092 01093 // If the if-converted block fallthrough or unconditionally branch into the 01094 // tail block, and the tail block does not have other predecessors, then 01095 // fold the tail block in as well. Otherwise, unless it falls through to the 01096 // tail, add a unconditional branch to it. 01097 if (TailBB) { 01098 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()]; 01099 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) { 01100 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 01101 MergeBlocks(BBI, TailBBI); 01102 TailBBI.IsDone = true; 01103 } else { 01104 InsertUncondBranch(BBI.BB, TailBB, TII); 01105 BBI.HasFallThrough = false; 01106 } 01107 } 01108 01109 RemoveExtraEdges(BBI); 01110 01111 // Update block info. 01112 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true; 01113 InvalidatePreds(BBI.BB); 01114 01115 // FIXME: Must maintain LiveIns. 01116 return true; 01117 } 01118 01119 /// PredicateBlock - Predicate instructions from the start of the block to the 01120 /// specified end with the specified condition. 01121 void IfConverter::PredicateBlock(BBInfo &BBI, 01122 MachineBasicBlock::iterator E, 01123 SmallVectorImpl<MachineOperand> &Cond) { 01124 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) { 01125 if (TII->isPredicated(I)) 01126 continue; 01127 if (!TII->PredicateInstruction(I, Cond)) { 01128 cerr << "Unable to predicate " << *I << "!\n"; 01129 abort(); 01130 } 01131 } 01132 01133 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate)); 01134 01135 BBI.IsAnalyzed = false; 01136 BBI.NonPredSize = 0; 01137 01138 NumIfConvBBs++; 01139 } 01140 01141 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to 01142 /// the destination block. Skip end of block branches if IgnoreBr is true. 01143 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 01144 SmallVectorImpl<MachineOperand> &Cond, 01145 bool IgnoreBr) { 01146 MachineFunction &MF = *ToBBI.BB->getParent(); 01147 01148 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(), 01149 E = FromBBI.BB->end(); I != E; ++I) { 01150 const TargetInstrDesc &TID = I->getDesc(); 01151 bool isPredicated = TII->isPredicated(I); 01152 // Do not copy the end of the block branches. 01153 if (IgnoreBr && !isPredicated && TID.isBranch()) 01154 break; 01155 01156 MachineInstr *MI = MF.CloneMachineInstr(I); 01157 ToBBI.BB->insert(ToBBI.BB->end(), MI); 01158 ToBBI.NonPredSize++; 01159 01160 if (!isPredicated) 01161 if (!TII->PredicateInstruction(MI, Cond)) { 01162 cerr << "Unable to predicate " << *MI << "!\n"; 01163 abort(); 01164 } 01165 } 01166 01167 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(), 01168 FromBBI.BB->succ_end()); 01169 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 01170 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL; 01171 01172 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 01173 MachineBasicBlock *Succ = Succs[i]; 01174 // Fallthrough edge can't be transferred. 01175 if (Succ == FallThrough) 01176 continue; 01177 if (!ToBBI.BB->isSuccessor(Succ)) 01178 ToBBI.BB->addSuccessor(Succ); 01179 } 01180 01181 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(), 01182 std::back_inserter(ToBBI.Predicate)); 01183 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate)); 01184 01185 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 01186 ToBBI.IsAnalyzed = false; 01187 01188 NumDupBBs++; 01189 } 01190 01191 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB. 01192 /// 01193 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) { 01194 ToBBI.BB->splice(ToBBI.BB->end(), 01195 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end()); 01196 01197 // Redirect all branches to FromBB to ToBB. 01198 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(), 01199 FromBBI.BB->pred_end()); 01200 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 01201 MachineBasicBlock *Pred = Preds[i]; 01202 if (Pred == ToBBI.BB) 01203 continue; 01204 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB); 01205 } 01206 01207 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(), 01208 FromBBI.BB->succ_end()); 01209 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 01210 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL; 01211 01212 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 01213 MachineBasicBlock *Succ = Succs[i]; 01214 // Fallthrough edge can't be transferred. 01215 if (Succ == FallThrough) 01216 continue; 01217 FromBBI.BB->removeSuccessor(Succ); 01218 if (!ToBBI.BB->isSuccessor(Succ)) 01219 ToBBI.BB->addSuccessor(Succ); 01220 } 01221 01222 // Now FromBBI always fall through to the next block! 01223 if (NBB && !FromBBI.BB->isSuccessor(NBB)) 01224 FromBBI.BB->addSuccessor(NBB); 01225 01226 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(), 01227 std::back_inserter(ToBBI.Predicate)); 01228 FromBBI.Predicate.clear(); 01229 01230 ToBBI.NonPredSize += FromBBI.NonPredSize; 01231 FromBBI.NonPredSize = 0; 01232 01233 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 01234 ToBBI.HasFallThrough = FromBBI.HasFallThrough; 01235 ToBBI.IsAnalyzed = false; 01236 FromBBI.IsAnalyzed = false; 01237 }