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 #include "llvm/CodeGen/Passes.h" 15 #include "BranchFolding.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallSet.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/CodeGen/LivePhysRegs.h" 20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 21 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 22 #include "llvm/CodeGen/MachineFunctionPass.h" 23 #include "llvm/CodeGen/MachineInstrBuilder.h" 24 #include "llvm/CodeGen/MachineModuleInfo.h" 25 #include "llvm/CodeGen/MachineRegisterInfo.h" 26 #include "llvm/CodeGen/TargetSchedule.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Target/TargetInstrInfo.h" 32 #include "llvm/Target/TargetLowering.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include "llvm/Target/TargetSubtargetInfo.h" 35 36 using namespace llvm; 37 38 #define DEBUG_TYPE "ifcvt" 39 40 // Hidden options for help debugging. 41 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden); 42 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden); 43 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden); 44 static cl::opt<bool> DisableSimple("disable-ifcvt-simple", 45 cl::init(false), cl::Hidden); 46 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false", 47 cl::init(false), cl::Hidden); 48 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle", 49 cl::init(false), cl::Hidden); 50 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev", 51 cl::init(false), cl::Hidden); 52 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false", 53 cl::init(false), cl::Hidden); 54 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev", 55 cl::init(false), cl::Hidden); 56 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond", 57 cl::init(false), cl::Hidden); 58 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold", 59 cl::init(true), cl::Hidden); 60 61 STATISTIC(NumSimple, "Number of simple if-conversions performed"); 62 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed"); 63 STATISTIC(NumTriangle, "Number of triangle if-conversions performed"); 64 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed"); 65 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed"); 66 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed"); 67 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed"); 68 STATISTIC(NumIfConvBBs, "Number of if-converted blocks"); 69 STATISTIC(NumDupBBs, "Number of duplicated blocks"); 70 STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated"); 71 72 namespace { 73 class IfConverter : public MachineFunctionPass { 74 enum IfcvtKind { 75 ICNotClassfied, // BB data valid, but not classified. 76 ICSimpleFalse, // Same as ICSimple, but on the false path. 77 ICSimple, // BB is entry of an one split, no rejoin sub-CFG. 78 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition. 79 ICTriangleRev, // Same as ICTriangle, but true path rev condition. 80 ICTriangleFalse, // Same as ICTriangle, but on the false path. 81 ICTriangle, // BB is entry of a triangle sub-CFG. 82 ICDiamond // BB is entry of a diamond sub-CFG. 83 }; 84 85 /// BBInfo - One per MachineBasicBlock, this is used to cache the result 86 /// if-conversion feasibility analysis. This includes results from 87 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its 88 /// classification, and common tail block of its successors (if it's a 89 /// diamond shape), its size, whether it's predicable, and whether any 90 /// instruction can clobber the 'would-be' predicate. 91 /// 92 /// IsDone - True if BB is not to be considered for ifcvt. 93 /// IsBeingAnalyzed - True if BB is currently being analyzed. 94 /// IsAnalyzed - True if BB has been analyzed (info is still valid). 95 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed. 96 /// IsBrAnalyzable - True if AnalyzeBranch() returns false. 97 /// HasFallThrough - True if BB may fallthrough to the following BB. 98 /// IsUnpredicable - True if BB is known to be unpredicable. 99 /// ClobbersPred - True if BB could modify predicates (e.g. has 100 /// cmp, call, etc.) 101 /// NonPredSize - Number of non-predicated instructions. 102 /// ExtraCost - Extra cost for multi-cycle instructions. 103 /// ExtraCost2 - Some instructions are slower when predicated 104 /// BB - Corresponding MachineBasicBlock. 105 /// TrueBB / FalseBB- See AnalyzeBranch(). 106 /// BrCond - Conditions for end of block conditional branches. 107 /// Predicate - Predicate used in the BB. 108 struct BBInfo { 109 bool IsDone : 1; 110 bool IsBeingAnalyzed : 1; 111 bool IsAnalyzed : 1; 112 bool IsEnqueued : 1; 113 bool IsBrAnalyzable : 1; 114 bool HasFallThrough : 1; 115 bool IsUnpredicable : 1; 116 bool CannotBeCopied : 1; 117 bool ClobbersPred : 1; 118 unsigned NonPredSize; 119 unsigned ExtraCost; 120 unsigned ExtraCost2; 121 MachineBasicBlock *BB; 122 MachineBasicBlock *TrueBB; 123 MachineBasicBlock *FalseBB; 124 SmallVector<MachineOperand, 4> BrCond; 125 SmallVector<MachineOperand, 4> Predicate; 126 BBInfo() : IsDone(false), IsBeingAnalyzed(false), 127 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false), 128 HasFallThrough(false), IsUnpredicable(false), 129 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0), 130 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr), 131 FalseBB(nullptr) {} 132 }; 133 134 /// IfcvtToken - Record information about pending if-conversions to attempt: 135 /// BBI - Corresponding BBInfo. 136 /// Kind - Type of block. See IfcvtKind. 137 /// NeedSubsumption - True if the to-be-predicated BB has already been 138 /// predicated. 139 /// NumDups - Number of instructions that would be duplicated due 140 /// to this if-conversion. (For diamonds, the number of 141 /// identical instructions at the beginnings of both 142 /// paths). 143 /// NumDups2 - For diamonds, the number of identical instructions 144 /// at the ends of both paths. 145 struct IfcvtToken { 146 BBInfo &BBI; 147 IfcvtKind Kind; 148 bool NeedSubsumption; 149 unsigned NumDups; 150 unsigned NumDups2; 151 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0) 152 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {} 153 }; 154 155 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by 156 /// basic block number. 157 std::vector<BBInfo> BBAnalysis; 158 TargetSchedModel SchedModel; 159 160 const TargetLoweringBase *TLI; 161 const TargetInstrInfo *TII; 162 const TargetRegisterInfo *TRI; 163 const MachineBlockFrequencyInfo *MBFI; 164 const MachineBranchProbabilityInfo *MBPI; 165 MachineRegisterInfo *MRI; 166 167 LivePhysRegs Redefs; 168 LivePhysRegs DontKill; 169 170 bool PreRegAlloc; 171 bool MadeChange; 172 int FnNum; 173 public: 174 static char ID; 175 IfConverter() : MachineFunctionPass(ID), FnNum(-1) { 176 initializeIfConverterPass(*PassRegistry::getPassRegistry()); 177 } 178 179 void getAnalysisUsage(AnalysisUsage &AU) const override { 180 AU.addRequired<MachineBlockFrequencyInfo>(); 181 AU.addRequired<MachineBranchProbabilityInfo>(); 182 MachineFunctionPass::getAnalysisUsage(AU); 183 } 184 185 bool runOnMachineFunction(MachineFunction &MF) override; 186 187 private: 188 bool ReverseBranchCondition(BBInfo &BBI); 189 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups, 190 const BranchProbability &Prediction) const; 191 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 192 bool FalseBranch, unsigned &Dups, 193 const BranchProbability &Prediction) const; 194 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 195 unsigned &Dups1, unsigned &Dups2) const; 196 void ScanInstructions(BBInfo &BBI); 197 BBInfo &AnalyzeBlock(MachineBasicBlock *BB, 198 std::vector<IfcvtToken*> &Tokens); 199 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond, 200 bool isTriangle = false, bool RevBranch = false); 201 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens); 202 void InvalidatePreds(MachineBasicBlock *BB); 203 void RemoveExtraEdges(BBInfo &BBI); 204 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind); 205 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind); 206 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 207 unsigned NumDups1, unsigned NumDups2); 208 void PredicateBlock(BBInfo &BBI, 209 MachineBasicBlock::iterator E, 210 SmallVectorImpl<MachineOperand> &Cond, 211 SmallSet<unsigned, 4> *LaterRedefs = nullptr); 212 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 213 SmallVectorImpl<MachineOperand> &Cond, 214 bool IgnoreBr = false); 215 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true); 216 217 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, 218 unsigned Cycle, unsigned Extra, 219 const BranchProbability &Prediction) const { 220 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra, 221 Prediction); 222 } 223 224 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, 225 unsigned TCycle, unsigned TExtra, 226 MachineBasicBlock &FBB, 227 unsigned FCycle, unsigned FExtra, 228 const BranchProbability &Prediction) const { 229 return TCycle > 0 && FCycle > 0 && 230 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra, 231 Prediction); 232 } 233 234 // blockAlwaysFallThrough - Block ends without a terminator. 235 bool blockAlwaysFallThrough(BBInfo &BBI) const { 236 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr; 237 } 238 239 // IfcvtTokenCmp - Used to sort if-conversion candidates. 240 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) { 241 int Incr1 = (C1->Kind == ICDiamond) 242 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups; 243 int Incr2 = (C2->Kind == ICDiamond) 244 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups; 245 if (Incr1 > Incr2) 246 return true; 247 else if (Incr1 == Incr2) { 248 // Favors subsumption. 249 if (!C1->NeedSubsumption && C2->NeedSubsumption) 250 return true; 251 else if (C1->NeedSubsumption == C2->NeedSubsumption) { 252 // Favors diamond over triangle, etc. 253 if ((unsigned)C1->Kind < (unsigned)C2->Kind) 254 return true; 255 else if (C1->Kind == C2->Kind) 256 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber(); 257 } 258 } 259 return false; 260 } 261 }; 262 263 char IfConverter::ID = 0; 264 } 265 266 char &llvm::IfConverterID = IfConverter::ID; 267 268 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false) 269 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 270 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false) 271 272 bool IfConverter::runOnMachineFunction(MachineFunction &MF) { 273 const TargetSubtargetInfo &ST = MF.getSubtarget(); 274 TLI = ST.getTargetLowering(); 275 TII = ST.getInstrInfo(); 276 TRI = ST.getRegisterInfo(); 277 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 278 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 279 MRI = &MF.getRegInfo(); 280 SchedModel.init(ST.getSchedModel(), &ST, TII); 281 282 if (!TII) return false; 283 284 PreRegAlloc = MRI->isSSA(); 285 286 bool BFChange = false; 287 if (!PreRegAlloc) { 288 // Tail merge tend to expose more if-conversion opportunities. 289 BranchFolder BF(true, false, *MBFI, *MBPI); 290 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(), 291 getAnalysisIfAvailable<MachineModuleInfo>()); 292 } 293 294 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'" 295 << MF.getName() << "\'"); 296 297 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) { 298 DEBUG(dbgs() << " skipped\n"); 299 return false; 300 } 301 DEBUG(dbgs() << "\n"); 302 303 MF.RenumberBlocks(); 304 BBAnalysis.resize(MF.getNumBlockIDs()); 305 306 std::vector<IfcvtToken*> Tokens; 307 MadeChange = false; 308 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + 309 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds; 310 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) { 311 // Do an initial analysis for each basic block and find all the potential 312 // candidates to perform if-conversion. 313 bool Change = false; 314 AnalyzeBlocks(MF, Tokens); 315 while (!Tokens.empty()) { 316 IfcvtToken *Token = Tokens.back(); 317 Tokens.pop_back(); 318 BBInfo &BBI = Token->BBI; 319 IfcvtKind Kind = Token->Kind; 320 unsigned NumDups = Token->NumDups; 321 unsigned NumDups2 = Token->NumDups2; 322 323 delete Token; 324 325 // If the block has been evicted out of the queue or it has already been 326 // marked dead (due to it being predicated), then skip it. 327 if (BBI.IsDone) 328 BBI.IsEnqueued = false; 329 if (!BBI.IsEnqueued) 330 continue; 331 332 BBI.IsEnqueued = false; 333 334 bool RetVal = false; 335 switch (Kind) { 336 default: llvm_unreachable("Unexpected!"); 337 case ICSimple: 338 case ICSimpleFalse: { 339 bool isFalse = Kind == ICSimpleFalse; 340 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break; 341 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? 342 " false" : "") 343 << "): BB#" << BBI.BB->getNumber() << " (" 344 << ((Kind == ICSimpleFalse) 345 ? BBI.FalseBB->getNumber() 346 : BBI.TrueBB->getNumber()) << ") "); 347 RetVal = IfConvertSimple(BBI, Kind); 348 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n"); 349 if (RetVal) { 350 if (isFalse) ++NumSimpleFalse; 351 else ++NumSimple; 352 } 353 break; 354 } 355 case ICTriangle: 356 case ICTriangleRev: 357 case ICTriangleFalse: 358 case ICTriangleFRev: { 359 bool isFalse = Kind == ICTriangleFalse; 360 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev); 361 if (DisableTriangle && !isFalse && !isRev) break; 362 if (DisableTriangleR && !isFalse && isRev) break; 363 if (DisableTriangleF && isFalse && !isRev) break; 364 if (DisableTriangleFR && isFalse && isRev) break; 365 DEBUG(dbgs() << "Ifcvt (Triangle"); 366 if (isFalse) 367 DEBUG(dbgs() << " false"); 368 if (isRev) 369 DEBUG(dbgs() << " rev"); 370 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:" 371 << BBI.TrueBB->getNumber() << ",F:" 372 << BBI.FalseBB->getNumber() << ") "); 373 RetVal = IfConvertTriangle(BBI, Kind); 374 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n"); 375 if (RetVal) { 376 if (isFalse) { 377 if (isRev) ++NumTriangleFRev; 378 else ++NumTriangleFalse; 379 } else { 380 if (isRev) ++NumTriangleRev; 381 else ++NumTriangle; 382 } 383 } 384 break; 385 } 386 case ICDiamond: { 387 if (DisableDiamond) break; 388 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:" 389 << BBI.TrueBB->getNumber() << ",F:" 390 << BBI.FalseBB->getNumber() << ") "); 391 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2); 392 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n"); 393 if (RetVal) ++NumDiamonds; 394 break; 395 } 396 } 397 398 Change |= RetVal; 399 400 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev + 401 NumTriangleFalse + NumTriangleFRev + NumDiamonds; 402 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit) 403 break; 404 } 405 406 if (!Change) 407 break; 408 MadeChange |= Change; 409 } 410 411 // Delete tokens in case of early exit. 412 while (!Tokens.empty()) { 413 IfcvtToken *Token = Tokens.back(); 414 Tokens.pop_back(); 415 delete Token; 416 } 417 418 Tokens.clear(); 419 BBAnalysis.clear(); 420 421 if (MadeChange && IfCvtBranchFold) { 422 BranchFolder BF(false, false, *MBFI, *MBPI); 423 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), 424 getAnalysisIfAvailable<MachineModuleInfo>()); 425 } 426 427 MadeChange |= BFChange; 428 return MadeChange; 429 } 430 431 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given 432 /// its 'true' successor. 433 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, 434 MachineBasicBlock *TrueBB) { 435 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 436 E = BB->succ_end(); SI != E; ++SI) { 437 MachineBasicBlock *SuccBB = *SI; 438 if (SuccBB != TrueBB) 439 return SuccBB; 440 } 441 return nullptr; 442 } 443 444 /// ReverseBranchCondition - Reverse the condition of the end of the block 445 /// branch. Swap block's 'true' and 'false' successors. 446 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) { 447 DebugLoc dl; // FIXME: this is nowhere 448 if (!TII->ReverseBranchCondition(BBI.BrCond)) { 449 TII->RemoveBranch(*BBI.BB); 450 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl); 451 std::swap(BBI.TrueBB, BBI.FalseBB); 452 return true; 453 } 454 return false; 455 } 456 457 /// getNextBlock - Returns the next block in the function blocks ordering. If 458 /// it is the end, returns NULL. 459 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) { 460 MachineFunction::iterator I = BB; 461 MachineFunction::iterator E = BB->getParent()->end(); 462 if (++I == E) 463 return nullptr; 464 return I; 465 } 466 467 /// ValidSimple - Returns true if the 'true' block (along with its 468 /// predecessor) forms a valid simple shape for ifcvt. It also returns the 469 /// number of instructions that the ifcvt would need to duplicate if performed 470 /// in Dups. 471 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups, 472 const BranchProbability &Prediction) const { 473 Dups = 0; 474 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 475 return false; 476 477 if (TrueBBI.IsBrAnalyzable) 478 return false; 479 480 if (TrueBBI.BB->pred_size() > 1) { 481 if (TrueBBI.CannotBeCopied || 482 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize, 483 Prediction)) 484 return false; 485 Dups = TrueBBI.NonPredSize; 486 } 487 488 return true; 489 } 490 491 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along 492 /// with their common predecessor) forms a valid triangle shape for ifcvt. 493 /// If 'FalseBranch' is true, it checks if 'true' block's false branch 494 /// branches to the 'false' block rather than the other way around. It also 495 /// returns the number of instructions that the ifcvt would need to duplicate 496 /// if performed in 'Dups'. 497 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 498 bool FalseBranch, unsigned &Dups, 499 const BranchProbability &Prediction) const { 500 Dups = 0; 501 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 502 return false; 503 504 if (TrueBBI.BB->pred_size() > 1) { 505 if (TrueBBI.CannotBeCopied) 506 return false; 507 508 unsigned Size = TrueBBI.NonPredSize; 509 if (TrueBBI.IsBrAnalyzable) { 510 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty()) 511 // Ends with an unconditional branch. It will be removed. 512 --Size; 513 else { 514 MachineBasicBlock *FExit = FalseBranch 515 ? TrueBBI.TrueBB : TrueBBI.FalseBB; 516 if (FExit) 517 // Require a conditional branch 518 ++Size; 519 } 520 } 521 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction)) 522 return false; 523 Dups = Size; 524 } 525 526 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB; 527 if (!TExit && blockAlwaysFallThrough(TrueBBI)) { 528 MachineFunction::iterator I = TrueBBI.BB; 529 if (++I == TrueBBI.BB->getParent()->end()) 530 return false; 531 TExit = I; 532 } 533 return TExit && TExit == FalseBBI.BB; 534 } 535 536 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along 537 /// with their common predecessor) forms a valid diamond shape for ifcvt. 538 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 539 unsigned &Dups1, unsigned &Dups2) const { 540 Dups1 = Dups2 = 0; 541 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone || 542 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone) 543 return false; 544 545 MachineBasicBlock *TT = TrueBBI.TrueBB; 546 MachineBasicBlock *FT = FalseBBI.TrueBB; 547 548 if (!TT && blockAlwaysFallThrough(TrueBBI)) 549 TT = getNextBlock(TrueBBI.BB); 550 if (!FT && blockAlwaysFallThrough(FalseBBI)) 551 FT = getNextBlock(FalseBBI.BB); 552 if (TT != FT) 553 return false; 554 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable)) 555 return false; 556 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) 557 return false; 558 559 // FIXME: Allow true block to have an early exit? 560 if (TrueBBI.FalseBB || FalseBBI.FalseBB || 561 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)) 562 return false; 563 564 // Count duplicate instructions at the beginning of the true and false blocks. 565 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin(); 566 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin(); 567 MachineBasicBlock::iterator TIE = TrueBBI.BB->end(); 568 MachineBasicBlock::iterator FIE = FalseBBI.BB->end(); 569 while (TIB != TIE && FIB != FIE) { 570 // Skip dbg_value instructions. These do not count. 571 if (TIB->isDebugValue()) { 572 while (TIB != TIE && TIB->isDebugValue()) 573 ++TIB; 574 if (TIB == TIE) 575 break; 576 } 577 if (FIB->isDebugValue()) { 578 while (FIB != FIE && FIB->isDebugValue()) 579 ++FIB; 580 if (FIB == FIE) 581 break; 582 } 583 if (!TIB->isIdenticalTo(FIB)) 584 break; 585 ++Dups1; 586 ++TIB; 587 ++FIB; 588 } 589 590 // Now, in preparation for counting duplicate instructions at the ends of the 591 // blocks, move the end iterators up past any branch instructions. 592 while (TIE != TIB) { 593 --TIE; 594 if (!TIE->isBranch()) 595 break; 596 } 597 while (FIE != FIB) { 598 --FIE; 599 if (!FIE->isBranch()) 600 break; 601 } 602 603 // If Dups1 includes all of a block, then don't count duplicate 604 // instructions at the end of the blocks. 605 if (TIB == TIE || FIB == FIE) 606 return true; 607 608 // Count duplicate instructions at the ends of the blocks. 609 while (TIE != TIB && FIE != FIB) { 610 // Skip dbg_value instructions. These do not count. 611 if (TIE->isDebugValue()) { 612 while (TIE != TIB && TIE->isDebugValue()) 613 --TIE; 614 if (TIE == TIB) 615 break; 616 } 617 if (FIE->isDebugValue()) { 618 while (FIE != FIB && FIE->isDebugValue()) 619 --FIE; 620 if (FIE == FIB) 621 break; 622 } 623 if (!TIE->isIdenticalTo(FIE)) 624 break; 625 ++Dups2; 626 --TIE; 627 --FIE; 628 } 629 630 return true; 631 } 632 633 /// ScanInstructions - Scan all the instructions in the block to determine if 634 /// the block is predicable. In most cases, that means all the instructions 635 /// in the block are isPredicable(). Also checks if the block contains any 636 /// instruction which can clobber a predicate (e.g. condition code register). 637 /// If so, the block is not predicable unless it's the last instruction. 638 void IfConverter::ScanInstructions(BBInfo &BBI) { 639 if (BBI.IsDone) 640 return; 641 642 bool AlreadyPredicated = !BBI.Predicate.empty(); 643 // First analyze the end of BB branches. 644 BBI.TrueBB = BBI.FalseBB = nullptr; 645 BBI.BrCond.clear(); 646 BBI.IsBrAnalyzable = 647 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond); 648 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr; 649 650 if (BBI.BrCond.size()) { 651 // No false branch. This BB must end with a conditional branch and a 652 // fallthrough. 653 if (!BBI.FalseBB) 654 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB); 655 if (!BBI.FalseBB) { 656 // Malformed bcc? True and false blocks are the same? 657 BBI.IsUnpredicable = true; 658 return; 659 } 660 } 661 662 // Then scan all the instructions. 663 BBI.NonPredSize = 0; 664 BBI.ExtraCost = 0; 665 BBI.ExtraCost2 = 0; 666 BBI.ClobbersPred = false; 667 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end(); 668 I != E; ++I) { 669 if (I->isDebugValue()) 670 continue; 671 672 if (I->isNotDuplicable()) 673 BBI.CannotBeCopied = true; 674 675 bool isPredicated = TII->isPredicated(I); 676 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch(); 677 678 // A conditional branch is not predicable, but it may be eliminated. 679 if (isCondBr) 680 continue; 681 682 if (!isPredicated) { 683 BBI.NonPredSize++; 684 unsigned ExtraPredCost = TII->getPredicationCost(&*I); 685 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false); 686 if (NumCycles > 1) 687 BBI.ExtraCost += NumCycles-1; 688 BBI.ExtraCost2 += ExtraPredCost; 689 } else if (!AlreadyPredicated) { 690 // FIXME: This instruction is already predicated before the 691 // if-conversion pass. It's probably something like a conditional move. 692 // Mark this block unpredicable for now. 693 BBI.IsUnpredicable = true; 694 return; 695 } 696 697 if (BBI.ClobbersPred && !isPredicated) { 698 // Predicate modification instruction should end the block (except for 699 // already predicated instructions and end of block branches). 700 // Predicate may have been modified, the subsequent (currently) 701 // unpredicated instructions cannot be correctly predicated. 702 BBI.IsUnpredicable = true; 703 return; 704 } 705 706 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are 707 // still potentially predicable. 708 std::vector<MachineOperand> PredDefs; 709 if (TII->DefinesPredicate(I, PredDefs)) 710 BBI.ClobbersPred = true; 711 712 if (!TII->isPredicable(I)) { 713 BBI.IsUnpredicable = true; 714 return; 715 } 716 } 717 } 718 719 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be 720 /// predicated by the specified predicate. 721 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI, 722 SmallVectorImpl<MachineOperand> &Pred, 723 bool isTriangle, bool RevBranch) { 724 // If the block is dead or unpredicable, then it cannot be predicated. 725 if (BBI.IsDone || BBI.IsUnpredicable) 726 return false; 727 728 // If it is already predicated but we couldn't analyze its terminator, the 729 // latter might fallthrough, but we can't determine where to. 730 // Conservatively avoid if-converting again. 731 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable) 732 return false; 733 734 // If it is already predicated, check if the new predicate subsumes 735 // its predicate. 736 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate)) 737 return false; 738 739 if (BBI.BrCond.size()) { 740 if (!isTriangle) 741 return false; 742 743 // Test predicate subsumption. 744 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end()); 745 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 746 if (RevBranch) { 747 if (TII->ReverseBranchCondition(Cond)) 748 return false; 749 } 750 if (TII->ReverseBranchCondition(RevPred) || 751 !TII->SubsumesPredicate(Cond, RevPred)) 752 return false; 753 } 754 755 return true; 756 } 757 758 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from 759 /// the specified block. Record its successors and whether it looks like an 760 /// if-conversion candidate. 761 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB, 762 std::vector<IfcvtToken*> &Tokens) { 763 BBInfo &BBI = BBAnalysis[BB->getNumber()]; 764 765 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) 766 return BBI; 767 768 BBI.BB = BB; 769 BBI.IsBeingAnalyzed = true; 770 771 ScanInstructions(BBI); 772 773 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not 774 // considered for ifcvt anymore. 775 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) { 776 BBI.IsBeingAnalyzed = false; 777 BBI.IsAnalyzed = true; 778 return BBI; 779 } 780 781 // Do not ifcvt if either path is a back edge to the entry block. 782 if (BBI.TrueBB == BB || BBI.FalseBB == BB) { 783 BBI.IsBeingAnalyzed = false; 784 BBI.IsAnalyzed = true; 785 return BBI; 786 } 787 788 // Do not ifcvt if true and false fallthrough blocks are the same. 789 if (!BBI.FalseBB) { 790 BBI.IsBeingAnalyzed = false; 791 BBI.IsAnalyzed = true; 792 return BBI; 793 } 794 795 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens); 796 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens); 797 798 if (TrueBBI.IsDone && FalseBBI.IsDone) { 799 BBI.IsBeingAnalyzed = false; 800 BBI.IsAnalyzed = true; 801 return BBI; 802 } 803 804 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 805 bool CanRevCond = !TII->ReverseBranchCondition(RevCond); 806 807 unsigned Dups = 0; 808 unsigned Dups2 = 0; 809 bool TNeedSub = !TrueBBI.Predicate.empty(); 810 bool FNeedSub = !FalseBBI.Predicate.empty(); 811 bool Enqueued = false; 812 813 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB); 814 815 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) && 816 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) + 817 TrueBBI.ExtraCost), TrueBBI.ExtraCost2, 818 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) + 819 FalseBBI.ExtraCost),FalseBBI.ExtraCost2, 820 Prediction) && 821 FeasibilityAnalysis(TrueBBI, BBI.BrCond) && 822 FeasibilityAnalysis(FalseBBI, RevCond)) { 823 // Diamond: 824 // EBB 825 // / \_ 826 // | | 827 // TBB FBB 828 // \ / 829 // TailBB 830 // Note TailBB can be empty. 831 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups, 832 Dups2)); 833 Enqueued = true; 834 } 835 836 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) && 837 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost, 838 TrueBBI.ExtraCost2, Prediction) && 839 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) { 840 // Triangle: 841 // EBB 842 // | \_ 843 // | | 844 // | TBB 845 // | / 846 // FBB 847 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups)); 848 Enqueued = true; 849 } 850 851 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) && 852 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost, 853 TrueBBI.ExtraCost2, Prediction) && 854 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) { 855 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups)); 856 Enqueued = true; 857 } 858 859 if (ValidSimple(TrueBBI, Dups, Prediction) && 860 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost, 861 TrueBBI.ExtraCost2, Prediction) && 862 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) { 863 // Simple (split, no rejoin): 864 // EBB 865 // | \_ 866 // | | 867 // | TBB---> exit 868 // | 869 // FBB 870 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups)); 871 Enqueued = true; 872 } 873 874 if (CanRevCond) { 875 // Try the other path... 876 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups, 877 Prediction.getCompl()) && 878 MeetIfcvtSizeLimit(*FalseBBI.BB, 879 FalseBBI.NonPredSize + FalseBBI.ExtraCost, 880 FalseBBI.ExtraCost2, Prediction.getCompl()) && 881 FeasibilityAnalysis(FalseBBI, RevCond, true)) { 882 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups)); 883 Enqueued = true; 884 } 885 886 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups, 887 Prediction.getCompl()) && 888 MeetIfcvtSizeLimit(*FalseBBI.BB, 889 FalseBBI.NonPredSize + FalseBBI.ExtraCost, 890 FalseBBI.ExtraCost2, Prediction.getCompl()) && 891 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) { 892 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups)); 893 Enqueued = true; 894 } 895 896 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) && 897 MeetIfcvtSizeLimit(*FalseBBI.BB, 898 FalseBBI.NonPredSize + FalseBBI.ExtraCost, 899 FalseBBI.ExtraCost2, Prediction.getCompl()) && 900 FeasibilityAnalysis(FalseBBI, RevCond)) { 901 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups)); 902 Enqueued = true; 903 } 904 } 905 906 BBI.IsEnqueued = Enqueued; 907 BBI.IsBeingAnalyzed = false; 908 BBI.IsAnalyzed = true; 909 return BBI; 910 } 911 912 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion 913 /// candidates. 914 void IfConverter::AnalyzeBlocks(MachineFunction &MF, 915 std::vector<IfcvtToken*> &Tokens) { 916 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) { 917 MachineBasicBlock *BB = I; 918 AnalyzeBlock(BB, Tokens); 919 } 920 921 // Sort to favor more complex ifcvt scheme. 922 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp); 923 } 924 925 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or 926 /// that all the intervening blocks are empty (given BB can fall through to its 927 /// next block). 928 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) { 929 MachineFunction::iterator PI = BB; 930 MachineFunction::iterator I = std::next(PI); 931 MachineFunction::iterator TI = ToBB; 932 MachineFunction::iterator E = BB->getParent()->end(); 933 while (I != TI) { 934 // Check isSuccessor to avoid case where the next block is empty, but 935 // it's not a successor. 936 if (I == E || !I->empty() || !PI->isSuccessor(I)) 937 return false; 938 PI = I++; 939 } 940 return true; 941 } 942 943 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed 944 /// to determine if it can be if-converted. If predecessor is already enqueued, 945 /// dequeue it! 946 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) { 947 for (const auto &Predecessor : BB->predecessors()) { 948 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()]; 949 if (PBBI.IsDone || PBBI.BB == BB) 950 continue; 951 PBBI.IsAnalyzed = false; 952 PBBI.IsEnqueued = false; 953 } 954 } 955 956 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB. 957 /// 958 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB, 959 const TargetInstrInfo *TII) { 960 DebugLoc dl; // FIXME: this is nowhere 961 SmallVector<MachineOperand, 0> NoCond; 962 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl); 963 } 964 965 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer 966 /// successors. 967 void IfConverter::RemoveExtraEdges(BBInfo &BBI) { 968 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 969 SmallVector<MachineOperand, 4> Cond; 970 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond)) 971 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty()); 972 } 973 974 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all 975 /// values defined in MI which are not live/used by MI. 976 static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) { 977 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers; 978 Redefs.stepForward(*MI, Clobbers); 979 980 // Now add the implicit uses for each of the clobbered values. 981 for (auto Reg : Clobbers) { 982 // FIXME: Const cast here is nasty, but better than making StepForward 983 // take a mutable instruction instead of const. 984 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second); 985 MachineInstr *OpMI = Op.getParent(); 986 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI); 987 if (Op.isRegMask()) { 988 // First handle regmasks. They clobber any entries in the mask which 989 // means that we need a def for those registers. 990 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef); 991 992 // We also need to add an implicit def of this register for the later 993 // use to read from. 994 // For the register allocator to have allocated a register clobbered 995 // by the call which is used later, it must be the case that 996 // the call doesn't return. 997 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define); 998 continue; 999 } 1000 assert(Op.isReg() && "Register operand required"); 1001 if (Op.isDead()) { 1002 // If we found a dead def, but it needs to be live, then remove the dead 1003 // flag. 1004 if (Redefs.contains(Op.getReg())) 1005 Op.setIsDead(false); 1006 } 1007 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef); 1008 } 1009 } 1010 1011 /** 1012 * Remove kill flags from operands with a registers in the @p DontKill set. 1013 */ 1014 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) { 1015 for (MIBundleOperands O(&MI); O.isValid(); ++O) { 1016 if (!O->isReg() || !O->isKill()) 1017 continue; 1018 if (DontKill.contains(O->getReg())) 1019 O->setIsKill(false); 1020 } 1021 } 1022 1023 /** 1024 * Walks a range of machine instructions and removes kill flags for registers 1025 * in the @p DontKill set. 1026 */ 1027 static void RemoveKills(MachineBasicBlock::iterator I, 1028 MachineBasicBlock::iterator E, 1029 const LivePhysRegs &DontKill, 1030 const MCRegisterInfo &MCRI) { 1031 for ( ; I != E; ++I) 1032 RemoveKills(*I, DontKill); 1033 } 1034 1035 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG. 1036 /// 1037 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) { 1038 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 1039 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 1040 BBInfo *CvtBBI = &TrueBBI; 1041 BBInfo *NextBBI = &FalseBBI; 1042 1043 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 1044 if (Kind == ICSimpleFalse) 1045 std::swap(CvtBBI, NextBBI); 1046 1047 if (CvtBBI->IsDone || 1048 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 1049 // Something has changed. It's no longer safe to predicate this block. 1050 BBI.IsAnalyzed = false; 1051 CvtBBI->IsAnalyzed = false; 1052 return false; 1053 } 1054 1055 if (CvtBBI->BB->hasAddressTaken()) 1056 // Conservatively abort if-conversion if BB's address is taken. 1057 return false; 1058 1059 if (Kind == ICSimpleFalse) 1060 if (TII->ReverseBranchCondition(Cond)) 1061 llvm_unreachable("Unable to reverse branch condition!"); 1062 1063 // Initialize liveins to the first BB. These are potentiall redefined by 1064 // predicated instructions. 1065 Redefs.init(TRI); 1066 Redefs.addLiveIns(CvtBBI->BB); 1067 Redefs.addLiveIns(NextBBI->BB); 1068 1069 // Compute a set of registers which must not be killed by instructions in 1070 // BB1: This is everything live-in to BB2. 1071 DontKill.init(TRI); 1072 DontKill.addLiveIns(NextBBI->BB); 1073 1074 if (CvtBBI->BB->pred_size() > 1) { 1075 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1076 // Copy instructions in the true block, predicate them, and add them to 1077 // the entry block. 1078 CopyAndPredicateBlock(BBI, *CvtBBI, Cond); 1079 1080 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so 1081 // explicitly remove CvtBBI as a successor. 1082 BBI.BB->removeSuccessor(CvtBBI->BB); 1083 } else { 1084 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI); 1085 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 1086 1087 // Merge converted block into entry block. 1088 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1089 MergeBlocks(BBI, *CvtBBI); 1090 } 1091 1092 bool IterIfcvt = true; 1093 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) { 1094 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 1095 BBI.HasFallThrough = false; 1096 // Now ifcvt'd block will look like this: 1097 // BB: 1098 // ... 1099 // t, f = cmp 1100 // if t op 1101 // b BBf 1102 // 1103 // We cannot further ifcvt this block because the unconditional branch 1104 // will have to be predicated on the new condition, that will not be 1105 // available if cmp executes. 1106 IterIfcvt = false; 1107 } 1108 1109 RemoveExtraEdges(BBI); 1110 1111 // Update block info. BB can be iteratively if-converted. 1112 if (!IterIfcvt) 1113 BBI.IsDone = true; 1114 InvalidatePreds(BBI.BB); 1115 CvtBBI->IsDone = true; 1116 1117 // FIXME: Must maintain LiveIns. 1118 return true; 1119 } 1120 1121 /// Scale down weights to fit into uint32_t. NewTrue is the new weight 1122 /// for successor TrueBB, and NewFalse is the new weight for successor 1123 /// FalseBB. 1124 static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse, 1125 MachineBasicBlock *MBB, 1126 const MachineBasicBlock *TrueBB, 1127 const MachineBasicBlock *FalseBB, 1128 const MachineBranchProbabilityInfo *MBPI) { 1129 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; 1130 uint32_t Scale = (NewMax / UINT32_MAX) + 1; 1131 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), 1132 SE = MBB->succ_end(); 1133 SI != SE; ++SI) { 1134 if (*SI == TrueBB) 1135 MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale)); 1136 else if (*SI == FalseBB) 1137 MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale)); 1138 else 1139 MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale); 1140 } 1141 } 1142 1143 /// IfConvertTriangle - If convert a triangle sub-CFG. 1144 /// 1145 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) { 1146 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 1147 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 1148 BBInfo *CvtBBI = &TrueBBI; 1149 BBInfo *NextBBI = &FalseBBI; 1150 DebugLoc dl; // FIXME: this is nowhere 1151 1152 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 1153 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 1154 std::swap(CvtBBI, NextBBI); 1155 1156 if (CvtBBI->IsDone || 1157 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 1158 // Something has changed. It's no longer safe to predicate this block. 1159 BBI.IsAnalyzed = false; 1160 CvtBBI->IsAnalyzed = false; 1161 return false; 1162 } 1163 1164 if (CvtBBI->BB->hasAddressTaken()) 1165 // Conservatively abort if-conversion if BB's address is taken. 1166 return false; 1167 1168 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 1169 if (TII->ReverseBranchCondition(Cond)) 1170 llvm_unreachable("Unable to reverse branch condition!"); 1171 1172 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) { 1173 if (ReverseBranchCondition(*CvtBBI)) { 1174 // BB has been changed, modify its predecessors (except for this 1175 // one) so they don't get ifcvt'ed based on bad intel. 1176 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(), 1177 E = CvtBBI->BB->pred_end(); PI != E; ++PI) { 1178 MachineBasicBlock *PBB = *PI; 1179 if (PBB == BBI.BB) 1180 continue; 1181 BBInfo &PBBI = BBAnalysis[PBB->getNumber()]; 1182 if (PBBI.IsEnqueued) { 1183 PBBI.IsAnalyzed = false; 1184 PBBI.IsEnqueued = false; 1185 } 1186 } 1187 } 1188 } 1189 1190 // Initialize liveins to the first BB. These are potentially redefined by 1191 // predicated instructions. 1192 Redefs.init(TRI); 1193 Redefs.addLiveIns(CvtBBI->BB); 1194 Redefs.addLiveIns(NextBBI->BB); 1195 1196 DontKill.clear(); 1197 1198 bool HasEarlyExit = CvtBBI->FalseBB != nullptr; 1199 uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0; 1200 uint32_t WeightScale = 0; 1201 1202 if (HasEarlyExit) { 1203 // Get weights before modifying CvtBBI->BB and BBI.BB. 1204 CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB); 1205 CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB); 1206 BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB); 1207 BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB); 1208 SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale); 1209 } 1210 1211 if (CvtBBI->BB->pred_size() > 1) { 1212 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1213 // Copy instructions in the true block, predicate them, and add them to 1214 // the entry block. 1215 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true); 1216 1217 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so 1218 // explicitly remove CvtBBI as a successor. 1219 BBI.BB->removeSuccessor(CvtBBI->BB); 1220 } else { 1221 // Predicate the 'true' block after removing its branch. 1222 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB); 1223 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 1224 1225 // Now merge the entry of the triangle with the true block. 1226 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1227 MergeBlocks(BBI, *CvtBBI, false); 1228 } 1229 1230 // If 'true' block has a 'false' successor, add an exit branch to it. 1231 if (HasEarlyExit) { 1232 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(), 1233 CvtBBI->BrCond.end()); 1234 if (TII->ReverseBranchCondition(RevCond)) 1235 llvm_unreachable("Unable to reverse branch condition!"); 1236 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl); 1237 BBI.BB->addSuccessor(CvtBBI->FalseBB); 1238 // Update the edge weight for both CvtBBI->FalseBB and NextBBI. 1239 // New_Weight(BBI.BB, NextBBI->BB) = 1240 // Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) + 1241 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB) 1242 // New_Weight(BBI.BB, CvtBBI->FalseBB) = 1243 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB) 1244 1245 uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale; 1246 uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale; 1247 // We need to scale down all weights of BBI.BB to fit uint32_t. 1248 // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to 1249 // the next block. 1250 ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB), 1251 CvtBBI->FalseBB, MBPI); 1252 } 1253 1254 // Merge in the 'false' block if the 'false' block has no other 1255 // predecessors. Otherwise, add an unconditional branch to 'false'. 1256 bool FalseBBDead = false; 1257 bool IterIfcvt = true; 1258 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB); 1259 if (!isFallThrough) { 1260 // Only merge them if the true block does not fallthrough to the false 1261 // block. By not merging them, we make it possible to iteratively 1262 // ifcvt the blocks. 1263 if (!HasEarlyExit && 1264 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough && 1265 !NextBBI->BB->hasAddressTaken()) { 1266 MergeBlocks(BBI, *NextBBI); 1267 FalseBBDead = true; 1268 } else { 1269 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 1270 BBI.HasFallThrough = false; 1271 } 1272 // Mixed predicated and unpredicated code. This cannot be iteratively 1273 // predicated. 1274 IterIfcvt = false; 1275 } 1276 1277 RemoveExtraEdges(BBI); 1278 1279 // Update block info. BB can be iteratively if-converted. 1280 if (!IterIfcvt) 1281 BBI.IsDone = true; 1282 InvalidatePreds(BBI.BB); 1283 CvtBBI->IsDone = true; 1284 if (FalseBBDead) 1285 NextBBI->IsDone = true; 1286 1287 // FIXME: Must maintain LiveIns. 1288 return true; 1289 } 1290 1291 /// IfConvertDiamond - If convert a diamond sub-CFG. 1292 /// 1293 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 1294 unsigned NumDups1, unsigned NumDups2) { 1295 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 1296 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 1297 MachineBasicBlock *TailBB = TrueBBI.TrueBB; 1298 // True block must fall through or end with an unanalyzable terminator. 1299 if (!TailBB) { 1300 if (blockAlwaysFallThrough(TrueBBI)) 1301 TailBB = FalseBBI.TrueBB; 1302 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!"); 1303 } 1304 1305 if (TrueBBI.IsDone || FalseBBI.IsDone || 1306 TrueBBI.BB->pred_size() > 1 || 1307 FalseBBI.BB->pred_size() > 1) { 1308 // Something has changed. It's no longer safe to predicate these blocks. 1309 BBI.IsAnalyzed = false; 1310 TrueBBI.IsAnalyzed = false; 1311 FalseBBI.IsAnalyzed = false; 1312 return false; 1313 } 1314 1315 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken()) 1316 // Conservatively abort if-conversion if either BB has its address taken. 1317 return false; 1318 1319 // Put the predicated instructions from the 'true' block before the 1320 // instructions from the 'false' block, unless the true block would clobber 1321 // the predicate, in which case, do the opposite. 1322 BBInfo *BBI1 = &TrueBBI; 1323 BBInfo *BBI2 = &FalseBBI; 1324 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 1325 if (TII->ReverseBranchCondition(RevCond)) 1326 llvm_unreachable("Unable to reverse branch condition!"); 1327 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond; 1328 SmallVector<MachineOperand, 4> *Cond2 = &RevCond; 1329 1330 // Figure out the more profitable ordering. 1331 bool DoSwap = false; 1332 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred) 1333 DoSwap = true; 1334 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) { 1335 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize) 1336 DoSwap = true; 1337 } 1338 if (DoSwap) { 1339 std::swap(BBI1, BBI2); 1340 std::swap(Cond1, Cond2); 1341 } 1342 1343 // Remove the conditional branch from entry to the blocks. 1344 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1345 1346 // Initialize liveins to the first BB. These are potentially redefined by 1347 // predicated instructions. 1348 Redefs.init(TRI); 1349 Redefs.addLiveIns(BBI1->BB); 1350 1351 // Remove the duplicated instructions at the beginnings of both paths. 1352 MachineBasicBlock::iterator DI1 = BBI1->BB->begin(); 1353 MachineBasicBlock::iterator DI2 = BBI2->BB->begin(); 1354 MachineBasicBlock::iterator DIE1 = BBI1->BB->end(); 1355 MachineBasicBlock::iterator DIE2 = BBI2->BB->end(); 1356 // Skip dbg_value instructions 1357 while (DI1 != DIE1 && DI1->isDebugValue()) 1358 ++DI1; 1359 while (DI2 != DIE2 && DI2->isDebugValue()) 1360 ++DI2; 1361 BBI1->NonPredSize -= NumDups1; 1362 BBI2->NonPredSize -= NumDups1; 1363 1364 // Skip past the dups on each side separately since there may be 1365 // differing dbg_value entries. 1366 for (unsigned i = 0; i < NumDups1; ++DI1) { 1367 if (!DI1->isDebugValue()) 1368 ++i; 1369 } 1370 while (NumDups1 != 0) { 1371 ++DI2; 1372 if (!DI2->isDebugValue()) 1373 --NumDups1; 1374 } 1375 1376 // Compute a set of registers which must not be killed by instructions in BB1: 1377 // This is everything used+live in BB2 after the duplicated instructions. We 1378 // can compute this set by simulating liveness backwards from the end of BB2. 1379 DontKill.init(TRI); 1380 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(), 1381 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) { 1382 DontKill.stepBackward(*I); 1383 } 1384 1385 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E; 1386 ++I) { 1387 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers; 1388 Redefs.stepForward(*I, IgnoredClobbers); 1389 } 1390 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1); 1391 BBI2->BB->erase(BBI2->BB->begin(), DI2); 1392 1393 // Remove branch from 'true' block and remove duplicated instructions. 1394 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB); 1395 DI1 = BBI1->BB->end(); 1396 for (unsigned i = 0; i != NumDups2; ) { 1397 // NumDups2 only counted non-dbg_value instructions, so this won't 1398 // run off the head of the list. 1399 assert (DI1 != BBI1->BB->begin()); 1400 --DI1; 1401 // skip dbg_value instructions 1402 if (!DI1->isDebugValue()) 1403 ++i; 1404 } 1405 BBI1->BB->erase(DI1, BBI1->BB->end()); 1406 1407 // Kill flags in the true block for registers living into the false block 1408 // must be removed. 1409 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI); 1410 1411 // Remove 'false' block branch and find the last instruction to predicate. 1412 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB); 1413 DI2 = BBI2->BB->end(); 1414 while (NumDups2 != 0) { 1415 // NumDups2 only counted non-dbg_value instructions, so this won't 1416 // run off the head of the list. 1417 assert (DI2 != BBI2->BB->begin()); 1418 --DI2; 1419 // skip dbg_value instructions 1420 if (!DI2->isDebugValue()) 1421 --NumDups2; 1422 } 1423 1424 // Remember which registers would later be defined by the false block. 1425 // This allows us not to predicate instructions in the true block that would 1426 // later be re-defined. That is, rather than 1427 // subeq r0, r1, #1 1428 // addne r0, r1, #1 1429 // generate: 1430 // sub r0, r1, #1 1431 // addne r0, r1, #1 1432 SmallSet<unsigned, 4> RedefsByFalse; 1433 SmallSet<unsigned, 4> ExtUses; 1434 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) { 1435 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) { 1436 if (FI->isDebugValue()) 1437 continue; 1438 SmallVector<unsigned, 4> Defs; 1439 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) { 1440 const MachineOperand &MO = FI->getOperand(i); 1441 if (!MO.isReg()) 1442 continue; 1443 unsigned Reg = MO.getReg(); 1444 if (!Reg) 1445 continue; 1446 if (MO.isDef()) { 1447 Defs.push_back(Reg); 1448 } else if (!RedefsByFalse.count(Reg)) { 1449 // These are defined before ctrl flow reach the 'false' instructions. 1450 // They cannot be modified by the 'true' instructions. 1451 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 1452 SubRegs.isValid(); ++SubRegs) 1453 ExtUses.insert(*SubRegs); 1454 } 1455 } 1456 1457 for (unsigned i = 0, e = Defs.size(); i != e; ++i) { 1458 unsigned Reg = Defs[i]; 1459 if (!ExtUses.count(Reg)) { 1460 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 1461 SubRegs.isValid(); ++SubRegs) 1462 RedefsByFalse.insert(*SubRegs); 1463 } 1464 } 1465 } 1466 } 1467 1468 // Predicate the 'true' block. 1469 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse); 1470 1471 // Predicate the 'false' block. 1472 PredicateBlock(*BBI2, DI2, *Cond2); 1473 1474 // Merge the true block into the entry of the diamond. 1475 MergeBlocks(BBI, *BBI1, TailBB == nullptr); 1476 MergeBlocks(BBI, *BBI2, TailBB == nullptr); 1477 1478 // If the if-converted block falls through or unconditionally branches into 1479 // the tail block, and the tail block does not have other predecessors, then 1480 // fold the tail block in as well. Otherwise, unless it falls through to the 1481 // tail, add a unconditional branch to it. 1482 if (TailBB) { 1483 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()]; 1484 bool CanMergeTail = !TailBBI.HasFallThrough && 1485 !TailBBI.BB->hasAddressTaken(); 1486 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB; 1487 // check if there are any other predecessors besides those. 1488 unsigned NumPreds = TailBB->pred_size(); 1489 if (NumPreds > 1) 1490 CanMergeTail = false; 1491 else if (NumPreds == 1 && CanMergeTail) { 1492 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin(); 1493 if (*PI != BBI1->BB && *PI != BBI2->BB) 1494 CanMergeTail = false; 1495 } 1496 if (CanMergeTail) { 1497 MergeBlocks(BBI, TailBBI); 1498 TailBBI.IsDone = true; 1499 } else { 1500 BBI.BB->addSuccessor(TailBB); 1501 InsertUncondBranch(BBI.BB, TailBB, TII); 1502 BBI.HasFallThrough = false; 1503 } 1504 } 1505 1506 // RemoveExtraEdges won't work if the block has an unanalyzable branch, 1507 // which can happen here if TailBB is unanalyzable and is merged, so 1508 // explicitly remove BBI1 and BBI2 as successors. 1509 BBI.BB->removeSuccessor(BBI1->BB); 1510 BBI.BB->removeSuccessor(BBI2->BB); 1511 RemoveExtraEdges(BBI); 1512 1513 // Update block info. 1514 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true; 1515 InvalidatePreds(BBI.BB); 1516 1517 // FIXME: Must maintain LiveIns. 1518 return true; 1519 } 1520 1521 static bool MaySpeculate(const MachineInstr *MI, 1522 SmallSet<unsigned, 4> &LaterRedefs) { 1523 bool SawStore = true; 1524 if (!MI->isSafeToMove(nullptr, SawStore)) 1525 return false; 1526 1527 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1528 const MachineOperand &MO = MI->getOperand(i); 1529 if (!MO.isReg()) 1530 continue; 1531 unsigned Reg = MO.getReg(); 1532 if (!Reg) 1533 continue; 1534 if (MO.isDef() && !LaterRedefs.count(Reg)) 1535 return false; 1536 } 1537 1538 return true; 1539 } 1540 1541 /// PredicateBlock - Predicate instructions from the start of the block to the 1542 /// specified end with the specified condition. 1543 void IfConverter::PredicateBlock(BBInfo &BBI, 1544 MachineBasicBlock::iterator E, 1545 SmallVectorImpl<MachineOperand> &Cond, 1546 SmallSet<unsigned, 4> *LaterRedefs) { 1547 bool AnyUnpred = false; 1548 bool MaySpec = LaterRedefs != nullptr; 1549 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) { 1550 if (I->isDebugValue() || TII->isPredicated(I)) 1551 continue; 1552 // It may be possible not to predicate an instruction if it's the 'true' 1553 // side of a diamond and the 'false' side may re-define the instruction's 1554 // defs. 1555 if (MaySpec && MaySpeculate(I, *LaterRedefs)) { 1556 AnyUnpred = true; 1557 continue; 1558 } 1559 // If any instruction is predicated, then every instruction after it must 1560 // be predicated. 1561 MaySpec = false; 1562 if (!TII->PredicateInstruction(I, Cond)) { 1563 #ifndef NDEBUG 1564 dbgs() << "Unable to predicate " << *I << "!\n"; 1565 #endif 1566 llvm_unreachable(nullptr); 1567 } 1568 1569 // If the predicated instruction now redefines a register as the result of 1570 // if-conversion, add an implicit kill. 1571 UpdatePredRedefs(I, Redefs); 1572 } 1573 1574 BBI.Predicate.append(Cond.begin(), Cond.end()); 1575 1576 BBI.IsAnalyzed = false; 1577 BBI.NonPredSize = 0; 1578 1579 ++NumIfConvBBs; 1580 if (AnyUnpred) 1581 ++NumUnpred; 1582 } 1583 1584 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to 1585 /// the destination block. Skip end of block branches if IgnoreBr is true. 1586 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 1587 SmallVectorImpl<MachineOperand> &Cond, 1588 bool IgnoreBr) { 1589 MachineFunction &MF = *ToBBI.BB->getParent(); 1590 1591 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(), 1592 E = FromBBI.BB->end(); I != E; ++I) { 1593 // Do not copy the end of the block branches. 1594 if (IgnoreBr && I->isBranch()) 1595 break; 1596 1597 MachineInstr *MI = MF.CloneMachineInstr(I); 1598 ToBBI.BB->insert(ToBBI.BB->end(), MI); 1599 ToBBI.NonPredSize++; 1600 unsigned ExtraPredCost = TII->getPredicationCost(&*I); 1601 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false); 1602 if (NumCycles > 1) 1603 ToBBI.ExtraCost += NumCycles-1; 1604 ToBBI.ExtraCost2 += ExtraPredCost; 1605 1606 if (!TII->isPredicated(I) && !MI->isDebugValue()) { 1607 if (!TII->PredicateInstruction(MI, Cond)) { 1608 #ifndef NDEBUG 1609 dbgs() << "Unable to predicate " << *I << "!\n"; 1610 #endif 1611 llvm_unreachable(nullptr); 1612 } 1613 } 1614 1615 // If the predicated instruction now redefines a register as the result of 1616 // if-conversion, add an implicit kill. 1617 UpdatePredRedefs(MI, Redefs); 1618 1619 // Some kill flags may not be correct anymore. 1620 if (!DontKill.empty()) 1621 RemoveKills(*MI, DontKill); 1622 } 1623 1624 if (!IgnoreBr) { 1625 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(), 1626 FromBBI.BB->succ_end()); 1627 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 1628 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr; 1629 1630 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 1631 MachineBasicBlock *Succ = Succs[i]; 1632 // Fallthrough edge can't be transferred. 1633 if (Succ == FallThrough) 1634 continue; 1635 ToBBI.BB->addSuccessor(Succ); 1636 } 1637 } 1638 1639 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end()); 1640 ToBBI.Predicate.append(Cond.begin(), Cond.end()); 1641 1642 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 1643 ToBBI.IsAnalyzed = false; 1644 1645 ++NumDupBBs; 1646 } 1647 1648 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB. 1649 /// This will leave FromBB as an empty block, so remove all of its 1650 /// successor edges except for the fall-through edge. If AddEdges is true, 1651 /// i.e., when FromBBI's branch is being moved, add those successor edges to 1652 /// ToBBI. 1653 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) { 1654 assert(!FromBBI.BB->hasAddressTaken() && 1655 "Removing a BB whose address is taken!"); 1656 1657 ToBBI.BB->splice(ToBBI.BB->end(), 1658 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end()); 1659 1660 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(), 1661 FromBBI.BB->succ_end()); 1662 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 1663 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr; 1664 1665 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 1666 MachineBasicBlock *Succ = Succs[i]; 1667 // Fallthrough edge can't be transferred. 1668 if (Succ == FallThrough) 1669 continue; 1670 FromBBI.BB->removeSuccessor(Succ); 1671 if (AddEdges && !ToBBI.BB->isSuccessor(Succ)) 1672 ToBBI.BB->addSuccessor(Succ); 1673 } 1674 1675 // Now FromBBI always falls through to the next block! 1676 if (NBB && !FromBBI.BB->isSuccessor(NBB)) 1677 FromBBI.BB->addSuccessor(NBB); 1678 1679 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end()); 1680 FromBBI.Predicate.clear(); 1681 1682 ToBBI.NonPredSize += FromBBI.NonPredSize; 1683 ToBBI.ExtraCost += FromBBI.ExtraCost; 1684 ToBBI.ExtraCost2 += FromBBI.ExtraCost2; 1685 FromBBI.NonPredSize = 0; 1686 FromBBI.ExtraCost = 0; 1687 FromBBI.ExtraCost2 = 0; 1688 1689 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 1690 ToBBI.HasFallThrough = FromBBI.HasFallThrough; 1691 ToBBI.IsAnalyzed = false; 1692 FromBBI.IsAnalyzed = false; 1693 } 1694