IfConversion.cpp revision 4eb66e6a71dd207cf94332c93804265bfef49e03
1//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the machine instruction level if-conversion pass. 11// 12//===----------------------------------------------------------------------===// 13 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" 26#include "llvm/ADT/STLExtras.h" 27using namespace llvm; 28 29// Hidden options for help debugging. 30static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden); 31static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden); 32static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden); 33static cl::opt<bool> DisableSimple("disable-ifcvt-simple", 34 cl::init(false), cl::Hidden); 35static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false", 36 cl::init(false), cl::Hidden); 37static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle", 38 cl::init(false), cl::Hidden); 39static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev", 40 cl::init(false), cl::Hidden); 41static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false", 42 cl::init(false), cl::Hidden); 43static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev", 44 cl::init(false), cl::Hidden); 45static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond", 46 cl::init(false), cl::Hidden); 47 48STATISTIC(NumSimple, "Number of simple if-conversions performed"); 49STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed"); 50STATISTIC(NumTriangle, "Number of triangle if-conversions performed"); 51STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed"); 52STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed"); 53STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed"); 54STATISTIC(NumDiamonds, "Number of diamond if-conversions performed"); 55STATISTIC(NumIfConvBBs, "Number of if-converted blocks"); 56STATISTIC(NumDupBBs, "Number of duplicated blocks"); 57 58namespace { 59 class VISIBILITY_HIDDEN IfConverter : public MachineFunctionPass { 60 enum IfcvtKind { 61 ICNotClassfied, // BB data valid, but not classified. 62 ICSimpleFalse, // Same as ICSimple, but on the false path. 63 ICSimple, // BB is entry of an one split, no rejoin sub-CFG. 64 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition. 65 ICTriangleRev, // Same as ICTriangle, but true path rev condition. 66 ICTriangleFalse, // Same as ICTriangle, but on the false path. 67 ICTriangle, // BB is entry of a triangle sub-CFG. 68 ICDiamond // BB is entry of a diamond sub-CFG. 69 }; 70 71 /// BBInfo - One per MachineBasicBlock, this is used to cache the result 72 /// if-conversion feasibility analysis. This includes results from 73 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its 74 /// classification, and common tail block of its successors (if it's a 75 /// diamond shape), its size, whether it's predicable, and whether any 76 /// instruction can clobber the 'would-be' predicate. 77 /// 78 /// IsDone - True if BB is not to be considered for ifcvt. 79 /// IsBeingAnalyzed - True if BB is currently being analyzed. 80 /// IsAnalyzed - True if BB has been analyzed (info is still valid). 81 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed. 82 /// IsBrAnalyzable - True if AnalyzeBranch() returns false. 83 /// HasFallThrough - True if BB may fallthrough to the following BB. 84 /// IsUnpredicable - True if BB is known to be unpredicable. 85 /// ClobbersPred - True if BB could modify predicates (e.g. has 86 /// cmp, call, etc.) 87 /// NonPredSize - Number of non-predicated instructions. 88 /// BB - Corresponding MachineBasicBlock. 89 /// TrueBB / FalseBB- See AnalyzeBranch(). 90 /// BrCond - Conditions for end of block conditional branches. 91 /// Predicate - Predicate used in the BB. 92 struct BBInfo { 93 bool IsDone : 1; 94 bool IsBeingAnalyzed : 1; 95 bool IsAnalyzed : 1; 96 bool IsEnqueued : 1; 97 bool IsBrAnalyzable : 1; 98 bool HasFallThrough : 1; 99 bool IsUnpredicable : 1; 100 bool CannotBeCopied : 1; 101 bool ClobbersPred : 1; 102 unsigned NonPredSize; 103 MachineBasicBlock *BB; 104 MachineBasicBlock *TrueBB; 105 MachineBasicBlock *FalseBB; 106 SmallVector<MachineOperand, 4> BrCond; 107 SmallVector<MachineOperand, 4> Predicate; 108 BBInfo() : IsDone(false), IsBeingAnalyzed(false), 109 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false), 110 HasFallThrough(false), IsUnpredicable(false), 111 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0), 112 BB(0), TrueBB(0), FalseBB(0) {} 113 }; 114 115 /// IfcvtToken - Record information about pending if-conversions to attemp: 116 /// BBI - Corresponding BBInfo. 117 /// Kind - Type of block. See IfcvtKind. 118 /// NeedSubsumption - True if the to-be-predicated BB has already been 119 /// predicated. 120 /// NumDups - Number of instructions that would be duplicated due 121 /// to this if-conversion. (For diamonds, the number of 122 /// identical instructions at the beginnings of both 123 /// paths). 124 /// NumDups2 - For diamonds, the number of identical instructions 125 /// at the ends of both paths. 126 struct IfcvtToken { 127 BBInfo &BBI; 128 IfcvtKind Kind; 129 bool NeedSubsumption; 130 unsigned NumDups; 131 unsigned NumDups2; 132 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0) 133 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {} 134 }; 135 136 /// Roots - Basic blocks that do not have successors. These are the starting 137 /// points of Graph traversal. 138 std::vector<MachineBasicBlock*> Roots; 139 140 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by 141 /// basic block number. 142 std::vector<BBInfo> BBAnalysis; 143 144 const TargetLowering *TLI; 145 const TargetInstrInfo *TII; 146 bool MadeChange; 147 public: 148 static char ID; 149 IfConverter() : MachineFunctionPass(&ID) {} 150 151 virtual bool runOnMachineFunction(MachineFunction &MF); 152 virtual const char *getPassName() const { return "If Converter"; } 153 154 private: 155 bool ReverseBranchCondition(BBInfo &BBI); 156 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const; 157 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 158 bool FalseBranch, unsigned &Dups) const; 159 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 160 unsigned &Dups1, unsigned &Dups2) const; 161 void ScanInstructions(BBInfo &BBI); 162 BBInfo &AnalyzeBlock(MachineBasicBlock *BB, 163 std::vector<IfcvtToken*> &Tokens); 164 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond, 165 bool isTriangle = false, bool RevBranch = false); 166 bool AnalyzeBlocks(MachineFunction &MF, 167 std::vector<IfcvtToken*> &Tokens); 168 void InvalidatePreds(MachineBasicBlock *BB); 169 void RemoveExtraEdges(BBInfo &BBI); 170 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind); 171 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind); 172 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 173 unsigned NumDups1, unsigned NumDups2); 174 void PredicateBlock(BBInfo &BBI, 175 MachineBasicBlock::iterator E, 176 SmallVectorImpl<MachineOperand> &Cond); 177 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 178 SmallVectorImpl<MachineOperand> &Cond, 179 bool IgnoreBr = false); 180 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI); 181 182 bool MeetIfcvtSizeLimit(unsigned Size) const { 183 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit(); 184 } 185 186 // blockAlwaysFallThrough - Block ends without a terminator. 187 bool blockAlwaysFallThrough(BBInfo &BBI) const { 188 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL; 189 } 190 191 // IfcvtTokenCmp - Used to sort if-conversion candidates. 192 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) { 193 int Incr1 = (C1->Kind == ICDiamond) 194 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups; 195 int Incr2 = (C2->Kind == ICDiamond) 196 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups; 197 if (Incr1 > Incr2) 198 return true; 199 else if (Incr1 == Incr2) { 200 // Favors subsumption. 201 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true) 202 return true; 203 else if (C1->NeedSubsumption == C2->NeedSubsumption) { 204 // Favors diamond over triangle, etc. 205 if ((unsigned)C1->Kind < (unsigned)C2->Kind) 206 return true; 207 else if (C1->Kind == C2->Kind) 208 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber(); 209 } 210 } 211 return false; 212 } 213 }; 214 215 char IfConverter::ID = 0; 216} 217 218static RegisterPass<IfConverter> 219X("if-converter", "If Converter"); 220 221FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); } 222 223bool IfConverter::runOnMachineFunction(MachineFunction &MF) { 224 TLI = MF.getTarget().getTargetLowering(); 225 TII = MF.getTarget().getInstrInfo(); 226 if (!TII) return false; 227 228 static int FnNum = -1; 229 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'" 230 << MF.getFunction()->getName() << "\'"; 231 232 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) { 233 DOUT << " skipped\n"; 234 return false; 235 } 236 DOUT << "\n"; 237 238 MF.RenumberBlocks(); 239 BBAnalysis.resize(MF.getNumBlockIDs()); 240 241 // Look for root nodes, i.e. blocks without successors. 242 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) 243 if (I->succ_empty()) 244 Roots.push_back(I); 245 246 std::vector<IfcvtToken*> Tokens; 247 MadeChange = false; 248 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + 249 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds; 250 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) { 251 // Do an initial analysis for each basic block and find all the potential 252 // candidates to perform if-conversion. 253 bool Change = AnalyzeBlocks(MF, Tokens); 254 while (!Tokens.empty()) { 255 IfcvtToken *Token = Tokens.back(); 256 Tokens.pop_back(); 257 BBInfo &BBI = Token->BBI; 258 IfcvtKind Kind = Token->Kind; 259 unsigned NumDups = Token->NumDups; 260 unsigned NumDups2 = Token->NumDups2; 261 262 delete Token; 263 264 // If the block has been evicted out of the queue or it has already been 265 // marked dead (due to it being predicated), then skip it. 266 if (BBI.IsDone) 267 BBI.IsEnqueued = false; 268 if (!BBI.IsEnqueued) 269 continue; 270 271 BBI.IsEnqueued = false; 272 273 bool RetVal = false; 274 switch (Kind) { 275 default: assert(false && "Unexpected!"); 276 break; 277 case ICSimple: 278 case ICSimpleFalse: { 279 bool isFalse = Kind == ICSimpleFalse; 280 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break; 281 DOUT << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"") 282 << "): BB#" << BBI.BB->getNumber() << " (" 283 << ((Kind == ICSimpleFalse) 284 ? BBI.FalseBB->getNumber() 285 : BBI.TrueBB->getNumber()) << ") "; 286 RetVal = IfConvertSimple(BBI, Kind); 287 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n"; 288 if (RetVal) { 289 if (isFalse) NumSimpleFalse++; 290 else NumSimple++; 291 } 292 break; 293 } 294 case ICTriangle: 295 case ICTriangleRev: 296 case ICTriangleFalse: 297 case ICTriangleFRev: { 298 bool isFalse = Kind == ICTriangleFalse; 299 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev); 300 if (DisableTriangle && !isFalse && !isRev) break; 301 if (DisableTriangleR && !isFalse && isRev) break; 302 if (DisableTriangleF && isFalse && !isRev) break; 303 if (DisableTriangleFR && isFalse && isRev) break; 304 DOUT << "Ifcvt (Triangle"; 305 if (isFalse) 306 DOUT << " false"; 307 if (isRev) 308 DOUT << " rev"; 309 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:" 310 << BBI.TrueBB->getNumber() << ",F:" 311 << BBI.FalseBB->getNumber() << ") "; 312 RetVal = IfConvertTriangle(BBI, Kind); 313 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n"; 314 if (RetVal) { 315 if (isFalse) { 316 if (isRev) NumTriangleFRev++; 317 else NumTriangleFalse++; 318 } else { 319 if (isRev) NumTriangleRev++; 320 else NumTriangle++; 321 } 322 } 323 break; 324 } 325 case ICDiamond: { 326 if (DisableDiamond) break; 327 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:" 328 << BBI.TrueBB->getNumber() << ",F:" 329 << BBI.FalseBB->getNumber() << ") "; 330 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2); 331 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n"; 332 if (RetVal) NumDiamonds++; 333 break; 334 } 335 } 336 337 Change |= RetVal; 338 339 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev + 340 NumTriangleFalse + NumTriangleFRev + NumDiamonds; 341 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit) 342 break; 343 } 344 345 if (!Change) 346 break; 347 MadeChange |= Change; 348 } 349 350 // Delete tokens in case of early exit. 351 while (!Tokens.empty()) { 352 IfcvtToken *Token = Tokens.back(); 353 Tokens.pop_back(); 354 delete Token; 355 } 356 357 Tokens.clear(); 358 Roots.clear(); 359 BBAnalysis.clear(); 360 361 return MadeChange; 362} 363 364/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given 365/// its 'true' successor. 366static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, 367 MachineBasicBlock *TrueBB) { 368 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 369 E = BB->succ_end(); SI != E; ++SI) { 370 MachineBasicBlock *SuccBB = *SI; 371 if (SuccBB != TrueBB) 372 return SuccBB; 373 } 374 return NULL; 375} 376 377/// ReverseBranchCondition - Reverse the condition of the end of the block 378/// branch. Swap block's 'true' and 'false' successors. 379bool IfConverter::ReverseBranchCondition(BBInfo &BBI) { 380 if (!TII->ReverseBranchCondition(BBI.BrCond)) { 381 TII->RemoveBranch(*BBI.BB); 382 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond); 383 std::swap(BBI.TrueBB, BBI.FalseBB); 384 return true; 385 } 386 return false; 387} 388 389/// getNextBlock - Returns the next block in the function blocks ordering. If 390/// it is the end, returns NULL. 391static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) { 392 MachineFunction::iterator I = BB; 393 MachineFunction::iterator E = BB->getParent()->end(); 394 if (++I == E) 395 return NULL; 396 return I; 397} 398 399/// ValidSimple - Returns true if the 'true' block (along with its 400/// predecessor) forms a valid simple shape for ifcvt. It also returns the 401/// number of instructions that the ifcvt would need to duplicate if performed 402/// in Dups. 403bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const { 404 Dups = 0; 405 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 406 return false; 407 408 if (TrueBBI.IsBrAnalyzable) 409 return false; 410 411 if (TrueBBI.BB->pred_size() > 1) { 412 if (TrueBBI.CannotBeCopied || 413 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit()) 414 return false; 415 Dups = TrueBBI.NonPredSize; 416 } 417 418 return true; 419} 420 421/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along 422/// with their common predecessor) forms a valid triangle shape for ifcvt. 423/// If 'FalseBranch' is true, it checks if 'true' block's false branch 424/// branches to the false branch rather than the other way around. It also 425/// returns the number of instructions that the ifcvt would need to duplicate 426/// if performed in 'Dups'. 427bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 428 bool FalseBranch, unsigned &Dups) const { 429 Dups = 0; 430 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 431 return false; 432 433 if (TrueBBI.BB->pred_size() > 1) { 434 if (TrueBBI.CannotBeCopied) 435 return false; 436 437 unsigned Size = TrueBBI.NonPredSize; 438 if (TrueBBI.IsBrAnalyzable) { 439 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty()) 440 // Ends with an unconditional branch. It will be removed. 441 --Size; 442 else { 443 MachineBasicBlock *FExit = FalseBranch 444 ? TrueBBI.TrueBB : TrueBBI.FalseBB; 445 if (FExit) 446 // Require a conditional branch 447 ++Size; 448 } 449 } 450 if (Size > TLI->getIfCvtDupBlockSizeLimit()) 451 return false; 452 Dups = Size; 453 } 454 455 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB; 456 if (!TExit && blockAlwaysFallThrough(TrueBBI)) { 457 MachineFunction::iterator I = TrueBBI.BB; 458 if (++I == TrueBBI.BB->getParent()->end()) 459 return false; 460 TExit = I; 461 } 462 return TExit && TExit == FalseBBI.BB; 463} 464 465static 466MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB, 467 const TargetInstrInfo *TII) { 468 MachineBasicBlock::iterator I = BB->end(); 469 while (I != BB->begin()) { 470 --I; 471 if (!I->getDesc().isBranch()) 472 break; 473 } 474 return I; 475} 476 477/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along 478/// with their common predecessor) forms a valid diamond shape for ifcvt. 479bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 480 unsigned &Dups1, unsigned &Dups2) const { 481 Dups1 = Dups2 = 0; 482 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone || 483 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone) 484 return false; 485 486 MachineBasicBlock *TT = TrueBBI.TrueBB; 487 MachineBasicBlock *FT = FalseBBI.TrueBB; 488 489 if (!TT && blockAlwaysFallThrough(TrueBBI)) 490 TT = getNextBlock(TrueBBI.BB); 491 if (!FT && blockAlwaysFallThrough(FalseBBI)) 492 FT = getNextBlock(FalseBBI.BB); 493 if (TT != FT) 494 return false; 495 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable)) 496 return false; 497 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) 498 return false; 499 500 // FIXME: Allow true block to have an early exit? 501 if (TrueBBI.FalseBB || FalseBBI.FalseBB || 502 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)) 503 return false; 504 505 MachineBasicBlock::iterator TI = TrueBBI.BB->begin(); 506 MachineBasicBlock::iterator FI = FalseBBI.BB->begin(); 507 while (TI != TrueBBI.BB->end() && FI != FalseBBI.BB->end()) { 508 if (!TI->isIdenticalTo(FI)) 509 break; 510 ++Dups1; 511 ++TI; 512 ++FI; 513 } 514 515 TI = firstNonBranchInst(TrueBBI.BB, TII); 516 FI = firstNonBranchInst(FalseBBI.BB, TII); 517 while (TI != TrueBBI.BB->begin() && FI != FalseBBI.BB->begin()) { 518 if (!TI->isIdenticalTo(FI)) 519 break; 520 ++Dups2; 521 --TI; 522 --FI; 523 } 524 525 return true; 526} 527 528/// ScanInstructions - Scan all the instructions in the block to determine if 529/// the block is predicable. In most cases, that means all the instructions 530/// in the block are isPredicable(). Also checks if the block contains any 531/// instruction which can clobber a predicate (e.g. condition code register). 532/// If so, the block is not predicable unless it's the last instruction. 533void IfConverter::ScanInstructions(BBInfo &BBI) { 534 if (BBI.IsDone) 535 return; 536 537 bool AlreadyPredicated = BBI.Predicate.size() > 0; 538 // First analyze the end of BB branches. 539 BBI.TrueBB = BBI.FalseBB = NULL; 540 BBI.BrCond.clear(); 541 BBI.IsBrAnalyzable = 542 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond); 543 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL; 544 545 if (BBI.BrCond.size()) { 546 // No false branch. This BB must end with a conditional branch and a 547 // fallthrough. 548 if (!BBI.FalseBB) 549 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB); 550 if (!BBI.FalseBB) { 551 // Malformed bcc? True and false blocks are the same? 552 BBI.IsUnpredicable = true; 553 return; 554 } 555 } 556 557 // Then scan all the instructions. 558 BBI.NonPredSize = 0; 559 BBI.ClobbersPred = false; 560 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end(); 561 I != E; ++I) { 562 const TargetInstrDesc &TID = I->getDesc(); 563 if (TID.isNotDuplicable()) 564 BBI.CannotBeCopied = true; 565 566 bool isPredicated = TII->isPredicated(I); 567 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch(); 568 569 if (!isCondBr) { 570 if (!isPredicated) 571 BBI.NonPredSize++; 572 else if (!AlreadyPredicated) { 573 // FIXME: This instruction is already predicated before the 574 // if-conversion pass. It's probably something like a conditional move. 575 // Mark this block unpredicable for now. 576 BBI.IsUnpredicable = true; 577 return; 578 } 579 } 580 581 if (BBI.ClobbersPred && !isPredicated) { 582 // Predicate modification instruction should end the block (except for 583 // already predicated instructions and end of block branches). 584 if (isCondBr) { 585 // A conditional branch is not predicable, but it may be eliminated. 586 continue; 587 } 588 589 // Predicate may have been modified, the subsequent (currently) 590 // unpredicated instructions cannot be correctly predicated. 591 BBI.IsUnpredicable = true; 592 return; 593 } 594 595 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are 596 // still potentially predicable. 597 std::vector<MachineOperand> PredDefs; 598 if (TII->DefinesPredicate(I, PredDefs)) 599 BBI.ClobbersPred = true; 600 601 if (!TID.isPredicable()) { 602 BBI.IsUnpredicable = true; 603 return; 604 } 605 } 606} 607 608/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be 609/// predicated by the specified predicate. 610bool IfConverter::FeasibilityAnalysis(BBInfo &BBI, 611 SmallVectorImpl<MachineOperand> &Pred, 612 bool isTriangle, bool RevBranch) { 613 // If the block is dead or unpredicable, then it cannot be predicated. 614 if (BBI.IsDone || BBI.IsUnpredicable) 615 return false; 616 617 // If it is already predicated, check if its predicate subsumes the new 618 // predicate. 619 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred)) 620 return false; 621 622 if (BBI.BrCond.size()) { 623 if (!isTriangle) 624 return false; 625 626 // Test predicate subsumption. 627 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end()); 628 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 629 if (RevBranch) { 630 if (TII->ReverseBranchCondition(Cond)) 631 return false; 632 } 633 if (TII->ReverseBranchCondition(RevPred) || 634 !TII->SubsumesPredicate(Cond, RevPred)) 635 return false; 636 } 637 638 return true; 639} 640 641/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from 642/// the specified block. Record its successors and whether it looks like an 643/// if-conversion candidate. 644IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB, 645 std::vector<IfcvtToken*> &Tokens) { 646 BBInfo &BBI = BBAnalysis[BB->getNumber()]; 647 648 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) 649 return BBI; 650 651 BBI.BB = BB; 652 BBI.IsBeingAnalyzed = true; 653 654 ScanInstructions(BBI); 655 656 // Unanalyzable or ends with fallthrough or unconditional branch. 657 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) { 658 BBI.IsBeingAnalyzed = false; 659 BBI.IsAnalyzed = true; 660 return BBI; 661 } 662 663 // Do not ifcvt if either path is a back edge to the entry block. 664 if (BBI.TrueBB == BB || BBI.FalseBB == BB) { 665 BBI.IsBeingAnalyzed = false; 666 BBI.IsAnalyzed = true; 667 return BBI; 668 } 669 670 // Do not ifcvt if true and false fallthrough blocks are the same. 671 if (!BBI.FalseBB) { 672 BBI.IsBeingAnalyzed = false; 673 BBI.IsAnalyzed = true; 674 return BBI; 675 } 676 677 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens); 678 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens); 679 680 if (TrueBBI.IsDone && FalseBBI.IsDone) { 681 BBI.IsBeingAnalyzed = false; 682 BBI.IsAnalyzed = true; 683 return BBI; 684 } 685 686 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 687 bool CanRevCond = !TII->ReverseBranchCondition(RevCond); 688 689 unsigned Dups = 0; 690 unsigned Dups2 = 0; 691 bool TNeedSub = TrueBBI.Predicate.size() > 0; 692 bool FNeedSub = FalseBBI.Predicate.size() > 0; 693 bool Enqueued = false; 694 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) && 695 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) && 696 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) && 697 FeasibilityAnalysis(TrueBBI, BBI.BrCond) && 698 FeasibilityAnalysis(FalseBBI, RevCond)) { 699 // Diamond: 700 // EBB 701 // / \_ 702 // | | 703 // TBB FBB 704 // \ / 705 // TailBB 706 // Note TailBB can be empty. 707 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups, 708 Dups2)); 709 Enqueued = true; 710 } 711 712 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) && 713 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) && 714 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) { 715 // Triangle: 716 // EBB 717 // | \_ 718 // | | 719 // | TBB 720 // | / 721 // FBB 722 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups)); 723 Enqueued = true; 724 } 725 726 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) && 727 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) && 728 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) { 729 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups)); 730 Enqueued = true; 731 } 732 733 if (ValidSimple(TrueBBI, Dups) && 734 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) && 735 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) { 736 // Simple (split, no rejoin): 737 // EBB 738 // | \_ 739 // | | 740 // | TBB---> exit 741 // | 742 // FBB 743 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups)); 744 Enqueued = true; 745 } 746 747 if (CanRevCond) { 748 // Try the other path... 749 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) && 750 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) && 751 FeasibilityAnalysis(FalseBBI, RevCond, true)) { 752 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups)); 753 Enqueued = true; 754 } 755 756 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) && 757 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) && 758 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) { 759 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups)); 760 Enqueued = true; 761 } 762 763 if (ValidSimple(FalseBBI, Dups) && 764 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) && 765 FeasibilityAnalysis(FalseBBI, RevCond)) { 766 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups)); 767 Enqueued = true; 768 } 769 } 770 771 BBI.IsEnqueued = Enqueued; 772 BBI.IsBeingAnalyzed = false; 773 BBI.IsAnalyzed = true; 774 return BBI; 775} 776 777/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion 778/// candidates. It returns true if any CFG restructuring is done to expose more 779/// if-conversion opportunities. 780bool IfConverter::AnalyzeBlocks(MachineFunction &MF, 781 std::vector<IfcvtToken*> &Tokens) { 782 bool Change = false; 783 std::set<MachineBasicBlock*> Visited; 784 for (unsigned i = 0, e = Roots.size(); i != e; ++i) { 785 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited), 786 E = idf_ext_end(Roots[i], Visited); I != E; ++I) { 787 MachineBasicBlock *BB = *I; 788 AnalyzeBlock(BB, Tokens); 789 } 790 } 791 792 // Sort to favor more complex ifcvt scheme. 793 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp); 794 795 return Change; 796} 797 798/// canFallThroughTo - Returns true either if ToBB is the next block after BB or 799/// that all the intervening blocks are empty (given BB can fall through to its 800/// next block). 801static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) { 802 MachineFunction::iterator I = BB; 803 MachineFunction::iterator TI = ToBB; 804 MachineFunction::iterator E = BB->getParent()->end(); 805 while (++I != TI) 806 if (I == E || !I->empty()) 807 return false; 808 return true; 809} 810 811/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed 812/// to determine if it can be if-converted. If predecessor is already enqueued, 813/// dequeue it! 814void IfConverter::InvalidatePreds(MachineBasicBlock *BB) { 815 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(), 816 E = BB->pred_end(); PI != E; ++PI) { 817 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()]; 818 if (PBBI.IsDone || PBBI.BB == BB) 819 continue; 820 PBBI.IsAnalyzed = false; 821 PBBI.IsEnqueued = false; 822 } 823} 824 825/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB. 826/// 827static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB, 828 const TargetInstrInfo *TII) { 829 SmallVector<MachineOperand, 0> NoCond; 830 TII->InsertBranch(*BB, ToBB, NULL, NoCond); 831} 832 833/// RemoveExtraEdges - Remove true / false edges if either / both are no longer 834/// successors. 835void IfConverter::RemoveExtraEdges(BBInfo &BBI) { 836 MachineBasicBlock *TBB = NULL, *FBB = NULL; 837 SmallVector<MachineOperand, 4> Cond; 838 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond)) 839 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty()); 840} 841 842/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG. 843/// 844bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) { 845 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 846 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 847 BBInfo *CvtBBI = &TrueBBI; 848 BBInfo *NextBBI = &FalseBBI; 849 850 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 851 if (Kind == ICSimpleFalse) 852 std::swap(CvtBBI, NextBBI); 853 854 if (CvtBBI->IsDone || 855 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 856 // Something has changed. It's no longer safe to predicate this block. 857 BBI.IsAnalyzed = false; 858 CvtBBI->IsAnalyzed = false; 859 return false; 860 } 861 862 if (Kind == ICSimpleFalse) 863 if (TII->ReverseBranchCondition(Cond)) 864 assert(false && "Unable to reverse branch condition!"); 865 866 if (CvtBBI->BB->pred_size() > 1) { 867 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 868 // Copy instructions in the true block, predicate them, and add them to 869 // the entry block. 870 CopyAndPredicateBlock(BBI, *CvtBBI, Cond); 871 } else { 872 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 873 874 // Merge converted block into entry block. 875 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 876 MergeBlocks(BBI, *CvtBBI); 877 } 878 879 bool IterIfcvt = true; 880 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) { 881 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 882 BBI.HasFallThrough = false; 883 // Now ifcvt'd block will look like this: 884 // BB: 885 // ... 886 // t, f = cmp 887 // if t op 888 // b BBf 889 // 890 // We cannot further ifcvt this block because the unconditional branch 891 // will have to be predicated on the new condition, that will not be 892 // available if cmp executes. 893 IterIfcvt = false; 894 } 895 896 RemoveExtraEdges(BBI); 897 898 // Update block info. BB can be iteratively if-converted. 899 if (!IterIfcvt) 900 BBI.IsDone = true; 901 InvalidatePreds(BBI.BB); 902 CvtBBI->IsDone = true; 903 904 // FIXME: Must maintain LiveIns. 905 return true; 906} 907 908/// IfConvertTriangle - If convert a triangle sub-CFG. 909/// 910bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) { 911 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 912 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 913 BBInfo *CvtBBI = &TrueBBI; 914 BBInfo *NextBBI = &FalseBBI; 915 916 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 917 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 918 std::swap(CvtBBI, NextBBI); 919 920 if (CvtBBI->IsDone || 921 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 922 // Something has changed. It's no longer safe to predicate this block. 923 BBI.IsAnalyzed = false; 924 CvtBBI->IsAnalyzed = false; 925 return false; 926 } 927 928 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 929 if (TII->ReverseBranchCondition(Cond)) 930 assert(false && "Unable to reverse branch condition!"); 931 932 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) { 933 if (ReverseBranchCondition(*CvtBBI)) { 934 // BB has been changed, modify its predecessors (except for this 935 // one) so they don't get ifcvt'ed based on bad intel. 936 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(), 937 E = CvtBBI->BB->pred_end(); PI != E; ++PI) { 938 MachineBasicBlock *PBB = *PI; 939 if (PBB == BBI.BB) 940 continue; 941 BBInfo &PBBI = BBAnalysis[PBB->getNumber()]; 942 if (PBBI.IsEnqueued) { 943 PBBI.IsAnalyzed = false; 944 PBBI.IsEnqueued = false; 945 } 946 } 947 } 948 } 949 950 bool HasEarlyExit = CvtBBI->FalseBB != NULL; 951 bool DupBB = CvtBBI->BB->pred_size() > 1; 952 if (DupBB) { 953 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 954 // Copy instructions in the true block, predicate them, and add them to 955 // the entry block. 956 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true); 957 } else { 958 // Predicate the 'true' block after removing its branch. 959 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB); 960 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 961 962 // Now merge the entry of the triangle with the true block. 963 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 964 MergeBlocks(BBI, *CvtBBI); 965 } 966 967 // If 'true' block has a 'false' successor, add an exit branch to it. 968 if (HasEarlyExit) { 969 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(), 970 CvtBBI->BrCond.end()); 971 if (TII->ReverseBranchCondition(RevCond)) 972 assert(false && "Unable to reverse branch condition!"); 973 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond); 974 BBI.BB->addSuccessor(CvtBBI->FalseBB); 975 } 976 977 // Merge in the 'false' block if the 'false' block has no other 978 // predecessors. Otherwise, add an unconditional branch to 'false'. 979 bool FalseBBDead = false; 980 bool IterIfcvt = true; 981 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB); 982 if (!isFallThrough) { 983 // Only merge them if the true block does not fallthrough to the false 984 // block. By not merging them, we make it possible to iteratively 985 // ifcvt the blocks. 986 if (!HasEarlyExit && 987 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) { 988 MergeBlocks(BBI, *NextBBI); 989 FalseBBDead = true; 990 } else { 991 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 992 BBI.HasFallThrough = false; 993 } 994 // Mixed predicated and unpredicated code. This cannot be iteratively 995 // predicated. 996 IterIfcvt = false; 997 } 998 999 RemoveExtraEdges(BBI); 1000 1001 // Update block info. BB can be iteratively if-converted. 1002 if (!IterIfcvt) 1003 BBI.IsDone = true; 1004 InvalidatePreds(BBI.BB); 1005 CvtBBI->IsDone = true; 1006 if (FalseBBDead) 1007 NextBBI->IsDone = true; 1008 1009 // FIXME: Must maintain LiveIns. 1010 return true; 1011} 1012 1013/// IfConvertDiamond - If convert a diamond sub-CFG. 1014/// 1015bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 1016 unsigned NumDups1, unsigned NumDups2) { 1017 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 1018 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 1019 MachineBasicBlock *TailBB = TrueBBI.TrueBB; 1020 // True block must fall through or end with an unanalyzable terminator. 1021 if (!TailBB) { 1022 if (blockAlwaysFallThrough(TrueBBI)) 1023 TailBB = FalseBBI.TrueBB; 1024 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!"); 1025 } 1026 1027 if (TrueBBI.IsDone || FalseBBI.IsDone || 1028 TrueBBI.BB->pred_size() > 1 || 1029 FalseBBI.BB->pred_size() > 1) { 1030 // Something has changed. It's no longer safe to predicate these blocks. 1031 BBI.IsAnalyzed = false; 1032 TrueBBI.IsAnalyzed = false; 1033 FalseBBI.IsAnalyzed = false; 1034 return false; 1035 } 1036 1037 // Merge the 'true' and 'false' blocks by copying the instructions 1038 // from the 'false' block to the 'true' block. That is, unless the true 1039 // block would clobber the predicate, in that case, do the opposite. 1040 BBInfo *BBI1 = &TrueBBI; 1041 BBInfo *BBI2 = &FalseBBI; 1042 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 1043 if (TII->ReverseBranchCondition(RevCond)) 1044 assert(false && "Unable to reverse branch condition!"); 1045 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond; 1046 SmallVector<MachineOperand, 4> *Cond2 = &RevCond; 1047 1048 // Figure out the more profitable ordering. 1049 bool DoSwap = false; 1050 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred) 1051 DoSwap = true; 1052 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) { 1053 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize) 1054 DoSwap = true; 1055 } 1056 if (DoSwap) { 1057 std::swap(BBI1, BBI2); 1058 std::swap(Cond1, Cond2); 1059 } 1060 1061 // Remove the conditional branch from entry to the blocks. 1062 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1063 1064 // Remove the duplicated instructions at the beginnings of both paths. 1065 MachineBasicBlock::iterator DI1 = BBI1->BB->begin(); 1066 MachineBasicBlock::iterator DI2 = BBI2->BB->begin(); 1067 BBI1->NonPredSize -= NumDups1; 1068 BBI2->NonPredSize -= NumDups1; 1069 while (NumDups1 != 0) { 1070 ++DI1; 1071 ++DI2; 1072 --NumDups1; 1073 } 1074 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1); 1075 BBI2->BB->erase(BBI2->BB->begin(), DI2); 1076 1077 // Predicate the 'true' block after removing its branch. 1078 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB); 1079 DI1 = BBI1->BB->end(); 1080 for (unsigned i = 0; i != NumDups2; ++i) 1081 --DI1; 1082 BBI1->BB->erase(DI1, BBI1->BB->end()); 1083 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1); 1084 1085 // Predicate the 'false' block. 1086 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB); 1087 DI2 = BBI2->BB->end(); 1088 while (NumDups2 != 0) { 1089 --DI2; 1090 --NumDups2; 1091 } 1092 PredicateBlock(*BBI2, DI2, *Cond2); 1093 1094 // Merge the true block into the entry of the diamond. 1095 MergeBlocks(BBI, *BBI1); 1096 MergeBlocks(BBI, *BBI2); 1097 1098 // If the if-converted block falls through or unconditionally branches into 1099 // the tail block, and the tail block does not have other predecessors, then 1100 // fold the tail block in as well. Otherwise, unless it falls through to the 1101 // tail, add a unconditional branch to it. 1102 if (TailBB) { 1103 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()]; 1104 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) { 1105 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1106 MergeBlocks(BBI, TailBBI); 1107 TailBBI.IsDone = true; 1108 } else { 1109 InsertUncondBranch(BBI.BB, TailBB, TII); 1110 BBI.HasFallThrough = false; 1111 } 1112 } 1113 1114 RemoveExtraEdges(BBI); 1115 1116 // Update block info. 1117 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true; 1118 InvalidatePreds(BBI.BB); 1119 1120 // FIXME: Must maintain LiveIns. 1121 return true; 1122} 1123 1124/// PredicateBlock - Predicate instructions from the start of the block to the 1125/// specified end with the specified condition. 1126void IfConverter::PredicateBlock(BBInfo &BBI, 1127 MachineBasicBlock::iterator E, 1128 SmallVectorImpl<MachineOperand> &Cond) { 1129 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) { 1130 if (TII->isPredicated(I)) 1131 continue; 1132 if (!TII->PredicateInstruction(I, Cond)) { 1133 cerr << "Unable to predicate " << *I << "!\n"; 1134 abort(); 1135 } 1136 } 1137 1138 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate)); 1139 1140 BBI.IsAnalyzed = false; 1141 BBI.NonPredSize = 0; 1142 1143 NumIfConvBBs++; 1144} 1145 1146/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to 1147/// the destination block. Skip end of block branches if IgnoreBr is true. 1148void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 1149 SmallVectorImpl<MachineOperand> &Cond, 1150 bool IgnoreBr) { 1151 MachineFunction &MF = *ToBBI.BB->getParent(); 1152 1153 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(), 1154 E = FromBBI.BB->end(); I != E; ++I) { 1155 const TargetInstrDesc &TID = I->getDesc(); 1156 bool isPredicated = TII->isPredicated(I); 1157 // Do not copy the end of the block branches. 1158 if (IgnoreBr && !isPredicated && TID.isBranch()) 1159 break; 1160 1161 MachineInstr *MI = MF.CloneMachineInstr(I); 1162 ToBBI.BB->insert(ToBBI.BB->end(), MI); 1163 ToBBI.NonPredSize++; 1164 1165 if (!isPredicated) 1166 if (!TII->PredicateInstruction(MI, Cond)) { 1167 cerr << "Unable to predicate " << *MI << "!\n"; 1168 abort(); 1169 } 1170 } 1171 1172 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(), 1173 FromBBI.BB->succ_end()); 1174 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 1175 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL; 1176 1177 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 1178 MachineBasicBlock *Succ = Succs[i]; 1179 // Fallthrough edge can't be transferred. 1180 if (Succ == FallThrough) 1181 continue; 1182 ToBBI.BB->addSuccessor(Succ); 1183 } 1184 1185 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(), 1186 std::back_inserter(ToBBI.Predicate)); 1187 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate)); 1188 1189 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 1190 ToBBI.IsAnalyzed = false; 1191 1192 NumDupBBs++; 1193} 1194 1195/// MergeBlocks - Move all instructions from FromBB to the end of ToBB. 1196/// 1197void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) { 1198 ToBBI.BB->splice(ToBBI.BB->end(), 1199 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end()); 1200 1201 // Redirect all branches to FromBB to ToBB. 1202 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(), 1203 FromBBI.BB->pred_end()); 1204 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 1205 MachineBasicBlock *Pred = Preds[i]; 1206 if (Pred == ToBBI.BB) 1207 continue; 1208 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB); 1209 } 1210 1211 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(), 1212 FromBBI.BB->succ_end()); 1213 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 1214 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL; 1215 1216 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 1217 MachineBasicBlock *Succ = Succs[i]; 1218 // Fallthrough edge can't be transferred. 1219 if (Succ == FallThrough) 1220 continue; 1221 FromBBI.BB->removeSuccessor(Succ); 1222 ToBBI.BB->addSuccessor(Succ); 1223 } 1224 1225 // Now FromBBI always falls through to the next block! 1226 if (NBB && !FromBBI.BB->isSuccessor(NBB)) 1227 FromBBI.BB->addSuccessor(NBB); 1228 1229 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(), 1230 std::back_inserter(ToBBI.Predicate)); 1231 FromBBI.Predicate.clear(); 1232 1233 ToBBI.NonPredSize += FromBBI.NonPredSize; 1234 FromBBI.NonPredSize = 0; 1235 1236 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 1237 ToBBI.HasFallThrough = FromBBI.HasFallThrough; 1238 ToBBI.IsAnalyzed = false; 1239 FromBBI.IsAnalyzed = false; 1240} 1241