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