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