1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// 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 // Peephole optimize the CFG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Utils/Local.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/ConstantFolding.h" 22 #include "llvm/Analysis/InstructionSimplify.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Analysis/ValueTracking.h" 25 #include "llvm/IR/CFG.h" 26 #include "llvm/IR/ConstantRange.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/IR/IRBuilder.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/MDBuilder.h" 36 #include "llvm/IR/Metadata.h" 37 #include "llvm/IR/Module.h" 38 #include "llvm/IR/NoFolder.h" 39 #include "llvm/IR/Operator.h" 40 #include "llvm/IR/PatternMatch.h" 41 #include "llvm/IR/Type.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/raw_ostream.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 46 #include "llvm/Transforms/Utils/Local.h" 47 #include <algorithm> 48 #include <map> 49 #include <set> 50 using namespace llvm; 51 using namespace PatternMatch; 52 53 #define DEBUG_TYPE "simplifycfg" 54 55 static cl::opt<unsigned> 56 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1), 57 cl::desc("Control the amount of phi node folding to perform (default = 1)")); 58 59 static cl::opt<bool> 60 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), 61 cl::desc("Duplicate return instructions into unconditional branches")); 62 63 static cl::opt<bool> 64 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), 65 cl::desc("Sink common instructions down to the end block")); 66 67 static cl::opt<bool> HoistCondStores( 68 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), 69 cl::desc("Hoist conditional stores if an unconditional store precedes")); 70 71 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); 72 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables"); 73 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)"); 74 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block"); 75 STATISTIC(NumSpeculations, "Number of speculative executed instructions"); 76 77 namespace { 78 /// ValueEqualityComparisonCase - Represents a case of a switch. 79 struct ValueEqualityComparisonCase { 80 ConstantInt *Value; 81 BasicBlock *Dest; 82 83 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) 84 : Value(Value), Dest(Dest) {} 85 86 bool operator<(ValueEqualityComparisonCase RHS) const { 87 // Comparing pointers is ok as we only rely on the order for uniquing. 88 return Value < RHS.Value; 89 } 90 91 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } 92 }; 93 94 class SimplifyCFGOpt { 95 const TargetTransformInfo &TTI; 96 const DataLayout *const DL; 97 Value *isValueEqualityComparison(TerminatorInst *TI); 98 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI, 99 std::vector<ValueEqualityComparisonCase> &Cases); 100 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, 101 BasicBlock *Pred, 102 IRBuilder<> &Builder); 103 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI, 104 IRBuilder<> &Builder); 105 106 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); 107 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); 108 bool SimplifyUnreachable(UnreachableInst *UI); 109 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); 110 bool SimplifyIndirectBr(IndirectBrInst *IBI); 111 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder); 112 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder); 113 114 public: 115 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout *DL) 116 : TTI(TTI), DL(DL) {} 117 bool run(BasicBlock *BB); 118 }; 119 } 120 121 /// SafeToMergeTerminators - Return true if it is safe to merge these two 122 /// terminator instructions together. 123 /// 124 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { 125 if (SI1 == SI2) return false; // Can't merge with self! 126 127 // It is not safe to merge these two switch instructions if they have a common 128 // successor, and if that successor has a PHI node, and if *that* PHI node has 129 // conflicting incoming values from the two switch blocks. 130 BasicBlock *SI1BB = SI1->getParent(); 131 BasicBlock *SI2BB = SI2->getParent(); 132 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 133 134 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) 135 if (SI1Succs.count(*I)) 136 for (BasicBlock::iterator BBI = (*I)->begin(); 137 isa<PHINode>(BBI); ++BBI) { 138 PHINode *PN = cast<PHINode>(BBI); 139 if (PN->getIncomingValueForBlock(SI1BB) != 140 PN->getIncomingValueForBlock(SI2BB)) 141 return false; 142 } 143 144 return true; 145 } 146 147 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable 148 /// to merge these two terminator instructions together, where SI1 is an 149 /// unconditional branch. PhiNodes will store all PHI nodes in common 150 /// successors. 151 /// 152 static bool isProfitableToFoldUnconditional(BranchInst *SI1, 153 BranchInst *SI2, 154 Instruction *Cond, 155 SmallVectorImpl<PHINode*> &PhiNodes) { 156 if (SI1 == SI2) return false; // Can't merge with self! 157 assert(SI1->isUnconditional() && SI2->isConditional()); 158 159 // We fold the unconditional branch if we can easily update all PHI nodes in 160 // common successors: 161 // 1> We have a constant incoming value for the conditional branch; 162 // 2> We have "Cond" as the incoming value for the unconditional branch; 163 // 3> SI2->getCondition() and Cond have same operands. 164 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); 165 if (!Ci2) return false; 166 if (!(Cond->getOperand(0) == Ci2->getOperand(0) && 167 Cond->getOperand(1) == Ci2->getOperand(1)) && 168 !(Cond->getOperand(0) == Ci2->getOperand(1) && 169 Cond->getOperand(1) == Ci2->getOperand(0))) 170 return false; 171 172 BasicBlock *SI1BB = SI1->getParent(); 173 BasicBlock *SI2BB = SI2->getParent(); 174 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 175 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) 176 if (SI1Succs.count(*I)) 177 for (BasicBlock::iterator BBI = (*I)->begin(); 178 isa<PHINode>(BBI); ++BBI) { 179 PHINode *PN = cast<PHINode>(BBI); 180 if (PN->getIncomingValueForBlock(SI1BB) != Cond || 181 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) 182 return false; 183 PhiNodes.push_back(PN); 184 } 185 return true; 186 } 187 188 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will 189 /// now be entries in it from the 'NewPred' block. The values that will be 190 /// flowing into the PHI nodes will be the same as those coming in from 191 /// ExistPred, an existing predecessor of Succ. 192 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, 193 BasicBlock *ExistPred) { 194 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do 195 196 PHINode *PN; 197 for (BasicBlock::iterator I = Succ->begin(); 198 (PN = dyn_cast<PHINode>(I)); ++I) 199 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred); 200 } 201 202 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the 203 /// given instruction, which is assumed to be safe to speculate. 1 means 204 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive. 205 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) { 206 assert(isSafeToSpeculativelyExecute(I, DL) && 207 "Instruction is not safe to speculatively execute!"); 208 switch (Operator::getOpcode(I)) { 209 default: 210 // In doubt, be conservative. 211 return UINT_MAX; 212 case Instruction::GetElementPtr: 213 // GEPs are cheap if all indices are constant. 214 if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 215 return UINT_MAX; 216 return 1; 217 case Instruction::ExtractValue: 218 case Instruction::Load: 219 case Instruction::Add: 220 case Instruction::Sub: 221 case Instruction::And: 222 case Instruction::Or: 223 case Instruction::Xor: 224 case Instruction::Shl: 225 case Instruction::LShr: 226 case Instruction::AShr: 227 case Instruction::ICmp: 228 case Instruction::Trunc: 229 case Instruction::ZExt: 230 case Instruction::SExt: 231 case Instruction::BitCast: 232 case Instruction::ExtractElement: 233 case Instruction::InsertElement: 234 return 1; // These are all cheap. 235 236 case Instruction::Call: 237 case Instruction::Select: 238 return 2; 239 } 240 } 241 242 /// DominatesMergePoint - If we have a merge point of an "if condition" as 243 /// accepted above, return true if the specified value dominates the block. We 244 /// don't handle the true generality of domination here, just a special case 245 /// which works well enough for us. 246 /// 247 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to 248 /// see if V (which must be an instruction) and its recursive operands 249 /// that do not dominate BB have a combined cost lower than CostRemaining and 250 /// are non-trapping. If both are true, the instruction is inserted into the 251 /// set and true is returned. 252 /// 253 /// The cost for most non-trapping instructions is defined as 1 except for 254 /// Select whose cost is 2. 255 /// 256 /// After this function returns, CostRemaining is decreased by the cost of 257 /// V plus its non-dominating operands. If that cost is greater than 258 /// CostRemaining, false is returned and CostRemaining is undefined. 259 static bool DominatesMergePoint(Value *V, BasicBlock *BB, 260 SmallPtrSetImpl<Instruction*> *AggressiveInsts, 261 unsigned &CostRemaining, 262 const DataLayout *DL) { 263 Instruction *I = dyn_cast<Instruction>(V); 264 if (!I) { 265 // Non-instructions all dominate instructions, but not all constantexprs 266 // can be executed unconditionally. 267 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) 268 if (C->canTrap()) 269 return false; 270 return true; 271 } 272 BasicBlock *PBB = I->getParent(); 273 274 // We don't want to allow weird loops that might have the "if condition" in 275 // the bottom of this block. 276 if (PBB == BB) return false; 277 278 // If this instruction is defined in a block that contains an unconditional 279 // branch to BB, then it must be in the 'conditional' part of the "if 280 // statement". If not, it definitely dominates the region. 281 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); 282 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) 283 return true; 284 285 // If we aren't allowing aggressive promotion anymore, then don't consider 286 // instructions in the 'if region'. 287 if (!AggressiveInsts) return false; 288 289 // If we have seen this instruction before, don't count it again. 290 if (AggressiveInsts->count(I)) return true; 291 292 // Okay, it looks like the instruction IS in the "condition". Check to 293 // see if it's a cheap instruction to unconditionally compute, and if it 294 // only uses stuff defined outside of the condition. If so, hoist it out. 295 if (!isSafeToSpeculativelyExecute(I, DL)) 296 return false; 297 298 unsigned Cost = ComputeSpeculationCost(I, DL); 299 300 if (Cost > CostRemaining) 301 return false; 302 303 CostRemaining -= Cost; 304 305 // Okay, we can only really hoist these out if their operands do 306 // not take us over the cost threshold. 307 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) 308 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL)) 309 return false; 310 // Okay, it's safe to do this! Remember this instruction. 311 AggressiveInsts->insert(I); 312 return true; 313 } 314 315 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr 316 /// and PointerNullValue. Return NULL if value is not a constant int. 317 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) { 318 // Normal constant int. 319 ConstantInt *CI = dyn_cast<ConstantInt>(V); 320 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy()) 321 return CI; 322 323 // This is some kind of pointer constant. Turn it into a pointer-sized 324 // ConstantInt if possible. 325 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType())); 326 327 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). 328 if (isa<ConstantPointerNull>(V)) 329 return ConstantInt::get(PtrTy, 0); 330 331 // IntToPtr const int. 332 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 333 if (CE->getOpcode() == Instruction::IntToPtr) 334 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { 335 // The constant is very likely to have the right type already. 336 if (CI->getType() == PtrTy) 337 return CI; 338 else 339 return cast<ConstantInt> 340 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); 341 } 342 return nullptr; 343 } 344 345 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together 346 /// collection of icmp eq/ne instructions that compare a value against a 347 /// constant, return the value being compared, and stick the constant into the 348 /// Values vector. 349 static Value * 350 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra, 351 const DataLayout *DL, bool isEQ, unsigned &UsedICmps) { 352 Instruction *I = dyn_cast<Instruction>(V); 353 if (!I) return nullptr; 354 355 // If this is an icmp against a constant, handle this as one of the cases. 356 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) { 357 if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) { 358 Value *RHSVal; 359 ConstantInt *RHSC; 360 361 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) { 362 // (x & ~2^x) == y --> x == y || x == y|2^x 363 // This undoes a transformation done by instcombine to fuse 2 compares. 364 if (match(ICI->getOperand(0), 365 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) { 366 APInt Not = ~RHSC->getValue(); 367 if (Not.isPowerOf2()) { 368 Vals.push_back(C); 369 Vals.push_back( 370 ConstantInt::get(C->getContext(), C->getValue() | Not)); 371 UsedICmps++; 372 return RHSVal; 373 } 374 } 375 376 UsedICmps++; 377 Vals.push_back(C); 378 return I->getOperand(0); 379 } 380 381 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to 382 // the set. 383 ConstantRange Span = 384 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue()); 385 386 // Shift the range if the compare is fed by an add. This is the range 387 // compare idiom as emitted by instcombine. 388 bool hasAdd = 389 match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC))); 390 if (hasAdd) 391 Span = Span.subtract(RHSC->getValue()); 392 393 // If this is an and/!= check then we want to optimize "x ugt 2" into 394 // x != 0 && x != 1. 395 if (!isEQ) 396 Span = Span.inverse(); 397 398 // If there are a ton of values, we don't want to make a ginormous switch. 399 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) 400 return nullptr; 401 402 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) 403 Vals.push_back(ConstantInt::get(V->getContext(), Tmp)); 404 UsedICmps++; 405 return hasAdd ? RHSVal : I->getOperand(0); 406 } 407 return nullptr; 408 } 409 410 // Otherwise, we can only handle an | or &, depending on isEQ. 411 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And)) 412 return nullptr; 413 414 unsigned NumValsBeforeLHS = Vals.size(); 415 unsigned UsedICmpsBeforeLHS = UsedICmps; 416 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL, 417 isEQ, UsedICmps)) { 418 unsigned NumVals = Vals.size(); 419 unsigned UsedICmpsBeforeRHS = UsedICmps; 420 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL, 421 isEQ, UsedICmps)) { 422 if (LHS == RHS) 423 return LHS; 424 Vals.resize(NumVals); 425 UsedICmps = UsedICmpsBeforeRHS; 426 } 427 428 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet, 429 // set it and return success. 430 if (Extra == nullptr || Extra == I->getOperand(1)) { 431 Extra = I->getOperand(1); 432 return LHS; 433 } 434 435 Vals.resize(NumValsBeforeLHS); 436 UsedICmps = UsedICmpsBeforeLHS; 437 return nullptr; 438 } 439 440 // If the LHS can't be folded in, but Extra is available and RHS can, try to 441 // use LHS as Extra. 442 if (Extra == nullptr || Extra == I->getOperand(0)) { 443 Value *OldExtra = Extra; 444 Extra = I->getOperand(0); 445 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL, 446 isEQ, UsedICmps)) 447 return RHS; 448 assert(Vals.size() == NumValsBeforeLHS); 449 Extra = OldExtra; 450 } 451 452 return nullptr; 453 } 454 455 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) { 456 Instruction *Cond = nullptr; 457 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 458 Cond = dyn_cast<Instruction>(SI->getCondition()); 459 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 460 if (BI->isConditional()) 461 Cond = dyn_cast<Instruction>(BI->getCondition()); 462 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { 463 Cond = dyn_cast<Instruction>(IBI->getAddress()); 464 } 465 466 TI->eraseFromParent(); 467 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond); 468 } 469 470 /// isValueEqualityComparison - Return true if the specified terminator checks 471 /// to see if a value is equal to constant integer value. 472 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) { 473 Value *CV = nullptr; 474 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 475 // Do not permit merging of large switch instructions into their 476 // predecessors unless there is only one predecessor. 477 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()), 478 pred_end(SI->getParent())) <= 128) 479 CV = SI->getCondition(); 480 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 481 if (BI->isConditional() && BI->getCondition()->hasOneUse()) 482 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) 483 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) 484 CV = ICI->getOperand(0); 485 486 // Unwrap any lossless ptrtoint cast. 487 if (DL && CV) { 488 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { 489 Value *Ptr = PTII->getPointerOperand(); 490 if (PTII->getType() == DL->getIntPtrType(Ptr->getType())) 491 CV = Ptr; 492 } 493 } 494 return CV; 495 } 496 497 /// GetValueEqualityComparisonCases - Given a value comparison instruction, 498 /// decode all of the 'cases' that it represents and return the 'default' block. 499 BasicBlock *SimplifyCFGOpt:: 500 GetValueEqualityComparisonCases(TerminatorInst *TI, 501 std::vector<ValueEqualityComparisonCase> 502 &Cases) { 503 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 504 Cases.reserve(SI->getNumCases()); 505 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i) 506 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(), 507 i.getCaseSuccessor())); 508 return SI->getDefaultDest(); 509 } 510 511 BranchInst *BI = cast<BranchInst>(TI); 512 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 513 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); 514 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1), 515 DL), 516 Succ)); 517 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); 518 } 519 520 521 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries 522 /// in the list that match the specified block. 523 static void EliminateBlockCases(BasicBlock *BB, 524 std::vector<ValueEqualityComparisonCase> &Cases) { 525 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); 526 } 527 528 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as 529 /// well. 530 static bool 531 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, 532 std::vector<ValueEqualityComparisonCase > &C2) { 533 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; 534 535 // Make V1 be smaller than V2. 536 if (V1->size() > V2->size()) 537 std::swap(V1, V2); 538 539 if (V1->size() == 0) return false; 540 if (V1->size() == 1) { 541 // Just scan V2. 542 ConstantInt *TheVal = (*V1)[0].Value; 543 for (unsigned i = 0, e = V2->size(); i != e; ++i) 544 if (TheVal == (*V2)[i].Value) 545 return true; 546 } 547 548 // Otherwise, just sort both lists and compare element by element. 549 array_pod_sort(V1->begin(), V1->end()); 550 array_pod_sort(V2->begin(), V2->end()); 551 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); 552 while (i1 != e1 && i2 != e2) { 553 if ((*V1)[i1].Value == (*V2)[i2].Value) 554 return true; 555 if ((*V1)[i1].Value < (*V2)[i2].Value) 556 ++i1; 557 else 558 ++i2; 559 } 560 return false; 561 } 562 563 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a 564 /// terminator instruction and its block is known to only have a single 565 /// predecessor block, check to see if that predecessor is also a value 566 /// comparison with the same value, and if that comparison determines the 567 /// outcome of this comparison. If so, simplify TI. This does a very limited 568 /// form of jump threading. 569 bool SimplifyCFGOpt:: 570 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, 571 BasicBlock *Pred, 572 IRBuilder<> &Builder) { 573 Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); 574 if (!PredVal) return false; // Not a value comparison in predecessor. 575 576 Value *ThisVal = isValueEqualityComparison(TI); 577 assert(ThisVal && "This isn't a value comparison!!"); 578 if (ThisVal != PredVal) return false; // Different predicates. 579 580 // TODO: Preserve branch weight metadata, similarly to how 581 // FoldValueComparisonIntoPredecessors preserves it. 582 583 // Find out information about when control will move from Pred to TI's block. 584 std::vector<ValueEqualityComparisonCase> PredCases; 585 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), 586 PredCases); 587 EliminateBlockCases(PredDef, PredCases); // Remove default from cases. 588 589 // Find information about how control leaves this block. 590 std::vector<ValueEqualityComparisonCase> ThisCases; 591 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); 592 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. 593 594 // If TI's block is the default block from Pred's comparison, potentially 595 // simplify TI based on this knowledge. 596 if (PredDef == TI->getParent()) { 597 // If we are here, we know that the value is none of those cases listed in 598 // PredCases. If there are any cases in ThisCases that are in PredCases, we 599 // can simplify TI. 600 if (!ValuesOverlap(PredCases, ThisCases)) 601 return false; 602 603 if (isa<BranchInst>(TI)) { 604 // Okay, one of the successors of this condbr is dead. Convert it to a 605 // uncond br. 606 assert(ThisCases.size() == 1 && "Branch can only have one case!"); 607 // Insert the new branch. 608 Instruction *NI = Builder.CreateBr(ThisDef); 609 (void) NI; 610 611 // Remove PHI node entries for the dead edge. 612 ThisCases[0].Dest->removePredecessor(TI->getParent()); 613 614 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 615 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); 616 617 EraseTerminatorInstAndDCECond(TI); 618 return true; 619 } 620 621 SwitchInst *SI = cast<SwitchInst>(TI); 622 // Okay, TI has cases that are statically dead, prune them away. 623 SmallPtrSet<Constant*, 16> DeadCases; 624 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 625 DeadCases.insert(PredCases[i].Value); 626 627 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 628 << "Through successor TI: " << *TI); 629 630 // Collect branch weights into a vector. 631 SmallVector<uint32_t, 8> Weights; 632 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof); 633 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); 634 if (HasWeight) 635 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; 636 ++MD_i) { 637 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i)); 638 assert(CI); 639 Weights.push_back(CI->getValue().getZExtValue()); 640 } 641 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { 642 --i; 643 if (DeadCases.count(i.getCaseValue())) { 644 if (HasWeight) { 645 std::swap(Weights[i.getCaseIndex()+1], Weights.back()); 646 Weights.pop_back(); 647 } 648 i.getCaseSuccessor()->removePredecessor(TI->getParent()); 649 SI->removeCase(i); 650 } 651 } 652 if (HasWeight && Weights.size() >= 2) 653 SI->setMetadata(LLVMContext::MD_prof, 654 MDBuilder(SI->getParent()->getContext()). 655 createBranchWeights(Weights)); 656 657 DEBUG(dbgs() << "Leaving: " << *TI << "\n"); 658 return true; 659 } 660 661 // Otherwise, TI's block must correspond to some matched value. Find out 662 // which value (or set of values) this is. 663 ConstantInt *TIV = nullptr; 664 BasicBlock *TIBB = TI->getParent(); 665 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 666 if (PredCases[i].Dest == TIBB) { 667 if (TIV) 668 return false; // Cannot handle multiple values coming to this block. 669 TIV = PredCases[i].Value; 670 } 671 assert(TIV && "No edge from pred to succ?"); 672 673 // Okay, we found the one constant that our value can be if we get into TI's 674 // BB. Find out which successor will unconditionally be branched to. 675 BasicBlock *TheRealDest = nullptr; 676 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) 677 if (ThisCases[i].Value == TIV) { 678 TheRealDest = ThisCases[i].Dest; 679 break; 680 } 681 682 // If not handled by any explicit cases, it is handled by the default case. 683 if (!TheRealDest) TheRealDest = ThisDef; 684 685 // Remove PHI node entries for dead edges. 686 BasicBlock *CheckEdge = TheRealDest; 687 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) 688 if (*SI != CheckEdge) 689 (*SI)->removePredecessor(TIBB); 690 else 691 CheckEdge = nullptr; 692 693 // Insert the new branch. 694 Instruction *NI = Builder.CreateBr(TheRealDest); 695 (void) NI; 696 697 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 698 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); 699 700 EraseTerminatorInstAndDCECond(TI); 701 return true; 702 } 703 704 namespace { 705 /// ConstantIntOrdering - This class implements a stable ordering of constant 706 /// integers that does not depend on their address. This is important for 707 /// applications that sort ConstantInt's to ensure uniqueness. 708 struct ConstantIntOrdering { 709 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { 710 return LHS->getValue().ult(RHS->getValue()); 711 } 712 }; 713 } 714 715 static int ConstantIntSortPredicate(ConstantInt *const *P1, 716 ConstantInt *const *P2) { 717 const ConstantInt *LHS = *P1; 718 const ConstantInt *RHS = *P2; 719 if (LHS->getValue().ult(RHS->getValue())) 720 return 1; 721 if (LHS->getValue() == RHS->getValue()) 722 return 0; 723 return -1; 724 } 725 726 static inline bool HasBranchWeights(const Instruction* I) { 727 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof); 728 if (ProfMD && ProfMD->getOperand(0)) 729 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) 730 return MDS->getString().equals("branch_weights"); 731 732 return false; 733 } 734 735 /// Get Weights of a given TerminatorInst, the default weight is at the front 736 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight 737 /// metadata. 738 static void GetBranchWeights(TerminatorInst *TI, 739 SmallVectorImpl<uint64_t> &Weights) { 740 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof); 741 assert(MD); 742 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) { 743 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i)); 744 Weights.push_back(CI->getValue().getZExtValue()); 745 } 746 747 // If TI is a conditional eq, the default case is the false case, 748 // and the corresponding branch-weight data is at index 2. We swap the 749 // default weight to be the first entry. 750 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) { 751 assert(Weights.size() == 2); 752 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 753 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 754 std::swap(Weights.front(), Weights.back()); 755 } 756 } 757 758 /// Keep halving the weights until all can fit in uint32_t. 759 static void FitWeights(MutableArrayRef<uint64_t> Weights) { 760 uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); 761 if (Max > UINT_MAX) { 762 unsigned Offset = 32 - countLeadingZeros(Max); 763 for (uint64_t &I : Weights) 764 I >>= Offset; 765 } 766 } 767 768 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value 769 /// equality comparison instruction (either a switch or a branch on "X == c"). 770 /// See if any of the predecessors of the terminator block are value comparisons 771 /// on the same value. If so, and if safe to do so, fold them together. 772 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI, 773 IRBuilder<> &Builder) { 774 BasicBlock *BB = TI->getParent(); 775 Value *CV = isValueEqualityComparison(TI); // CondVal 776 assert(CV && "Not a comparison?"); 777 bool Changed = false; 778 779 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB)); 780 while (!Preds.empty()) { 781 BasicBlock *Pred = Preds.pop_back_val(); 782 783 // See if the predecessor is a comparison with the same value. 784 TerminatorInst *PTI = Pred->getTerminator(); 785 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal 786 787 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { 788 // Figure out which 'cases' to copy from SI to PSI. 789 std::vector<ValueEqualityComparisonCase> BBCases; 790 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); 791 792 std::vector<ValueEqualityComparisonCase> PredCases; 793 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); 794 795 // Based on whether the default edge from PTI goes to BB or not, fill in 796 // PredCases and PredDefault with the new switch cases we would like to 797 // build. 798 SmallVector<BasicBlock*, 8> NewSuccessors; 799 800 // Update the branch weight metadata along the way 801 SmallVector<uint64_t, 8> Weights; 802 bool PredHasWeights = HasBranchWeights(PTI); 803 bool SuccHasWeights = HasBranchWeights(TI); 804 805 if (PredHasWeights) { 806 GetBranchWeights(PTI, Weights); 807 // branch-weight metadata is inconsistent here. 808 if (Weights.size() != 1 + PredCases.size()) 809 PredHasWeights = SuccHasWeights = false; 810 } else if (SuccHasWeights) 811 // If there are no predecessor weights but there are successor weights, 812 // populate Weights with 1, which will later be scaled to the sum of 813 // successor's weights 814 Weights.assign(1 + PredCases.size(), 1); 815 816 SmallVector<uint64_t, 8> SuccWeights; 817 if (SuccHasWeights) { 818 GetBranchWeights(TI, SuccWeights); 819 // branch-weight metadata is inconsistent here. 820 if (SuccWeights.size() != 1 + BBCases.size()) 821 PredHasWeights = SuccHasWeights = false; 822 } else if (PredHasWeights) 823 SuccWeights.assign(1 + BBCases.size(), 1); 824 825 if (PredDefault == BB) { 826 // If this is the default destination from PTI, only the edges in TI 827 // that don't occur in PTI, or that branch to BB will be activated. 828 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; 829 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 830 if (PredCases[i].Dest != BB) 831 PTIHandled.insert(PredCases[i].Value); 832 else { 833 // The default destination is BB, we don't need explicit targets. 834 std::swap(PredCases[i], PredCases.back()); 835 836 if (PredHasWeights || SuccHasWeights) { 837 // Increase weight for the default case. 838 Weights[0] += Weights[i+1]; 839 std::swap(Weights[i+1], Weights.back()); 840 Weights.pop_back(); 841 } 842 843 PredCases.pop_back(); 844 --i; --e; 845 } 846 847 // Reconstruct the new switch statement we will be building. 848 if (PredDefault != BBDefault) { 849 PredDefault->removePredecessor(Pred); 850 PredDefault = BBDefault; 851 NewSuccessors.push_back(BBDefault); 852 } 853 854 unsigned CasesFromPred = Weights.size(); 855 uint64_t ValidTotalSuccWeight = 0; 856 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 857 if (!PTIHandled.count(BBCases[i].Value) && 858 BBCases[i].Dest != BBDefault) { 859 PredCases.push_back(BBCases[i]); 860 NewSuccessors.push_back(BBCases[i].Dest); 861 if (SuccHasWeights || PredHasWeights) { 862 // The default weight is at index 0, so weight for the ith case 863 // should be at index i+1. Scale the cases from successor by 864 // PredDefaultWeight (Weights[0]). 865 Weights.push_back(Weights[0] * SuccWeights[i+1]); 866 ValidTotalSuccWeight += SuccWeights[i+1]; 867 } 868 } 869 870 if (SuccHasWeights || PredHasWeights) { 871 ValidTotalSuccWeight += SuccWeights[0]; 872 // Scale the cases from predecessor by ValidTotalSuccWeight. 873 for (unsigned i = 1; i < CasesFromPred; ++i) 874 Weights[i] *= ValidTotalSuccWeight; 875 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). 876 Weights[0] *= SuccWeights[0]; 877 } 878 } else { 879 // If this is not the default destination from PSI, only the edges 880 // in SI that occur in PSI with a destination of BB will be 881 // activated. 882 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; 883 std::map<ConstantInt*, uint64_t> WeightsForHandled; 884 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 885 if (PredCases[i].Dest == BB) { 886 PTIHandled.insert(PredCases[i].Value); 887 888 if (PredHasWeights || SuccHasWeights) { 889 WeightsForHandled[PredCases[i].Value] = Weights[i+1]; 890 std::swap(Weights[i+1], Weights.back()); 891 Weights.pop_back(); 892 } 893 894 std::swap(PredCases[i], PredCases.back()); 895 PredCases.pop_back(); 896 --i; --e; 897 } 898 899 // Okay, now we know which constants were sent to BB from the 900 // predecessor. Figure out where they will all go now. 901 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 902 if (PTIHandled.count(BBCases[i].Value)) { 903 // If this is one we are capable of getting... 904 if (PredHasWeights || SuccHasWeights) 905 Weights.push_back(WeightsForHandled[BBCases[i].Value]); 906 PredCases.push_back(BBCases[i]); 907 NewSuccessors.push_back(BBCases[i].Dest); 908 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of 909 } 910 911 // If there are any constants vectored to BB that TI doesn't handle, 912 // they must go to the default destination of TI. 913 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I = 914 PTIHandled.begin(), 915 E = PTIHandled.end(); I != E; ++I) { 916 if (PredHasWeights || SuccHasWeights) 917 Weights.push_back(WeightsForHandled[*I]); 918 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault)); 919 NewSuccessors.push_back(BBDefault); 920 } 921 } 922 923 // Okay, at this point, we know which new successor Pred will get. Make 924 // sure we update the number of entries in the PHI nodes for these 925 // successors. 926 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i) 927 AddPredecessorToBlock(NewSuccessors[i], Pred, BB); 928 929 Builder.SetInsertPoint(PTI); 930 // Convert pointer to int before we switch. 931 if (CV->getType()->isPointerTy()) { 932 assert(DL && "Cannot switch on pointer without DataLayout"); 933 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()), 934 "magicptr"); 935 } 936 937 // Now that the successors are updated, create the new Switch instruction. 938 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, 939 PredCases.size()); 940 NewSI->setDebugLoc(PTI->getDebugLoc()); 941 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 942 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest); 943 944 if (PredHasWeights || SuccHasWeights) { 945 // Halve the weights if any of them cannot fit in an uint32_t 946 FitWeights(Weights); 947 948 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 949 950 NewSI->setMetadata(LLVMContext::MD_prof, 951 MDBuilder(BB->getContext()). 952 createBranchWeights(MDWeights)); 953 } 954 955 EraseTerminatorInstAndDCECond(PTI); 956 957 // Okay, last check. If BB is still a successor of PSI, then we must 958 // have an infinite loop case. If so, add an infinitely looping block 959 // to handle the case to preserve the behavior of the code. 960 BasicBlock *InfLoopBlock = nullptr; 961 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) 962 if (NewSI->getSuccessor(i) == BB) { 963 if (!InfLoopBlock) { 964 // Insert it at the end of the function, because it's either code, 965 // or it won't matter if it's hot. :) 966 InfLoopBlock = BasicBlock::Create(BB->getContext(), 967 "infloop", BB->getParent()); 968 BranchInst::Create(InfLoopBlock, InfLoopBlock); 969 } 970 NewSI->setSuccessor(i, InfLoopBlock); 971 } 972 973 Changed = true; 974 } 975 } 976 return Changed; 977 } 978 979 // isSafeToHoistInvoke - If we would need to insert a select that uses the 980 // value of this invoke (comments in HoistThenElseCodeToIf explain why we 981 // would need to do this), we can't hoist the invoke, as there is nowhere 982 // to put the select in this case. 983 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, 984 Instruction *I1, Instruction *I2) { 985 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { 986 PHINode *PN; 987 for (BasicBlock::iterator BBI = SI->begin(); 988 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 989 Value *BB1V = PN->getIncomingValueForBlock(BB1); 990 Value *BB2V = PN->getIncomingValueForBlock(BB2); 991 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) { 992 return false; 993 } 994 } 995 } 996 return true; 997 } 998 999 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and 1000 /// BB2, hoist any common code in the two blocks up into the branch block. The 1001 /// caller of this function guarantees that BI's block dominates BB1 and BB2. 1002 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) { 1003 // This does very trivial matching, with limited scanning, to find identical 1004 // instructions in the two blocks. In particular, we don't want to get into 1005 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As 1006 // such, we currently just scan for obviously identical instructions in an 1007 // identical order. 1008 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. 1009 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination 1010 1011 BasicBlock::iterator BB1_Itr = BB1->begin(); 1012 BasicBlock::iterator BB2_Itr = BB2->begin(); 1013 1014 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++; 1015 // Skip debug info if it is not identical. 1016 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 1017 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 1018 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 1019 while (isa<DbgInfoIntrinsic>(I1)) 1020 I1 = BB1_Itr++; 1021 while (isa<DbgInfoIntrinsic>(I2)) 1022 I2 = BB2_Itr++; 1023 } 1024 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || 1025 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))) 1026 return false; 1027 1028 BasicBlock *BIParent = BI->getParent(); 1029 1030 bool Changed = false; 1031 do { 1032 // If we are hoisting the terminator instruction, don't move one (making a 1033 // broken BB), instead clone it, and remove BI. 1034 if (isa<TerminatorInst>(I1)) 1035 goto HoistTerminator; 1036 1037 // For a normal instruction, we just move one to right before the branch, 1038 // then replace all uses of the other with the first. Finally, we remove 1039 // the now redundant second instruction. 1040 BIParent->getInstList().splice(BI, BB1->getInstList(), I1); 1041 if (!I2->use_empty()) 1042 I2->replaceAllUsesWith(I1); 1043 I1->intersectOptionalDataWith(I2); 1044 unsigned KnownIDs[] = { 1045 LLVMContext::MD_tbaa, 1046 LLVMContext::MD_range, 1047 LLVMContext::MD_fpmath, 1048 LLVMContext::MD_invariant_load 1049 }; 1050 combineMetadata(I1, I2, KnownIDs); 1051 I2->eraseFromParent(); 1052 Changed = true; 1053 1054 I1 = BB1_Itr++; 1055 I2 = BB2_Itr++; 1056 // Skip debug info if it is not identical. 1057 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 1058 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 1059 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 1060 while (isa<DbgInfoIntrinsic>(I1)) 1061 I1 = BB1_Itr++; 1062 while (isa<DbgInfoIntrinsic>(I2)) 1063 I2 = BB2_Itr++; 1064 } 1065 } while (I1->isIdenticalToWhenDefined(I2)); 1066 1067 return true; 1068 1069 HoistTerminator: 1070 // It may not be possible to hoist an invoke. 1071 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) 1072 return Changed; 1073 1074 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { 1075 PHINode *PN; 1076 for (BasicBlock::iterator BBI = SI->begin(); 1077 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 1078 Value *BB1V = PN->getIncomingValueForBlock(BB1); 1079 Value *BB2V = PN->getIncomingValueForBlock(BB2); 1080 if (BB1V == BB2V) 1081 continue; 1082 1083 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL)) 1084 return Changed; 1085 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL)) 1086 return Changed; 1087 } 1088 } 1089 1090 // Okay, it is safe to hoist the terminator. 1091 Instruction *NT = I1->clone(); 1092 BIParent->getInstList().insert(BI, NT); 1093 if (!NT->getType()->isVoidTy()) { 1094 I1->replaceAllUsesWith(NT); 1095 I2->replaceAllUsesWith(NT); 1096 NT->takeName(I1); 1097 } 1098 1099 IRBuilder<true, NoFolder> Builder(NT); 1100 // Hoisting one of the terminators from our successor is a great thing. 1101 // Unfortunately, the successors of the if/else blocks may have PHI nodes in 1102 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI 1103 // nodes, so we insert select instruction to compute the final result. 1104 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; 1105 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { 1106 PHINode *PN; 1107 for (BasicBlock::iterator BBI = SI->begin(); 1108 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 1109 Value *BB1V = PN->getIncomingValueForBlock(BB1); 1110 Value *BB2V = PN->getIncomingValueForBlock(BB2); 1111 if (BB1V == BB2V) continue; 1112 1113 // These values do not agree. Insert a select instruction before NT 1114 // that determines the right value. 1115 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; 1116 if (!SI) 1117 SI = cast<SelectInst> 1118 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, 1119 BB1V->getName()+"."+BB2V->getName())); 1120 1121 // Make the PHI node use the select for all incoming values for BB1/BB2 1122 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1123 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) 1124 PN->setIncomingValue(i, SI); 1125 } 1126 } 1127 1128 // Update any PHI nodes in our new successors. 1129 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) 1130 AddPredecessorToBlock(*SI, BIParent, BB1); 1131 1132 EraseTerminatorInstAndDCECond(BI); 1133 return true; 1134 } 1135 1136 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd, 1137 /// check whether BBEnd has only two predecessors and the other predecessor 1138 /// ends with an unconditional branch. If it is true, sink any common code 1139 /// in the two predecessors to BBEnd. 1140 static bool SinkThenElseCodeToEnd(BranchInst *BI1) { 1141 assert(BI1->isUnconditional()); 1142 BasicBlock *BB1 = BI1->getParent(); 1143 BasicBlock *BBEnd = BI1->getSuccessor(0); 1144 1145 // Check that BBEnd has two predecessors and the other predecessor ends with 1146 // an unconditional branch. 1147 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd); 1148 BasicBlock *Pred0 = *PI++; 1149 if (PI == PE) // Only one predecessor. 1150 return false; 1151 BasicBlock *Pred1 = *PI++; 1152 if (PI != PE) // More than two predecessors. 1153 return false; 1154 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0; 1155 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator()); 1156 if (!BI2 || !BI2->isUnconditional()) 1157 return false; 1158 1159 // Gather the PHI nodes in BBEnd. 1160 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2; 1161 Instruction *FirstNonPhiInBBEnd = nullptr; 1162 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); 1163 I != E; ++I) { 1164 if (PHINode *PN = dyn_cast<PHINode>(I)) { 1165 Value *BB1V = PN->getIncomingValueForBlock(BB1); 1166 Value *BB2V = PN->getIncomingValueForBlock(BB2); 1167 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN); 1168 } else { 1169 FirstNonPhiInBBEnd = &*I; 1170 break; 1171 } 1172 } 1173 if (!FirstNonPhiInBBEnd) 1174 return false; 1175 1176 1177 // This does very trivial matching, with limited scanning, to find identical 1178 // instructions in the two blocks. We scan backward for obviously identical 1179 // instructions in an identical order. 1180 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(), 1181 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(), 1182 RE2 = BB2->getInstList().rend(); 1183 // Skip debug info. 1184 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; 1185 if (RI1 == RE1) 1186 return false; 1187 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; 1188 if (RI2 == RE2) 1189 return false; 1190 // Skip the unconditional branches. 1191 ++RI1; 1192 ++RI2; 1193 1194 bool Changed = false; 1195 while (RI1 != RE1 && RI2 != RE2) { 1196 // Skip debug info. 1197 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; 1198 if (RI1 == RE1) 1199 return Changed; 1200 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; 1201 if (RI2 == RE2) 1202 return Changed; 1203 1204 Instruction *I1 = &*RI1, *I2 = &*RI2; 1205 // I1 and I2 should have a single use in the same PHI node, and they 1206 // perform the same operation. 1207 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 1208 if (isa<PHINode>(I1) || isa<PHINode>(I2) || 1209 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) || 1210 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) || 1211 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) || 1212 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() || 1213 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() || 1214 !I1->hasOneUse() || !I2->hasOneUse() || 1215 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() || 1216 MapValueFromBB1ToBB2[I1].first != I2) 1217 return Changed; 1218 1219 // Check whether we should swap the operands of ICmpInst. 1220 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2); 1221 bool SwapOpnds = false; 1222 if (ICmp1 && ICmp2 && 1223 ICmp1->getOperand(0) != ICmp2->getOperand(0) && 1224 ICmp1->getOperand(1) != ICmp2->getOperand(1) && 1225 (ICmp1->getOperand(0) == ICmp2->getOperand(1) || 1226 ICmp1->getOperand(1) == ICmp2->getOperand(0))) { 1227 ICmp2->swapOperands(); 1228 SwapOpnds = true; 1229 } 1230 if (!I1->isSameOperationAs(I2)) { 1231 if (SwapOpnds) 1232 ICmp2->swapOperands(); 1233 return Changed; 1234 } 1235 1236 // The operands should be either the same or they need to be generated 1237 // with a PHI node after sinking. We only handle the case where there is 1238 // a single pair of different operands. 1239 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr; 1240 unsigned Op1Idx = 0; 1241 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) { 1242 if (I1->getOperand(I) == I2->getOperand(I)) 1243 continue; 1244 // Early exit if we have more-than one pair of different operands or 1245 // the different operand is already in MapValueFromBB1ToBB2. 1246 // Early exit if we need a PHI node to replace a constant. 1247 if (DifferentOp1 || 1248 MapValueFromBB1ToBB2.find(I1->getOperand(I)) != 1249 MapValueFromBB1ToBB2.end() || 1250 isa<Constant>(I1->getOperand(I)) || 1251 isa<Constant>(I2->getOperand(I))) { 1252 // If we can't sink the instructions, undo the swapping. 1253 if (SwapOpnds) 1254 ICmp2->swapOperands(); 1255 return Changed; 1256 } 1257 DifferentOp1 = I1->getOperand(I); 1258 Op1Idx = I; 1259 DifferentOp2 = I2->getOperand(I); 1260 } 1261 1262 // We insert the pair of different operands to MapValueFromBB1ToBB2 and 1263 // remove (I1, I2) from MapValueFromBB1ToBB2. 1264 if (DifferentOp1) { 1265 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2, 1266 DifferentOp1->getName() + ".sink", 1267 BBEnd->begin()); 1268 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN); 1269 // I1 should use NewPN instead of DifferentOp1. 1270 I1->setOperand(Op1Idx, NewPN); 1271 NewPN->addIncoming(DifferentOp1, BB1); 1272 NewPN->addIncoming(DifferentOp2, BB2); 1273 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";); 1274 } 1275 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second; 1276 MapValueFromBB1ToBB2.erase(I1); 1277 1278 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";); 1279 DEBUG(dbgs() << " " << *I2 << "\n";); 1280 // We need to update RE1 and RE2 if we are going to sink the first 1281 // instruction in the basic block down. 1282 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin()); 1283 // Sink the instruction. 1284 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1); 1285 if (!OldPN->use_empty()) 1286 OldPN->replaceAllUsesWith(I1); 1287 OldPN->eraseFromParent(); 1288 1289 if (!I2->use_empty()) 1290 I2->replaceAllUsesWith(I1); 1291 I1->intersectOptionalDataWith(I2); 1292 I2->eraseFromParent(); 1293 1294 if (UpdateRE1) 1295 RE1 = BB1->getInstList().rend(); 1296 if (UpdateRE2) 1297 RE2 = BB2->getInstList().rend(); 1298 FirstNonPhiInBBEnd = I1; 1299 NumSinkCommons++; 1300 Changed = true; 1301 } 1302 return Changed; 1303 } 1304 1305 /// \brief Determine if we can hoist sink a sole store instruction out of a 1306 /// conditional block. 1307 /// 1308 /// We are looking for code like the following: 1309 /// BrBB: 1310 /// store i32 %add, i32* %arrayidx2 1311 /// ... // No other stores or function calls (we could be calling a memory 1312 /// ... // function). 1313 /// %cmp = icmp ult %x, %y 1314 /// br i1 %cmp, label %EndBB, label %ThenBB 1315 /// ThenBB: 1316 /// store i32 %add5, i32* %arrayidx2 1317 /// br label EndBB 1318 /// EndBB: 1319 /// ... 1320 /// We are going to transform this into: 1321 /// BrBB: 1322 /// store i32 %add, i32* %arrayidx2 1323 /// ... // 1324 /// %cmp = icmp ult %x, %y 1325 /// %add.add5 = select i1 %cmp, i32 %add, %add5 1326 /// store i32 %add.add5, i32* %arrayidx2 1327 /// ... 1328 /// 1329 /// \return The pointer to the value of the previous store if the store can be 1330 /// hoisted into the predecessor block. 0 otherwise. 1331 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, 1332 BasicBlock *StoreBB, BasicBlock *EndBB) { 1333 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); 1334 if (!StoreToHoist) 1335 return nullptr; 1336 1337 // Volatile or atomic. 1338 if (!StoreToHoist->isSimple()) 1339 return nullptr; 1340 1341 Value *StorePtr = StoreToHoist->getPointerOperand(); 1342 1343 // Look for a store to the same pointer in BrBB. 1344 unsigned MaxNumInstToLookAt = 10; 1345 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), 1346 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) { 1347 Instruction *CurI = &*RI; 1348 1349 // Could be calling an instruction that effects memory like free(). 1350 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI)) 1351 return nullptr; 1352 1353 StoreInst *SI = dyn_cast<StoreInst>(CurI); 1354 // Found the previous store make sure it stores to the same location. 1355 if (SI && SI->getPointerOperand() == StorePtr) 1356 // Found the previous store, return its value operand. 1357 return SI->getValueOperand(); 1358 else if (SI) 1359 return nullptr; // Unknown store. 1360 } 1361 1362 return nullptr; 1363 } 1364 1365 /// \brief Speculate a conditional basic block flattening the CFG. 1366 /// 1367 /// Note that this is a very risky transform currently. Speculating 1368 /// instructions like this is most often not desirable. Instead, there is an MI 1369 /// pass which can do it with full awareness of the resource constraints. 1370 /// However, some cases are "obvious" and we should do directly. An example of 1371 /// this is speculating a single, reasonably cheap instruction. 1372 /// 1373 /// There is only one distinct advantage to flattening the CFG at the IR level: 1374 /// it makes very common but simplistic optimizations such as are common in 1375 /// instcombine and the DAG combiner more powerful by removing CFG edges and 1376 /// modeling their effects with easier to reason about SSA value graphs. 1377 /// 1378 /// 1379 /// An illustration of this transform is turning this IR: 1380 /// \code 1381 /// BB: 1382 /// %cmp = icmp ult %x, %y 1383 /// br i1 %cmp, label %EndBB, label %ThenBB 1384 /// ThenBB: 1385 /// %sub = sub %x, %y 1386 /// br label BB2 1387 /// EndBB: 1388 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] 1389 /// ... 1390 /// \endcode 1391 /// 1392 /// Into this IR: 1393 /// \code 1394 /// BB: 1395 /// %cmp = icmp ult %x, %y 1396 /// %sub = sub %x, %y 1397 /// %cond = select i1 %cmp, 0, %sub 1398 /// ... 1399 /// \endcode 1400 /// 1401 /// \returns true if the conditional block is removed. 1402 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, 1403 const DataLayout *DL) { 1404 // Be conservative for now. FP select instruction can often be expensive. 1405 Value *BrCond = BI->getCondition(); 1406 if (isa<FCmpInst>(BrCond)) 1407 return false; 1408 1409 BasicBlock *BB = BI->getParent(); 1410 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); 1411 1412 // If ThenBB is actually on the false edge of the conditional branch, remember 1413 // to swap the select operands later. 1414 bool Invert = false; 1415 if (ThenBB != BI->getSuccessor(0)) { 1416 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); 1417 Invert = true; 1418 } 1419 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); 1420 1421 // Keep a count of how many times instructions are used within CondBB when 1422 // they are candidates for sinking into CondBB. Specifically: 1423 // - They are defined in BB, and 1424 // - They have no side effects, and 1425 // - All of their uses are in CondBB. 1426 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; 1427 1428 unsigned SpeculationCost = 0; 1429 Value *SpeculatedStoreValue = nullptr; 1430 StoreInst *SpeculatedStore = nullptr; 1431 for (BasicBlock::iterator BBI = ThenBB->begin(), 1432 BBE = std::prev(ThenBB->end()); 1433 BBI != BBE; ++BBI) { 1434 Instruction *I = BBI; 1435 // Skip debug info. 1436 if (isa<DbgInfoIntrinsic>(I)) 1437 continue; 1438 1439 // Only speculatively execution a single instruction (not counting the 1440 // terminator) for now. 1441 ++SpeculationCost; 1442 if (SpeculationCost > 1) 1443 return false; 1444 1445 // Don't hoist the instruction if it's unsafe or expensive. 1446 if (!isSafeToSpeculativelyExecute(I, DL) && 1447 !(HoistCondStores && 1448 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB, 1449 EndBB)))) 1450 return false; 1451 if (!SpeculatedStoreValue && 1452 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold) 1453 return false; 1454 1455 // Store the store speculation candidate. 1456 if (SpeculatedStoreValue) 1457 SpeculatedStore = cast<StoreInst>(I); 1458 1459 // Do not hoist the instruction if any of its operands are defined but not 1460 // used in BB. The transformation will prevent the operand from 1461 // being sunk into the use block. 1462 for (User::op_iterator i = I->op_begin(), e = I->op_end(); 1463 i != e; ++i) { 1464 Instruction *OpI = dyn_cast<Instruction>(*i); 1465 if (!OpI || OpI->getParent() != BB || 1466 OpI->mayHaveSideEffects()) 1467 continue; // Not a candidate for sinking. 1468 1469 ++SinkCandidateUseCounts[OpI]; 1470 } 1471 } 1472 1473 // Consider any sink candidates which are only used in CondBB as costs for 1474 // speculation. Note, while we iterate over a DenseMap here, we are summing 1475 // and so iteration order isn't significant. 1476 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I = 1477 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end(); 1478 I != E; ++I) 1479 if (I->first->getNumUses() == I->second) { 1480 ++SpeculationCost; 1481 if (SpeculationCost > 1) 1482 return false; 1483 } 1484 1485 // Check that the PHI nodes can be converted to selects. 1486 bool HaveRewritablePHIs = false; 1487 for (BasicBlock::iterator I = EndBB->begin(); 1488 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 1489 Value *OrigV = PN->getIncomingValueForBlock(BB); 1490 Value *ThenV = PN->getIncomingValueForBlock(ThenBB); 1491 1492 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. 1493 // Skip PHIs which are trivial. 1494 if (ThenV == OrigV) 1495 continue; 1496 1497 HaveRewritablePHIs = true; 1498 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); 1499 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); 1500 if (!OrigCE && !ThenCE) 1501 continue; // Known safe and cheap. 1502 1503 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) || 1504 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL))) 1505 return false; 1506 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0; 1507 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0; 1508 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold) 1509 return false; 1510 1511 // Account for the cost of an unfolded ConstantExpr which could end up 1512 // getting expanded into Instructions. 1513 // FIXME: This doesn't account for how many operations are combined in the 1514 // constant expression. 1515 ++SpeculationCost; 1516 if (SpeculationCost > 1) 1517 return false; 1518 } 1519 1520 // If there are no PHIs to process, bail early. This helps ensure idempotence 1521 // as well. 1522 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) 1523 return false; 1524 1525 // If we get here, we can hoist the instruction and if-convert. 1526 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); 1527 1528 // Insert a select of the value of the speculated store. 1529 if (SpeculatedStoreValue) { 1530 IRBuilder<true, NoFolder> Builder(BI); 1531 Value *TrueV = SpeculatedStore->getValueOperand(); 1532 Value *FalseV = SpeculatedStoreValue; 1533 if (Invert) 1534 std::swap(TrueV, FalseV); 1535 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() + 1536 "." + FalseV->getName()); 1537 SpeculatedStore->setOperand(0, S); 1538 } 1539 1540 // Hoist the instructions. 1541 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(), 1542 std::prev(ThenBB->end())); 1543 1544 // Insert selects and rewrite the PHI operands. 1545 IRBuilder<true, NoFolder> Builder(BI); 1546 for (BasicBlock::iterator I = EndBB->begin(); 1547 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 1548 unsigned OrigI = PN->getBasicBlockIndex(BB); 1549 unsigned ThenI = PN->getBasicBlockIndex(ThenBB); 1550 Value *OrigV = PN->getIncomingValue(OrigI); 1551 Value *ThenV = PN->getIncomingValue(ThenI); 1552 1553 // Skip PHIs which are trivial. 1554 if (OrigV == ThenV) 1555 continue; 1556 1557 // Create a select whose true value is the speculatively executed value and 1558 // false value is the preexisting value. Swap them if the branch 1559 // destinations were inverted. 1560 Value *TrueV = ThenV, *FalseV = OrigV; 1561 if (Invert) 1562 std::swap(TrueV, FalseV); 1563 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, 1564 TrueV->getName() + "." + FalseV->getName()); 1565 PN->setIncomingValue(OrigI, V); 1566 PN->setIncomingValue(ThenI, V); 1567 } 1568 1569 ++NumSpeculations; 1570 return true; 1571 } 1572 1573 /// \returns True if this block contains a CallInst with the NoDuplicate 1574 /// attribute. 1575 static bool HasNoDuplicateCall(const BasicBlock *BB) { 1576 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1577 const CallInst *CI = dyn_cast<CallInst>(I); 1578 if (!CI) 1579 continue; 1580 if (CI->cannotDuplicate()) 1581 return true; 1582 } 1583 return false; 1584 } 1585 1586 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch 1587 /// across this block. 1588 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { 1589 BranchInst *BI = cast<BranchInst>(BB->getTerminator()); 1590 unsigned Size = 0; 1591 1592 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 1593 if (isa<DbgInfoIntrinsic>(BBI)) 1594 continue; 1595 if (Size > 10) return false; // Don't clone large BB's. 1596 ++Size; 1597 1598 // We can only support instructions that do not define values that are 1599 // live outside of the current basic block. 1600 for (User *U : BBI->users()) { 1601 Instruction *UI = cast<Instruction>(U); 1602 if (UI->getParent() != BB || isa<PHINode>(UI)) return false; 1603 } 1604 1605 // Looks ok, continue checking. 1606 } 1607 1608 return true; 1609 } 1610 1611 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value 1612 /// that is defined in the same block as the branch and if any PHI entries are 1613 /// constants, thread edges corresponding to that entry to be branches to their 1614 /// ultimate destination. 1615 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) { 1616 BasicBlock *BB = BI->getParent(); 1617 PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); 1618 // NOTE: we currently cannot transform this case if the PHI node is used 1619 // outside of the block. 1620 if (!PN || PN->getParent() != BB || !PN->hasOneUse()) 1621 return false; 1622 1623 // Degenerate case of a single entry PHI. 1624 if (PN->getNumIncomingValues() == 1) { 1625 FoldSingleEntryPHINodes(PN->getParent()); 1626 return true; 1627 } 1628 1629 // Now we know that this block has multiple preds and two succs. 1630 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false; 1631 1632 if (HasNoDuplicateCall(BB)) return false; 1633 1634 // Okay, this is a simple enough basic block. See if any phi values are 1635 // constants. 1636 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1637 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); 1638 if (!CB || !CB->getType()->isIntegerTy(1)) continue; 1639 1640 // Okay, we now know that all edges from PredBB should be revectored to 1641 // branch to RealDest. 1642 BasicBlock *PredBB = PN->getIncomingBlock(i); 1643 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); 1644 1645 if (RealDest == BB) continue; // Skip self loops. 1646 // Skip if the predecessor's terminator is an indirect branch. 1647 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue; 1648 1649 // The dest block might have PHI nodes, other predecessors and other 1650 // difficult cases. Instead of being smart about this, just insert a new 1651 // block that jumps to the destination block, effectively splitting 1652 // the edge we are about to create. 1653 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(), 1654 RealDest->getName()+".critedge", 1655 RealDest->getParent(), RealDest); 1656 BranchInst::Create(RealDest, EdgeBB); 1657 1658 // Update PHI nodes. 1659 AddPredecessorToBlock(RealDest, EdgeBB, BB); 1660 1661 // BB may have instructions that are being threaded over. Clone these 1662 // instructions into EdgeBB. We know that there will be no uses of the 1663 // cloned instructions outside of EdgeBB. 1664 BasicBlock::iterator InsertPt = EdgeBB->begin(); 1665 DenseMap<Value*, Value*> TranslateMap; // Track translated values. 1666 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 1667 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 1668 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); 1669 continue; 1670 } 1671 // Clone the instruction. 1672 Instruction *N = BBI->clone(); 1673 if (BBI->hasName()) N->setName(BBI->getName()+".c"); 1674 1675 // Update operands due to translation. 1676 for (User::op_iterator i = N->op_begin(), e = N->op_end(); 1677 i != e; ++i) { 1678 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i); 1679 if (PI != TranslateMap.end()) 1680 *i = PI->second; 1681 } 1682 1683 // Check for trivial simplification. 1684 if (Value *V = SimplifyInstruction(N, DL)) { 1685 TranslateMap[BBI] = V; 1686 delete N; // Instruction folded away, don't need actual inst 1687 } else { 1688 // Insert the new instruction into its new home. 1689 EdgeBB->getInstList().insert(InsertPt, N); 1690 if (!BBI->use_empty()) 1691 TranslateMap[BBI] = N; 1692 } 1693 } 1694 1695 // Loop over all of the edges from PredBB to BB, changing them to branch 1696 // to EdgeBB instead. 1697 TerminatorInst *PredBBTI = PredBB->getTerminator(); 1698 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) 1699 if (PredBBTI->getSuccessor(i) == BB) { 1700 BB->removePredecessor(PredBB); 1701 PredBBTI->setSuccessor(i, EdgeBB); 1702 } 1703 1704 // Recurse, simplifying any other constants. 1705 return FoldCondBranchOnPHI(BI, DL) | true; 1706 } 1707 1708 return false; 1709 } 1710 1711 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry 1712 /// PHI node, see if we can eliminate it. 1713 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) { 1714 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 1715 // statement", which has a very simple dominance structure. Basically, we 1716 // are trying to find the condition that is being branched on, which 1717 // subsequently causes this merge to happen. We really want control 1718 // dependence information for this check, but simplifycfg can't keep it up 1719 // to date, and this catches most of the cases we care about anyway. 1720 BasicBlock *BB = PN->getParent(); 1721 BasicBlock *IfTrue, *IfFalse; 1722 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); 1723 if (!IfCond || 1724 // Don't bother if the branch will be constant folded trivially. 1725 isa<ConstantInt>(IfCond)) 1726 return false; 1727 1728 // Okay, we found that we can merge this two-entry phi node into a select. 1729 // Doing so would require us to fold *all* two entry phi nodes in this block. 1730 // At some point this becomes non-profitable (particularly if the target 1731 // doesn't support cmov's). Only do this transformation if there are two or 1732 // fewer PHI nodes in this block. 1733 unsigned NumPhis = 0; 1734 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) 1735 if (NumPhis > 2) 1736 return false; 1737 1738 // Loop over the PHI's seeing if we can promote them all to select 1739 // instructions. While we are at it, keep track of the instructions 1740 // that need to be moved to the dominating block. 1741 SmallPtrSet<Instruction*, 4> AggressiveInsts; 1742 unsigned MaxCostVal0 = PHINodeFoldingThreshold, 1743 MaxCostVal1 = PHINodeFoldingThreshold; 1744 1745 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { 1746 PHINode *PN = cast<PHINode>(II++); 1747 if (Value *V = SimplifyInstruction(PN, DL)) { 1748 PN->replaceAllUsesWith(V); 1749 PN->eraseFromParent(); 1750 continue; 1751 } 1752 1753 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts, 1754 MaxCostVal0, DL) || 1755 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts, 1756 MaxCostVal1, DL)) 1757 return false; 1758 } 1759 1760 // If we folded the first phi, PN dangles at this point. Refresh it. If 1761 // we ran out of PHIs then we simplified them all. 1762 PN = dyn_cast<PHINode>(BB->begin()); 1763 if (!PN) return true; 1764 1765 // Don't fold i1 branches on PHIs which contain binary operators. These can 1766 // often be turned into switches and other things. 1767 if (PN->getType()->isIntegerTy(1) && 1768 (isa<BinaryOperator>(PN->getIncomingValue(0)) || 1769 isa<BinaryOperator>(PN->getIncomingValue(1)) || 1770 isa<BinaryOperator>(IfCond))) 1771 return false; 1772 1773 // If we all PHI nodes are promotable, check to make sure that all 1774 // instructions in the predecessor blocks can be promoted as well. If 1775 // not, we won't be able to get rid of the control flow, so it's not 1776 // worth promoting to select instructions. 1777 BasicBlock *DomBlock = nullptr; 1778 BasicBlock *IfBlock1 = PN->getIncomingBlock(0); 1779 BasicBlock *IfBlock2 = PN->getIncomingBlock(1); 1780 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { 1781 IfBlock1 = nullptr; 1782 } else { 1783 DomBlock = *pred_begin(IfBlock1); 1784 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I) 1785 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { 1786 // This is not an aggressive instruction that we can promote. 1787 // Because of this, we won't be able to get rid of the control 1788 // flow, so the xform is not worth it. 1789 return false; 1790 } 1791 } 1792 1793 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { 1794 IfBlock2 = nullptr; 1795 } else { 1796 DomBlock = *pred_begin(IfBlock2); 1797 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I) 1798 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { 1799 // This is not an aggressive instruction that we can promote. 1800 // Because of this, we won't be able to get rid of the control 1801 // flow, so the xform is not worth it. 1802 return false; 1803 } 1804 } 1805 1806 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: " 1807 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); 1808 1809 // If we can still promote the PHI nodes after this gauntlet of tests, 1810 // do all of the PHI's now. 1811 Instruction *InsertPt = DomBlock->getTerminator(); 1812 IRBuilder<true, NoFolder> Builder(InsertPt); 1813 1814 // Move all 'aggressive' instructions, which are defined in the 1815 // conditional parts of the if's up to the dominating block. 1816 if (IfBlock1) 1817 DomBlock->getInstList().splice(InsertPt, 1818 IfBlock1->getInstList(), IfBlock1->begin(), 1819 IfBlock1->getTerminator()); 1820 if (IfBlock2) 1821 DomBlock->getInstList().splice(InsertPt, 1822 IfBlock2->getInstList(), IfBlock2->begin(), 1823 IfBlock2->getTerminator()); 1824 1825 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 1826 // Change the PHI node into a select instruction. 1827 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); 1828 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); 1829 1830 SelectInst *NV = 1831 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, "")); 1832 PN->replaceAllUsesWith(NV); 1833 NV->takeName(PN); 1834 PN->eraseFromParent(); 1835 } 1836 1837 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement 1838 // has been flattened. Change DomBlock to jump directly to our new block to 1839 // avoid other simplifycfg's kicking in on the diamond. 1840 TerminatorInst *OldTI = DomBlock->getTerminator(); 1841 Builder.SetInsertPoint(OldTI); 1842 Builder.CreateBr(BB); 1843 OldTI->eraseFromParent(); 1844 return true; 1845 } 1846 1847 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes 1848 /// to two returning blocks, try to merge them together into one return, 1849 /// introducing a select if the return values disagree. 1850 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, 1851 IRBuilder<> &Builder) { 1852 assert(BI->isConditional() && "Must be a conditional branch"); 1853 BasicBlock *TrueSucc = BI->getSuccessor(0); 1854 BasicBlock *FalseSucc = BI->getSuccessor(1); 1855 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); 1856 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); 1857 1858 // Check to ensure both blocks are empty (just a return) or optionally empty 1859 // with PHI nodes. If there are other instructions, merging would cause extra 1860 // computation on one path or the other. 1861 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) 1862 return false; 1863 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) 1864 return false; 1865 1866 Builder.SetInsertPoint(BI); 1867 // Okay, we found a branch that is going to two return nodes. If 1868 // there is no return value for this function, just change the 1869 // branch into a return. 1870 if (FalseRet->getNumOperands() == 0) { 1871 TrueSucc->removePredecessor(BI->getParent()); 1872 FalseSucc->removePredecessor(BI->getParent()); 1873 Builder.CreateRetVoid(); 1874 EraseTerminatorInstAndDCECond(BI); 1875 return true; 1876 } 1877 1878 // Otherwise, figure out what the true and false return values are 1879 // so we can insert a new select instruction. 1880 Value *TrueValue = TrueRet->getReturnValue(); 1881 Value *FalseValue = FalseRet->getReturnValue(); 1882 1883 // Unwrap any PHI nodes in the return blocks. 1884 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) 1885 if (TVPN->getParent() == TrueSucc) 1886 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); 1887 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) 1888 if (FVPN->getParent() == FalseSucc) 1889 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); 1890 1891 // In order for this transformation to be safe, we must be able to 1892 // unconditionally execute both operands to the return. This is 1893 // normally the case, but we could have a potentially-trapping 1894 // constant expression that prevents this transformation from being 1895 // safe. 1896 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) 1897 if (TCV->canTrap()) 1898 return false; 1899 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) 1900 if (FCV->canTrap()) 1901 return false; 1902 1903 // Okay, we collected all the mapped values and checked them for sanity, and 1904 // defined to really do this transformation. First, update the CFG. 1905 TrueSucc->removePredecessor(BI->getParent()); 1906 FalseSucc->removePredecessor(BI->getParent()); 1907 1908 // Insert select instructions where needed. 1909 Value *BrCond = BI->getCondition(); 1910 if (TrueValue) { 1911 // Insert a select if the results differ. 1912 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { 1913 } else if (isa<UndefValue>(TrueValue)) { 1914 TrueValue = FalseValue; 1915 } else { 1916 TrueValue = Builder.CreateSelect(BrCond, TrueValue, 1917 FalseValue, "retval"); 1918 } 1919 } 1920 1921 Value *RI = !TrueValue ? 1922 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); 1923 1924 (void) RI; 1925 1926 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 1927 << "\n " << *BI << "NewRet = " << *RI 1928 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc); 1929 1930 EraseTerminatorInstAndDCECond(BI); 1931 1932 return true; 1933 } 1934 1935 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the 1936 /// probabilities of the branch taking each edge. Fills in the two APInt 1937 /// parameters and return true, or returns false if no or invalid metadata was 1938 /// found. 1939 static bool ExtractBranchMetadata(BranchInst *BI, 1940 uint64_t &ProbTrue, uint64_t &ProbFalse) { 1941 assert(BI->isConditional() && 1942 "Looking for probabilities on unconditional branch?"); 1943 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof); 1944 if (!ProfileData || ProfileData->getNumOperands() != 3) return false; 1945 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1)); 1946 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2)); 1947 if (!CITrue || !CIFalse) return false; 1948 ProbTrue = CITrue->getValue().getZExtValue(); 1949 ProbFalse = CIFalse->getValue().getZExtValue(); 1950 return true; 1951 } 1952 1953 /// checkCSEInPredecessor - Return true if the given instruction is available 1954 /// in its predecessor block. If yes, the instruction will be removed. 1955 /// 1956 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) { 1957 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) 1958 return false; 1959 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) { 1960 Instruction *PBI = &*I; 1961 // Check whether Inst and PBI generate the same value. 1962 if (Inst->isIdenticalTo(PBI)) { 1963 Inst->replaceAllUsesWith(PBI); 1964 Inst->eraseFromParent(); 1965 return true; 1966 } 1967 } 1968 return false; 1969 } 1970 1971 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a 1972 /// predecessor branches to us and one of our successors, fold the block into 1973 /// the predecessor and use logical operations to pick the right destination. 1974 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL) { 1975 BasicBlock *BB = BI->getParent(); 1976 1977 Instruction *Cond = nullptr; 1978 if (BI->isConditional()) 1979 Cond = dyn_cast<Instruction>(BI->getCondition()); 1980 else { 1981 // For unconditional branch, check for a simple CFG pattern, where 1982 // BB has a single predecessor and BB's successor is also its predecessor's 1983 // successor. If such pattern exisits, check for CSE between BB and its 1984 // predecessor. 1985 if (BasicBlock *PB = BB->getSinglePredecessor()) 1986 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) 1987 if (PBI->isConditional() && 1988 (BI->getSuccessor(0) == PBI->getSuccessor(0) || 1989 BI->getSuccessor(0) == PBI->getSuccessor(1))) { 1990 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); 1991 I != E; ) { 1992 Instruction *Curr = I++; 1993 if (isa<CmpInst>(Curr)) { 1994 Cond = Curr; 1995 break; 1996 } 1997 // Quit if we can't remove this instruction. 1998 if (!checkCSEInPredecessor(Curr, PB)) 1999 return false; 2000 } 2001 } 2002 2003 if (!Cond) 2004 return false; 2005 } 2006 2007 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 2008 Cond->getParent() != BB || !Cond->hasOneUse()) 2009 return false; 2010 2011 // Only allow this if the condition is a simple instruction that can be 2012 // executed unconditionally. It must be in the same block as the branch, and 2013 // must be at the front of the block. 2014 BasicBlock::iterator FrontIt = BB->front(); 2015 2016 // Ignore dbg intrinsics. 2017 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt; 2018 2019 // Allow a single instruction to be hoisted in addition to the compare 2020 // that feeds the branch. We later ensure that any values that _it_ uses 2021 // were also live in the predecessor, so that we don't unnecessarily create 2022 // register pressure or inhibit out-of-order execution. 2023 Instruction *BonusInst = nullptr; 2024 if (&*FrontIt != Cond && 2025 FrontIt->hasOneUse() && FrontIt->user_back() == Cond && 2026 isSafeToSpeculativelyExecute(FrontIt, DL)) { 2027 BonusInst = &*FrontIt; 2028 ++FrontIt; 2029 2030 // Ignore dbg intrinsics. 2031 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt; 2032 } 2033 2034 // Only a single bonus inst is allowed. 2035 if (&*FrontIt != Cond) 2036 return false; 2037 2038 // Make sure the instruction after the condition is the cond branch. 2039 BasicBlock::iterator CondIt = Cond; ++CondIt; 2040 2041 // Ignore dbg intrinsics. 2042 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt; 2043 2044 if (&*CondIt != BI) 2045 return false; 2046 2047 // Cond is known to be a compare or binary operator. Check to make sure that 2048 // neither operand is a potentially-trapping constant expression. 2049 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 2050 if (CE->canTrap()) 2051 return false; 2052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 2053 if (CE->canTrap()) 2054 return false; 2055 2056 // Finally, don't infinitely unroll conditional loops. 2057 BasicBlock *TrueDest = BI->getSuccessor(0); 2058 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; 2059 if (TrueDest == BB || FalseDest == BB) 2060 return false; 2061 2062 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 2063 BasicBlock *PredBlock = *PI; 2064 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 2065 2066 // Check that we have two conditional branches. If there is a PHI node in 2067 // the common successor, verify that the same value flows in from both 2068 // blocks. 2069 SmallVector<PHINode*, 4> PHIs; 2070 if (!PBI || PBI->isUnconditional() || 2071 (BI->isConditional() && 2072 !SafeToMergeTerminators(BI, PBI)) || 2073 (!BI->isConditional() && 2074 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) 2075 continue; 2076 2077 // Determine if the two branches share a common destination. 2078 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; 2079 bool InvertPredCond = false; 2080 2081 if (BI->isConditional()) { 2082 if (PBI->getSuccessor(0) == TrueDest) 2083 Opc = Instruction::Or; 2084 else if (PBI->getSuccessor(1) == FalseDest) 2085 Opc = Instruction::And; 2086 else if (PBI->getSuccessor(0) == FalseDest) 2087 Opc = Instruction::And, InvertPredCond = true; 2088 else if (PBI->getSuccessor(1) == TrueDest) 2089 Opc = Instruction::Or, InvertPredCond = true; 2090 else 2091 continue; 2092 } else { 2093 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) 2094 continue; 2095 } 2096 2097 // Ensure that any values used in the bonus instruction are also used 2098 // by the terminator of the predecessor. This means that those values 2099 // must already have been resolved, so we won't be inhibiting the 2100 // out-of-order core by speculating them earlier. We also allow 2101 // instructions that are used by the terminator's condition because it 2102 // exposes more merging opportunities. 2103 bool UsedByBranch = (BonusInst && BonusInst->hasOneUse() && 2104 BonusInst->user_back() == Cond); 2105 2106 if (BonusInst && !UsedByBranch) { 2107 // Collect the values used by the bonus inst 2108 SmallPtrSet<Value*, 4> UsedValues; 2109 for (Instruction::op_iterator OI = BonusInst->op_begin(), 2110 OE = BonusInst->op_end(); OI != OE; ++OI) { 2111 Value *V = *OI; 2112 if (!isa<Constant>(V) && !isa<Argument>(V)) 2113 UsedValues.insert(V); 2114 } 2115 2116 SmallVector<std::pair<Value*, unsigned>, 4> Worklist; 2117 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0)); 2118 2119 // Walk up to four levels back up the use-def chain of the predecessor's 2120 // terminator to see if all those values were used. The choice of four 2121 // levels is arbitrary, to provide a compile-time-cost bound. 2122 while (!Worklist.empty()) { 2123 std::pair<Value*, unsigned> Pair = Worklist.back(); 2124 Worklist.pop_back(); 2125 2126 if (Pair.second >= 4) continue; 2127 UsedValues.erase(Pair.first); 2128 if (UsedValues.empty()) break; 2129 2130 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) { 2131 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 2132 OI != OE; ++OI) 2133 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1)); 2134 } 2135 } 2136 2137 if (!UsedValues.empty()) return false; 2138 } 2139 2140 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 2141 IRBuilder<> Builder(PBI); 2142 2143 // If we need to invert the condition in the pred block to match, do so now. 2144 if (InvertPredCond) { 2145 Value *NewCond = PBI->getCondition(); 2146 2147 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 2148 CmpInst *CI = cast<CmpInst>(NewCond); 2149 CI->setPredicate(CI->getInversePredicate()); 2150 } else { 2151 NewCond = Builder.CreateNot(NewCond, 2152 PBI->getCondition()->getName()+".not"); 2153 } 2154 2155 PBI->setCondition(NewCond); 2156 PBI->swapSuccessors(); 2157 } 2158 2159 // If we have a bonus inst, clone it into the predecessor block. 2160 Instruction *NewBonus = nullptr; 2161 if (BonusInst) { 2162 NewBonus = BonusInst->clone(); 2163 2164 // If we moved a load, we cannot any longer claim any knowledge about 2165 // its potential value. The previous information might have been valid 2166 // only given the branch precondition. 2167 // For an analogous reason, we must also drop all the metadata whose 2168 // semantics we don't understand. 2169 NewBonus->dropUnknownMetadata(LLVMContext::MD_dbg); 2170 2171 PredBlock->getInstList().insert(PBI, NewBonus); 2172 NewBonus->takeName(BonusInst); 2173 BonusInst->setName(BonusInst->getName()+".old"); 2174 } 2175 2176 // Clone Cond into the predecessor basic block, and or/and the 2177 // two conditions together. 2178 Instruction *New = Cond->clone(); 2179 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus); 2180 PredBlock->getInstList().insert(PBI, New); 2181 New->takeName(Cond); 2182 Cond->setName(New->getName()+".old"); 2183 2184 if (BI->isConditional()) { 2185 Instruction *NewCond = 2186 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(), 2187 New, "or.cond")); 2188 PBI->setCondition(NewCond); 2189 2190 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 2191 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, 2192 PredFalseWeight); 2193 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, 2194 SuccFalseWeight); 2195 SmallVector<uint64_t, 8> NewWeights; 2196 2197 if (PBI->getSuccessor(0) == BB) { 2198 if (PredHasWeights && SuccHasWeights) { 2199 // PBI: br i1 %x, BB, FalseDest 2200 // BI: br i1 %y, TrueDest, FalseDest 2201 //TrueWeight is TrueWeight for PBI * TrueWeight for BI. 2202 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 2203 //FalseWeight is FalseWeight for PBI * TotalWeight for BI + 2204 // TrueWeight for PBI * FalseWeight for BI. 2205 // We assume that total weights of a BranchInst can fit into 32 bits. 2206 // Therefore, we will not have overflow using 64-bit arithmetic. 2207 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight + 2208 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight); 2209 } 2210 AddPredecessorToBlock(TrueDest, PredBlock, BB); 2211 PBI->setSuccessor(0, TrueDest); 2212 } 2213 if (PBI->getSuccessor(1) == BB) { 2214 if (PredHasWeights && SuccHasWeights) { 2215 // PBI: br i1 %x, TrueDest, BB 2216 // BI: br i1 %y, TrueDest, FalseDest 2217 //TrueWeight is TrueWeight for PBI * TotalWeight for BI + 2218 // FalseWeight for PBI * TrueWeight for BI. 2219 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + 2220 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight); 2221 //FalseWeight is FalseWeight for PBI * FalseWeight for BI. 2222 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 2223 } 2224 AddPredecessorToBlock(FalseDest, PredBlock, BB); 2225 PBI->setSuccessor(1, FalseDest); 2226 } 2227 if (NewWeights.size() == 2) { 2228 // Halve the weights if any of them cannot fit in an uint32_t 2229 FitWeights(NewWeights); 2230 2231 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end()); 2232 PBI->setMetadata(LLVMContext::MD_prof, 2233 MDBuilder(BI->getContext()). 2234 createBranchWeights(MDWeights)); 2235 } else 2236 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 2237 } else { 2238 // Update PHI nodes in the common successors. 2239 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { 2240 ConstantInt *PBI_C = cast<ConstantInt>( 2241 PHIs[i]->getIncomingValueForBlock(PBI->getParent())); 2242 assert(PBI_C->getType()->isIntegerTy(1)); 2243 Instruction *MergedCond = nullptr; 2244 if (PBI->getSuccessor(0) == TrueDest) { 2245 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) 2246 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) 2247 // is false: !PBI_Cond and BI_Value 2248 Instruction *NotCond = 2249 cast<Instruction>(Builder.CreateNot(PBI->getCondition(), 2250 "not.cond")); 2251 MergedCond = 2252 cast<Instruction>(Builder.CreateBinOp(Instruction::And, 2253 NotCond, New, 2254 "and.cond")); 2255 if (PBI_C->isOne()) 2256 MergedCond = 2257 cast<Instruction>(Builder.CreateBinOp(Instruction::Or, 2258 PBI->getCondition(), MergedCond, 2259 "or.cond")); 2260 } else { 2261 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) 2262 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) 2263 // is false: PBI_Cond and BI_Value 2264 MergedCond = 2265 cast<Instruction>(Builder.CreateBinOp(Instruction::And, 2266 PBI->getCondition(), New, 2267 "and.cond")); 2268 if (PBI_C->isOne()) { 2269 Instruction *NotCond = 2270 cast<Instruction>(Builder.CreateNot(PBI->getCondition(), 2271 "not.cond")); 2272 MergedCond = 2273 cast<Instruction>(Builder.CreateBinOp(Instruction::Or, 2274 NotCond, MergedCond, 2275 "or.cond")); 2276 } 2277 } 2278 // Update PHI Node. 2279 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()), 2280 MergedCond); 2281 } 2282 // Change PBI from Conditional to Unconditional. 2283 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); 2284 EraseTerminatorInstAndDCECond(PBI); 2285 PBI = New_PBI; 2286 } 2287 2288 // TODO: If BB is reachable from all paths through PredBlock, then we 2289 // could replace PBI's branch probabilities with BI's. 2290 2291 // Copy any debug value intrinsics into the end of PredBlock. 2292 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 2293 if (isa<DbgInfoIntrinsic>(*I)) 2294 I->clone()->insertBefore(PBI); 2295 2296 return true; 2297 } 2298 return false; 2299 } 2300 2301 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a 2302 /// predecessor of another block, this function tries to simplify it. We know 2303 /// that PBI and BI are both conditional branches, and BI is in one of the 2304 /// successor blocks of PBI - PBI branches to BI. 2305 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) { 2306 assert(PBI->isConditional() && BI->isConditional()); 2307 BasicBlock *BB = BI->getParent(); 2308 2309 // If this block ends with a branch instruction, and if there is a 2310 // predecessor that ends on a branch of the same condition, make 2311 // this conditional branch redundant. 2312 if (PBI->getCondition() == BI->getCondition() && 2313 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 2314 // Okay, the outcome of this conditional branch is statically 2315 // knowable. If this block had a single pred, handle specially. 2316 if (BB->getSinglePredecessor()) { 2317 // Turn this into a branch on constant. 2318 bool CondIsTrue = PBI->getSuccessor(0) == BB; 2319 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 2320 CondIsTrue)); 2321 return true; // Nuke the branch on constant. 2322 } 2323 2324 // Otherwise, if there are multiple predecessors, insert a PHI that merges 2325 // in the constant and simplify the block result. Subsequent passes of 2326 // simplifycfg will thread the block. 2327 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 2328 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 2329 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()), 2330 std::distance(PB, PE), 2331 BI->getCondition()->getName() + ".pr", 2332 BB->begin()); 2333 // Okay, we're going to insert the PHI node. Since PBI is not the only 2334 // predecessor, compute the PHI'd conditional value for all of the preds. 2335 // Any predecessor where the condition is not computable we keep symbolic. 2336 for (pred_iterator PI = PB; PI != PE; ++PI) { 2337 BasicBlock *P = *PI; 2338 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && 2339 PBI != BI && PBI->isConditional() && 2340 PBI->getCondition() == BI->getCondition() && 2341 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 2342 bool CondIsTrue = PBI->getSuccessor(0) == BB; 2343 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 2344 CondIsTrue), P); 2345 } else { 2346 NewPN->addIncoming(BI->getCondition(), P); 2347 } 2348 } 2349 2350 BI->setCondition(NewPN); 2351 return true; 2352 } 2353 } 2354 2355 // If this is a conditional branch in an empty block, and if any 2356 // predecessors are a conditional branch to one of our destinations, 2357 // fold the conditions into logical ops and one cond br. 2358 BasicBlock::iterator BBI = BB->begin(); 2359 // Ignore dbg intrinsics. 2360 while (isa<DbgInfoIntrinsic>(BBI)) 2361 ++BBI; 2362 if (&*BBI != BI) 2363 return false; 2364 2365 2366 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 2367 if (CE->canTrap()) 2368 return false; 2369 2370 int PBIOp, BIOp; 2371 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) 2372 PBIOp = BIOp = 0; 2373 else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) 2374 PBIOp = 0, BIOp = 1; 2375 else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) 2376 PBIOp = 1, BIOp = 0; 2377 else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) 2378 PBIOp = BIOp = 1; 2379 else 2380 return false; 2381 2382 // Check to make sure that the other destination of this branch 2383 // isn't BB itself. If so, this is an infinite loop that will 2384 // keep getting unwound. 2385 if (PBI->getSuccessor(PBIOp) == BB) 2386 return false; 2387 2388 // Do not perform this transformation if it would require 2389 // insertion of a large number of select instructions. For targets 2390 // without predication/cmovs, this is a big pessimization. 2391 2392 // Also do not perform this transformation if any phi node in the common 2393 // destination block can trap when reached by BB or PBB (PR17073). In that 2394 // case, it would be unsafe to hoist the operation into a select instruction. 2395 2396 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 2397 unsigned NumPhis = 0; 2398 for (BasicBlock::iterator II = CommonDest->begin(); 2399 isa<PHINode>(II); ++II, ++NumPhis) { 2400 if (NumPhis > 2) // Disable this xform. 2401 return false; 2402 2403 PHINode *PN = cast<PHINode>(II); 2404 Value *BIV = PN->getIncomingValueForBlock(BB); 2405 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 2406 if (CE->canTrap()) 2407 return false; 2408 2409 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 2410 Value *PBIV = PN->getIncomingValue(PBBIdx); 2411 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 2412 if (CE->canTrap()) 2413 return false; 2414 } 2415 2416 // Finally, if everything is ok, fold the branches to logical ops. 2417 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 2418 2419 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 2420 << "AND: " << *BI->getParent()); 2421 2422 2423 // If OtherDest *is* BB, then BB is a basic block with a single conditional 2424 // branch in it, where one edge (OtherDest) goes back to itself but the other 2425 // exits. We don't *know* that the program avoids the infinite loop 2426 // (even though that seems likely). If we do this xform naively, we'll end up 2427 // recursively unpeeling the loop. Since we know that (after the xform is 2428 // done) that the block *is* infinite if reached, we just make it an obviously 2429 // infinite loop with no cond branch. 2430 if (OtherDest == BB) { 2431 // Insert it at the end of the function, because it's either code, 2432 // or it won't matter if it's hot. :) 2433 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(), 2434 "infloop", BB->getParent()); 2435 BranchInst::Create(InfLoopBlock, InfLoopBlock); 2436 OtherDest = InfLoopBlock; 2437 } 2438 2439 DEBUG(dbgs() << *PBI->getParent()->getParent()); 2440 2441 // BI may have other predecessors. Because of this, we leave 2442 // it alone, but modify PBI. 2443 2444 // Make sure we get to CommonDest on True&True directions. 2445 Value *PBICond = PBI->getCondition(); 2446 IRBuilder<true, NoFolder> Builder(PBI); 2447 if (PBIOp) 2448 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not"); 2449 2450 Value *BICond = BI->getCondition(); 2451 if (BIOp) 2452 BICond = Builder.CreateNot(BICond, BICond->getName()+".not"); 2453 2454 // Merge the conditions. 2455 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); 2456 2457 // Modify PBI to branch on the new condition to the new dests. 2458 PBI->setCondition(Cond); 2459 PBI->setSuccessor(0, CommonDest); 2460 PBI->setSuccessor(1, OtherDest); 2461 2462 // Update branch weight for PBI. 2463 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 2464 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, 2465 PredFalseWeight); 2466 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, 2467 SuccFalseWeight); 2468 if (PredHasWeights && SuccHasWeights) { 2469 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 2470 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight; 2471 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 2472 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 2473 // The weight to CommonDest should be PredCommon * SuccTotal + 2474 // PredOther * SuccCommon. 2475 // The weight to OtherDest should be PredOther * SuccOther. 2476 SmallVector<uint64_t, 2> NewWeights; 2477 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) + 2478 PredOther * SuccCommon); 2479 NewWeights.push_back(PredOther * SuccOther); 2480 // Halve the weights if any of them cannot fit in an uint32_t 2481 FitWeights(NewWeights); 2482 2483 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end()); 2484 PBI->setMetadata(LLVMContext::MD_prof, 2485 MDBuilder(BI->getContext()). 2486 createBranchWeights(MDWeights)); 2487 } 2488 2489 // OtherDest may have phi nodes. If so, add an entry from PBI's 2490 // block that are identical to the entries for BI's block. 2491 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 2492 2493 // We know that the CommonDest already had an edge from PBI to 2494 // it. If it has PHIs though, the PHIs may have different 2495 // entries for BB and PBI's BB. If so, insert a select to make 2496 // them agree. 2497 PHINode *PN; 2498 for (BasicBlock::iterator II = CommonDest->begin(); 2499 (PN = dyn_cast<PHINode>(II)); ++II) { 2500 Value *BIV = PN->getIncomingValueForBlock(BB); 2501 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 2502 Value *PBIV = PN->getIncomingValue(PBBIdx); 2503 if (BIV != PBIV) { 2504 // Insert a select in PBI to pick the right value. 2505 Value *NV = cast<SelectInst> 2506 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux")); 2507 PN->setIncomingValue(PBBIdx, NV); 2508 } 2509 } 2510 2511 DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 2512 DEBUG(dbgs() << *PBI->getParent()->getParent()); 2513 2514 // This basic block is probably dead. We know it has at least 2515 // one fewer predecessor. 2516 return true; 2517 } 2518 2519 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a 2520 // branch to TrueBB if Cond is true or to FalseBB if Cond is false. 2521 // Takes care of updating the successors and removing the old terminator. 2522 // Also makes sure not to introduce new successors by assuming that edges to 2523 // non-successor TrueBBs and FalseBBs aren't reachable. 2524 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, 2525 BasicBlock *TrueBB, BasicBlock *FalseBB, 2526 uint32_t TrueWeight, 2527 uint32_t FalseWeight){ 2528 // Remove any superfluous successor edges from the CFG. 2529 // First, figure out which successors to preserve. 2530 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 2531 // successor. 2532 BasicBlock *KeepEdge1 = TrueBB; 2533 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 2534 2535 // Then remove the rest. 2536 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) { 2537 BasicBlock *Succ = OldTerm->getSuccessor(I); 2538 // Make sure only to keep exactly one copy of each edge. 2539 if (Succ == KeepEdge1) 2540 KeepEdge1 = nullptr; 2541 else if (Succ == KeepEdge2) 2542 KeepEdge2 = nullptr; 2543 else 2544 Succ->removePredecessor(OldTerm->getParent()); 2545 } 2546 2547 IRBuilder<> Builder(OldTerm); 2548 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 2549 2550 // Insert an appropriate new terminator. 2551 if (!KeepEdge1 && !KeepEdge2) { 2552 if (TrueBB == FalseBB) 2553 // We were only looking for one successor, and it was present. 2554 // Create an unconditional branch to it. 2555 Builder.CreateBr(TrueBB); 2556 else { 2557 // We found both of the successors we were looking for. 2558 // Create a conditional branch sharing the condition of the select. 2559 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 2560 if (TrueWeight != FalseWeight) 2561 NewBI->setMetadata(LLVMContext::MD_prof, 2562 MDBuilder(OldTerm->getContext()). 2563 createBranchWeights(TrueWeight, FalseWeight)); 2564 } 2565 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 2566 // Neither of the selected blocks were successors, so this 2567 // terminator must be unreachable. 2568 new UnreachableInst(OldTerm->getContext(), OldTerm); 2569 } else { 2570 // One of the selected values was a successor, but the other wasn't. 2571 // Insert an unconditional branch to the one that was found; 2572 // the edge to the one that wasn't must be unreachable. 2573 if (!KeepEdge1) 2574 // Only TrueBB was found. 2575 Builder.CreateBr(TrueBB); 2576 else 2577 // Only FalseBB was found. 2578 Builder.CreateBr(FalseBB); 2579 } 2580 2581 EraseTerminatorInstAndDCECond(OldTerm); 2582 return true; 2583 } 2584 2585 // SimplifySwitchOnSelect - Replaces 2586 // (switch (select cond, X, Y)) on constant X, Y 2587 // with a branch - conditional if X and Y lead to distinct BBs, 2588 // unconditional otherwise. 2589 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { 2590 // Check for constant integer values in the select. 2591 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 2592 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 2593 if (!TrueVal || !FalseVal) 2594 return false; 2595 2596 // Find the relevant condition and destinations. 2597 Value *Condition = Select->getCondition(); 2598 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor(); 2599 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor(); 2600 2601 // Get weight for TrueBB and FalseBB. 2602 uint32_t TrueWeight = 0, FalseWeight = 0; 2603 SmallVector<uint64_t, 8> Weights; 2604 bool HasWeights = HasBranchWeights(SI); 2605 if (HasWeights) { 2606 GetBranchWeights(SI, Weights); 2607 if (Weights.size() == 1 + SI->getNumCases()) { 2608 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal). 2609 getSuccessorIndex()]; 2610 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal). 2611 getSuccessorIndex()]; 2612 } 2613 } 2614 2615 // Perform the actual simplification. 2616 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, 2617 TrueWeight, FalseWeight); 2618 } 2619 2620 // SimplifyIndirectBrOnSelect - Replaces 2621 // (indirectbr (select cond, blockaddress(@fn, BlockA), 2622 // blockaddress(@fn, BlockB))) 2623 // with 2624 // (br cond, BlockA, BlockB). 2625 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { 2626 // Check that both operands of the select are block addresses. 2627 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 2628 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 2629 if (!TBA || !FBA) 2630 return false; 2631 2632 // Extract the actual blocks. 2633 BasicBlock *TrueBB = TBA->getBasicBlock(); 2634 BasicBlock *FalseBB = FBA->getBasicBlock(); 2635 2636 // Perform the actual simplification. 2637 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 2638 0, 0); 2639 } 2640 2641 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp 2642 /// instruction (a seteq/setne with a constant) as the only instruction in a 2643 /// block that ends with an uncond branch. We are looking for a very specific 2644 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 2645 /// this case, we merge the first two "or's of icmp" into a switch, but then the 2646 /// default value goes to an uncond block with a seteq in it, we get something 2647 /// like: 2648 /// 2649 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 2650 /// DEFAULT: 2651 /// %tmp = icmp eq i8 %A, 92 2652 /// br label %end 2653 /// end: 2654 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 2655 /// 2656 /// We prefer to split the edge to 'end' so that there is a true/false entry to 2657 /// the PHI, merging the third icmp into the switch. 2658 static bool TryToSimplifyUncondBranchWithICmpInIt( 2659 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI, 2660 const DataLayout *DL) { 2661 BasicBlock *BB = ICI->getParent(); 2662 2663 // If the block has any PHIs in it or the icmp has multiple uses, it is too 2664 // complex. 2665 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false; 2666 2667 Value *V = ICI->getOperand(0); 2668 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 2669 2670 // The pattern we're looking for is where our only predecessor is a switch on 2671 // 'V' and this block is the default case for the switch. In this case we can 2672 // fold the compared value into the switch to simplify things. 2673 BasicBlock *Pred = BB->getSinglePredecessor(); 2674 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false; 2675 2676 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 2677 if (SI->getCondition() != V) 2678 return false; 2679 2680 // If BB is reachable on a non-default case, then we simply know the value of 2681 // V in this block. Substitute it and constant fold the icmp instruction 2682 // away. 2683 if (SI->getDefaultDest() != BB) { 2684 ConstantInt *VVal = SI->findCaseDest(BB); 2685 assert(VVal && "Should have a unique destination value"); 2686 ICI->setOperand(0, VVal); 2687 2688 if (Value *V = SimplifyInstruction(ICI, DL)) { 2689 ICI->replaceAllUsesWith(V); 2690 ICI->eraseFromParent(); 2691 } 2692 // BB is now empty, so it is likely to simplify away. 2693 return SimplifyCFG(BB, TTI, DL) | true; 2694 } 2695 2696 // Ok, the block is reachable from the default dest. If the constant we're 2697 // comparing exists in one of the other edges, then we can constant fold ICI 2698 // and zap it. 2699 if (SI->findCaseValue(Cst) != SI->case_default()) { 2700 Value *V; 2701 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 2702 V = ConstantInt::getFalse(BB->getContext()); 2703 else 2704 V = ConstantInt::getTrue(BB->getContext()); 2705 2706 ICI->replaceAllUsesWith(V); 2707 ICI->eraseFromParent(); 2708 // BB is now empty, so it is likely to simplify away. 2709 return SimplifyCFG(BB, TTI, DL) | true; 2710 } 2711 2712 // The use of the icmp has to be in the 'end' block, by the only PHI node in 2713 // the block. 2714 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 2715 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 2716 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 2717 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 2718 return false; 2719 2720 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 2721 // true in the PHI. 2722 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 2723 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 2724 2725 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 2726 std::swap(DefaultCst, NewCst); 2727 2728 // Replace ICI (which is used by the PHI for the default value) with true or 2729 // false depending on if it is EQ or NE. 2730 ICI->replaceAllUsesWith(DefaultCst); 2731 ICI->eraseFromParent(); 2732 2733 // Okay, the switch goes to this block on a default value. Add an edge from 2734 // the switch to the merge point on the compared value. 2735 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge", 2736 BB->getParent(), BB); 2737 SmallVector<uint64_t, 8> Weights; 2738 bool HasWeights = HasBranchWeights(SI); 2739 if (HasWeights) { 2740 GetBranchWeights(SI, Weights); 2741 if (Weights.size() == 1 + SI->getNumCases()) { 2742 // Split weight for default case to case for "Cst". 2743 Weights[0] = (Weights[0]+1) >> 1; 2744 Weights.push_back(Weights[0]); 2745 2746 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 2747 SI->setMetadata(LLVMContext::MD_prof, 2748 MDBuilder(SI->getContext()). 2749 createBranchWeights(MDWeights)); 2750 } 2751 } 2752 SI->addCase(Cst, NewBB); 2753 2754 // NewBB branches to the phi block, add the uncond branch and the phi entry. 2755 Builder.SetInsertPoint(NewBB); 2756 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 2757 Builder.CreateBr(SuccBlock); 2758 PHIUse->addIncoming(NewCst, NewBB); 2759 return true; 2760 } 2761 2762 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch. 2763 /// Check to see if it is branching on an or/and chain of icmp instructions, and 2764 /// fold it into a switch instruction if so. 2765 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL, 2766 IRBuilder<> &Builder) { 2767 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 2768 if (!Cond) return false; 2769 2770 2771 // Change br (X == 0 | X == 1), T, F into a switch instruction. 2772 // If this is a bunch of seteq's or'd together, or if it's a bunch of 2773 // 'setne's and'ed together, collect them. 2774 Value *CompVal = nullptr; 2775 std::vector<ConstantInt*> Values; 2776 bool TrueWhenEqual = true; 2777 Value *ExtraCase = nullptr; 2778 unsigned UsedICmps = 0; 2779 2780 if (Cond->getOpcode() == Instruction::Or) { 2781 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true, 2782 UsedICmps); 2783 } else if (Cond->getOpcode() == Instruction::And) { 2784 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false, 2785 UsedICmps); 2786 TrueWhenEqual = false; 2787 } 2788 2789 // If we didn't have a multiply compared value, fail. 2790 if (!CompVal) return false; 2791 2792 // Avoid turning single icmps into a switch. 2793 if (UsedICmps <= 1) 2794 return false; 2795 2796 // There might be duplicate constants in the list, which the switch 2797 // instruction can't handle, remove them now. 2798 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 2799 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 2800 2801 // If Extra was used, we require at least two switch values to do the 2802 // transformation. A switch with one value is just an cond branch. 2803 if (ExtraCase && Values.size() < 2) return false; 2804 2805 // TODO: Preserve branch weight metadata, similarly to how 2806 // FoldValueComparisonIntoPredecessors preserves it. 2807 2808 // Figure out which block is which destination. 2809 BasicBlock *DefaultBB = BI->getSuccessor(1); 2810 BasicBlock *EdgeBB = BI->getSuccessor(0); 2811 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); 2812 2813 BasicBlock *BB = BI->getParent(); 2814 2815 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 2816 << " cases into SWITCH. BB is:\n" << *BB); 2817 2818 // If there are any extra values that couldn't be folded into the switch 2819 // then we evaluate them with an explicit branch first. Split the block 2820 // right before the condbr to handle it. 2821 if (ExtraCase) { 2822 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test"); 2823 // Remove the uncond branch added to the old block. 2824 TerminatorInst *OldTI = BB->getTerminator(); 2825 Builder.SetInsertPoint(OldTI); 2826 2827 if (TrueWhenEqual) 2828 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 2829 else 2830 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 2831 2832 OldTI->eraseFromParent(); 2833 2834 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 2835 // for the edge we just added. 2836 AddPredecessorToBlock(EdgeBB, BB, NewBB); 2837 2838 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 2839 << "\nEXTRABB = " << *BB); 2840 BB = NewBB; 2841 } 2842 2843 Builder.SetInsertPoint(BI); 2844 // Convert pointer to int before we switch. 2845 if (CompVal->getType()->isPointerTy()) { 2846 assert(DL && "Cannot switch on pointer without DataLayout"); 2847 CompVal = Builder.CreatePtrToInt(CompVal, 2848 DL->getIntPtrType(CompVal->getType()), 2849 "magicptr"); 2850 } 2851 2852 // Create the new switch instruction now. 2853 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 2854 2855 // Add all of the 'cases' to the switch instruction. 2856 for (unsigned i = 0, e = Values.size(); i != e; ++i) 2857 New->addCase(Values[i], EdgeBB); 2858 2859 // We added edges from PI to the EdgeBB. As such, if there were any 2860 // PHI nodes in EdgeBB, they need entries to be added corresponding to 2861 // the number of edges added. 2862 for (BasicBlock::iterator BBI = EdgeBB->begin(); 2863 isa<PHINode>(BBI); ++BBI) { 2864 PHINode *PN = cast<PHINode>(BBI); 2865 Value *InVal = PN->getIncomingValueForBlock(BB); 2866 for (unsigned i = 0, e = Values.size()-1; i != e; ++i) 2867 PN->addIncoming(InVal, BB); 2868 } 2869 2870 // Erase the old branch instruction. 2871 EraseTerminatorInstAndDCECond(BI); 2872 2873 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 2874 return true; 2875 } 2876 2877 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 2878 // If this is a trivial landing pad that just continues unwinding the caught 2879 // exception then zap the landing pad, turning its invokes into calls. 2880 BasicBlock *BB = RI->getParent(); 2881 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); 2882 if (RI->getValue() != LPInst) 2883 // Not a landing pad, or the resume is not unwinding the exception that 2884 // caused control to branch here. 2885 return false; 2886 2887 // Check that there are no other instructions except for debug intrinsics. 2888 BasicBlock::iterator I = LPInst, E = RI; 2889 while (++I != E) 2890 if (!isa<DbgInfoIntrinsic>(I)) 2891 return false; 2892 2893 // Turn all invokes that unwind here into calls and delete the basic block. 2894 bool InvokeRequiresTableEntry = false; 2895 bool Changed = false; 2896 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 2897 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator()); 2898 2899 if (II->hasFnAttr(Attribute::UWTable)) { 2900 // Don't remove an `invoke' instruction if the ABI requires an entry into 2901 // the table. 2902 InvokeRequiresTableEntry = true; 2903 continue; 2904 } 2905 2906 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3); 2907 2908 // Insert a call instruction before the invoke. 2909 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II); 2910 Call->takeName(II); 2911 Call->setCallingConv(II->getCallingConv()); 2912 Call->setAttributes(II->getAttributes()); 2913 Call->setDebugLoc(II->getDebugLoc()); 2914 2915 // Anything that used the value produced by the invoke instruction now uses 2916 // the value produced by the call instruction. Note that we do this even 2917 // for void functions and calls with no uses so that the callgraph edge is 2918 // updated. 2919 II->replaceAllUsesWith(Call); 2920 BB->removePredecessor(II->getParent()); 2921 2922 // Insert a branch to the normal destination right before the invoke. 2923 BranchInst::Create(II->getNormalDest(), II); 2924 2925 // Finally, delete the invoke instruction! 2926 II->eraseFromParent(); 2927 Changed = true; 2928 } 2929 2930 if (!InvokeRequiresTableEntry) 2931 // The landingpad is now unreachable. Zap it. 2932 BB->eraseFromParent(); 2933 2934 return Changed; 2935 } 2936 2937 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { 2938 BasicBlock *BB = RI->getParent(); 2939 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false; 2940 2941 // Find predecessors that end with branches. 2942 SmallVector<BasicBlock*, 8> UncondBranchPreds; 2943 SmallVector<BranchInst*, 8> CondBranchPreds; 2944 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 2945 BasicBlock *P = *PI; 2946 TerminatorInst *PTI = P->getTerminator(); 2947 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { 2948 if (BI->isUnconditional()) 2949 UncondBranchPreds.push_back(P); 2950 else 2951 CondBranchPreds.push_back(BI); 2952 } 2953 } 2954 2955 // If we found some, do the transformation! 2956 if (!UncondBranchPreds.empty() && DupRet) { 2957 while (!UncondBranchPreds.empty()) { 2958 BasicBlock *Pred = UncondBranchPreds.pop_back_val(); 2959 DEBUG(dbgs() << "FOLDING: " << *BB 2960 << "INTO UNCOND BRANCH PRED: " << *Pred); 2961 (void)FoldReturnIntoUncondBranch(RI, BB, Pred); 2962 } 2963 2964 // If we eliminated all predecessors of the block, delete the block now. 2965 if (pred_begin(BB) == pred_end(BB)) 2966 // We know there are no successors, so just nuke the block. 2967 BB->eraseFromParent(); 2968 2969 return true; 2970 } 2971 2972 // Check out all of the conditional branches going to this return 2973 // instruction. If any of them just select between returns, change the 2974 // branch itself into a select/return pair. 2975 while (!CondBranchPreds.empty()) { 2976 BranchInst *BI = CondBranchPreds.pop_back_val(); 2977 2978 // Check to see if the non-BB successor is also a return block. 2979 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && 2980 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && 2981 SimplifyCondBranchToTwoReturns(BI, Builder)) 2982 return true; 2983 } 2984 return false; 2985 } 2986 2987 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { 2988 BasicBlock *BB = UI->getParent(); 2989 2990 bool Changed = false; 2991 2992 // If there are any instructions immediately before the unreachable that can 2993 // be removed, do so. 2994 while (UI != BB->begin()) { 2995 BasicBlock::iterator BBI = UI; 2996 --BBI; 2997 // Do not delete instructions that can have side effects which might cause 2998 // the unreachable to not be reachable; specifically, calls and volatile 2999 // operations may have this effect. 3000 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break; 3001 3002 if (BBI->mayHaveSideEffects()) { 3003 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { 3004 if (SI->isVolatile()) 3005 break; 3006 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 3007 if (LI->isVolatile()) 3008 break; 3009 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { 3010 if (RMWI->isVolatile()) 3011 break; 3012 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { 3013 if (CXI->isVolatile()) 3014 break; 3015 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && 3016 !isa<LandingPadInst>(BBI)) { 3017 break; 3018 } 3019 // Note that deleting LandingPad's here is in fact okay, although it 3020 // involves a bit of subtle reasoning. If this inst is a LandingPad, 3021 // all the predecessors of this block will be the unwind edges of Invokes, 3022 // and we can therefore guarantee this block will be erased. 3023 } 3024 3025 // Delete this instruction (any uses are guaranteed to be dead) 3026 if (!BBI->use_empty()) 3027 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 3028 BBI->eraseFromParent(); 3029 Changed = true; 3030 } 3031 3032 // If the unreachable instruction is the first in the block, take a gander 3033 // at all of the predecessors of this instruction, and simplify them. 3034 if (&BB->front() != UI) return Changed; 3035 3036 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB)); 3037 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 3038 TerminatorInst *TI = Preds[i]->getTerminator(); 3039 IRBuilder<> Builder(TI); 3040 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 3041 if (BI->isUnconditional()) { 3042 if (BI->getSuccessor(0) == BB) { 3043 new UnreachableInst(TI->getContext(), TI); 3044 TI->eraseFromParent(); 3045 Changed = true; 3046 } 3047 } else { 3048 if (BI->getSuccessor(0) == BB) { 3049 Builder.CreateBr(BI->getSuccessor(1)); 3050 EraseTerminatorInstAndDCECond(BI); 3051 } else if (BI->getSuccessor(1) == BB) { 3052 Builder.CreateBr(BI->getSuccessor(0)); 3053 EraseTerminatorInstAndDCECond(BI); 3054 Changed = true; 3055 } 3056 } 3057 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 3058 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 3059 i != e; ++i) 3060 if (i.getCaseSuccessor() == BB) { 3061 BB->removePredecessor(SI->getParent()); 3062 SI->removeCase(i); 3063 --i; --e; 3064 Changed = true; 3065 } 3066 // If the default value is unreachable, figure out the most popular 3067 // destination and make it the default. 3068 if (SI->getDefaultDest() == BB) { 3069 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity; 3070 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 3071 i != e; ++i) { 3072 std::pair<unsigned, unsigned> &entry = 3073 Popularity[i.getCaseSuccessor()]; 3074 if (entry.first == 0) { 3075 entry.first = 1; 3076 entry.second = i.getCaseIndex(); 3077 } else { 3078 entry.first++; 3079 } 3080 } 3081 3082 // Find the most popular block. 3083 unsigned MaxPop = 0; 3084 unsigned MaxIndex = 0; 3085 BasicBlock *MaxBlock = nullptr; 3086 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator 3087 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) { 3088 if (I->second.first > MaxPop || 3089 (I->second.first == MaxPop && MaxIndex > I->second.second)) { 3090 MaxPop = I->second.first; 3091 MaxIndex = I->second.second; 3092 MaxBlock = I->first; 3093 } 3094 } 3095 if (MaxBlock) { 3096 // Make this the new default, allowing us to delete any explicit 3097 // edges to it. 3098 SI->setDefaultDest(MaxBlock); 3099 Changed = true; 3100 3101 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from 3102 // it. 3103 if (isa<PHINode>(MaxBlock->begin())) 3104 for (unsigned i = 0; i != MaxPop-1; ++i) 3105 MaxBlock->removePredecessor(SI->getParent()); 3106 3107 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 3108 i != e; ++i) 3109 if (i.getCaseSuccessor() == MaxBlock) { 3110 SI->removeCase(i); 3111 --i; --e; 3112 } 3113 } 3114 } 3115 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { 3116 if (II->getUnwindDest() == BB) { 3117 // Convert the invoke to a call instruction. This would be a good 3118 // place to note that the call does not throw though. 3119 BranchInst *BI = Builder.CreateBr(II->getNormalDest()); 3120 II->removeFromParent(); // Take out of symbol table 3121 3122 // Insert the call now... 3123 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3); 3124 Builder.SetInsertPoint(BI); 3125 CallInst *CI = Builder.CreateCall(II->getCalledValue(), 3126 Args, II->getName()); 3127 CI->setCallingConv(II->getCallingConv()); 3128 CI->setAttributes(II->getAttributes()); 3129 // If the invoke produced a value, the call does now instead. 3130 II->replaceAllUsesWith(CI); 3131 delete II; 3132 Changed = true; 3133 } 3134 } 3135 } 3136 3137 // If this block is now dead, remove it. 3138 if (pred_begin(BB) == pred_end(BB) && 3139 BB != &BB->getParent()->getEntryBlock()) { 3140 // We know there are no successors, so just nuke the block. 3141 BB->eraseFromParent(); 3142 return true; 3143 } 3144 3145 return Changed; 3146 } 3147 3148 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a 3149 /// integer range comparison into a sub, an icmp and a branch. 3150 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { 3151 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 3152 3153 // Make sure all cases point to the same destination and gather the values. 3154 SmallVector<ConstantInt *, 16> Cases; 3155 SwitchInst::CaseIt I = SI->case_begin(); 3156 Cases.push_back(I.getCaseValue()); 3157 SwitchInst::CaseIt PrevI = I++; 3158 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) { 3159 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor()) 3160 return false; 3161 Cases.push_back(I.getCaseValue()); 3162 } 3163 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered"); 3164 3165 // Sort the case values, then check if they form a range we can transform. 3166 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 3167 for (unsigned I = 1, E = Cases.size(); I != E; ++I) { 3168 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1) 3169 return false; 3170 } 3171 3172 Constant *Offset = ConstantExpr::getNeg(Cases.back()); 3173 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()); 3174 3175 Value *Sub = SI->getCondition(); 3176 if (!Offset->isNullValue()) 3177 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off"); 3178 Value *Cmp; 3179 // If NumCases overflowed, then all possible values jump to the successor. 3180 if (NumCases->isNullValue() && SI->getNumCases() != 0) 3181 Cmp = ConstantInt::getTrue(SI->getContext()); 3182 else 3183 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 3184 BranchInst *NewBI = Builder.CreateCondBr( 3185 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest()); 3186 3187 // Update weight for the newly-created conditional branch. 3188 SmallVector<uint64_t, 8> Weights; 3189 bool HasWeights = HasBranchWeights(SI); 3190 if (HasWeights) { 3191 GetBranchWeights(SI, Weights); 3192 if (Weights.size() == 1 + SI->getNumCases()) { 3193 // Combine all weights for the cases to be the true weight of NewBI. 3194 // We assume that the sum of all weights for a Terminator can fit into 32 3195 // bits. 3196 uint32_t NewTrueWeight = 0; 3197 for (unsigned I = 1, E = Weights.size(); I != E; ++I) 3198 NewTrueWeight += (uint32_t)Weights[I]; 3199 NewBI->setMetadata(LLVMContext::MD_prof, 3200 MDBuilder(SI->getContext()). 3201 createBranchWeights(NewTrueWeight, 3202 (uint32_t)Weights[0])); 3203 } 3204 } 3205 3206 // Prune obsolete incoming values off the successor's PHI nodes. 3207 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin(); 3208 isa<PHINode>(BBI); ++BBI) { 3209 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I) 3210 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 3211 } 3212 SI->eraseFromParent(); 3213 3214 return true; 3215 } 3216 3217 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch 3218 /// and use it to remove dead cases. 3219 static bool EliminateDeadSwitchCases(SwitchInst *SI) { 3220 Value *Cond = SI->getCondition(); 3221 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 3222 APInt KnownZero(Bits, 0), KnownOne(Bits, 0); 3223 computeKnownBits(Cond, KnownZero, KnownOne); 3224 3225 // Gather dead cases. 3226 SmallVector<ConstantInt*, 8> DeadCases; 3227 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { 3228 if ((I.getCaseValue()->getValue() & KnownZero) != 0 || 3229 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) { 3230 DeadCases.push_back(I.getCaseValue()); 3231 DEBUG(dbgs() << "SimplifyCFG: switch case '" 3232 << I.getCaseValue() << "' is dead.\n"); 3233 } 3234 } 3235 3236 SmallVector<uint64_t, 8> Weights; 3237 bool HasWeight = HasBranchWeights(SI); 3238 if (HasWeight) { 3239 GetBranchWeights(SI, Weights); 3240 HasWeight = (Weights.size() == 1 + SI->getNumCases()); 3241 } 3242 3243 // Remove dead cases from the switch. 3244 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) { 3245 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]); 3246 assert(Case != SI->case_default() && 3247 "Case was not found. Probably mistake in DeadCases forming."); 3248 if (HasWeight) { 3249 std::swap(Weights[Case.getCaseIndex()+1], Weights.back()); 3250 Weights.pop_back(); 3251 } 3252 3253 // Prune unused values from PHI nodes. 3254 Case.getCaseSuccessor()->removePredecessor(SI->getParent()); 3255 SI->removeCase(Case); 3256 } 3257 if (HasWeight && Weights.size() >= 2) { 3258 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 3259 SI->setMetadata(LLVMContext::MD_prof, 3260 MDBuilder(SI->getParent()->getContext()). 3261 createBranchWeights(MDWeights)); 3262 } 3263 3264 return !DeadCases.empty(); 3265 } 3266 3267 /// FindPHIForConditionForwarding - If BB would be eligible for simplification 3268 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 3269 /// by an unconditional branch), look at the phi node for BB in the successor 3270 /// block and see if the incoming value is equal to CaseValue. If so, return 3271 /// the phi node, and set PhiIndex to BB's index in the phi node. 3272 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 3273 BasicBlock *BB, 3274 int *PhiIndex) { 3275 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 3276 return nullptr; // BB must be empty to be a candidate for simplification. 3277 if (!BB->getSinglePredecessor()) 3278 return nullptr; // BB must be dominated by the switch. 3279 3280 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 3281 if (!Branch || !Branch->isUnconditional()) 3282 return nullptr; // Terminator must be unconditional branch. 3283 3284 BasicBlock *Succ = Branch->getSuccessor(0); 3285 3286 BasicBlock::iterator I = Succ->begin(); 3287 while (PHINode *PHI = dyn_cast<PHINode>(I++)) { 3288 int Idx = PHI->getBasicBlockIndex(BB); 3289 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 3290 3291 Value *InValue = PHI->getIncomingValue(Idx); 3292 if (InValue != CaseValue) continue; 3293 3294 *PhiIndex = Idx; 3295 return PHI; 3296 } 3297 3298 return nullptr; 3299 } 3300 3301 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch 3302 /// instruction to a phi node dominated by the switch, if that would mean that 3303 /// some of the destination blocks of the switch can be folded away. 3304 /// Returns true if a change is made. 3305 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 3306 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap; 3307 ForwardingNodesMap ForwardingNodes; 3308 3309 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { 3310 ConstantInt *CaseValue = I.getCaseValue(); 3311 BasicBlock *CaseDest = I.getCaseSuccessor(); 3312 3313 int PhiIndex; 3314 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest, 3315 &PhiIndex); 3316 if (!PHI) continue; 3317 3318 ForwardingNodes[PHI].push_back(PhiIndex); 3319 } 3320 3321 bool Changed = false; 3322 3323 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(), 3324 E = ForwardingNodes.end(); I != E; ++I) { 3325 PHINode *Phi = I->first; 3326 SmallVectorImpl<int> &Indexes = I->second; 3327 3328 if (Indexes.size() < 2) continue; 3329 3330 for (size_t I = 0, E = Indexes.size(); I != E; ++I) 3331 Phi->setIncomingValue(Indexes[I], SI->getCondition()); 3332 Changed = true; 3333 } 3334 3335 return Changed; 3336 } 3337 3338 /// ValidLookupTableConstant - Return true if the backend will be able to handle 3339 /// initializing an array of constants like C. 3340 static bool ValidLookupTableConstant(Constant *C) { 3341 if (C->isThreadDependent()) 3342 return false; 3343 if (C->isDLLImportDependent()) 3344 return false; 3345 3346 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 3347 return CE->isGEPWithNoNotionalOverIndexing(); 3348 3349 return isa<ConstantFP>(C) || 3350 isa<ConstantInt>(C) || 3351 isa<ConstantPointerNull>(C) || 3352 isa<GlobalValue>(C) || 3353 isa<UndefValue>(C); 3354 } 3355 3356 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up 3357 /// its constant value in ConstantPool, returning 0 if it's not there. 3358 static Constant *LookupConstant(Value *V, 3359 const SmallDenseMap<Value*, Constant*>& ConstantPool) { 3360 if (Constant *C = dyn_cast<Constant>(V)) 3361 return C; 3362 return ConstantPool.lookup(V); 3363 } 3364 3365 /// ConstantFold - Try to fold instruction I into a constant. This works for 3366 /// simple instructions such as binary operations where both operands are 3367 /// constant or can be replaced by constants from the ConstantPool. Returns the 3368 /// resulting constant on success, 0 otherwise. 3369 static Constant * 3370 ConstantFold(Instruction *I, 3371 const SmallDenseMap<Value *, Constant *> &ConstantPool, 3372 const DataLayout *DL) { 3373 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 3374 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 3375 if (!A) 3376 return nullptr; 3377 if (A->isAllOnesValue()) 3378 return LookupConstant(Select->getTrueValue(), ConstantPool); 3379 if (A->isNullValue()) 3380 return LookupConstant(Select->getFalseValue(), ConstantPool); 3381 return nullptr; 3382 } 3383 3384 SmallVector<Constant *, 4> COps; 3385 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 3386 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 3387 COps.push_back(A); 3388 else 3389 return nullptr; 3390 } 3391 3392 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) 3393 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 3394 COps[1], DL); 3395 3396 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL); 3397 } 3398 3399 /// GetCaseResults - Try to determine the resulting constant values in phi nodes 3400 /// at the common destination basic block, *CommonDest, for one of the case 3401 /// destionations CaseDest corresponding to value CaseVal (0 for the default 3402 /// case), of a switch instruction SI. 3403 static bool 3404 GetCaseResults(SwitchInst *SI, 3405 ConstantInt *CaseVal, 3406 BasicBlock *CaseDest, 3407 BasicBlock **CommonDest, 3408 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res, 3409 const DataLayout *DL) { 3410 // The block from which we enter the common destination. 3411 BasicBlock *Pred = SI->getParent(); 3412 3413 // If CaseDest is empty except for some side-effect free instructions through 3414 // which we can constant-propagate the CaseVal, continue to its successor. 3415 SmallDenseMap<Value*, Constant*> ConstantPool; 3416 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 3417 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E; 3418 ++I) { 3419 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) { 3420 // If the terminator is a simple branch, continue to the next block. 3421 if (T->getNumSuccessors() != 1) 3422 return false; 3423 Pred = CaseDest; 3424 CaseDest = T->getSuccessor(0); 3425 } else if (isa<DbgInfoIntrinsic>(I)) { 3426 // Skip debug intrinsic. 3427 continue; 3428 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) { 3429 // Instruction is side-effect free and constant. 3430 ConstantPool.insert(std::make_pair(I, C)); 3431 } else { 3432 break; 3433 } 3434 } 3435 3436 // If we did not have a CommonDest before, use the current one. 3437 if (!*CommonDest) 3438 *CommonDest = CaseDest; 3439 // If the destination isn't the common one, abort. 3440 if (CaseDest != *CommonDest) 3441 return false; 3442 3443 // Get the values for this case from phi nodes in the destination block. 3444 BasicBlock::iterator I = (*CommonDest)->begin(); 3445 while (PHINode *PHI = dyn_cast<PHINode>(I++)) { 3446 int Idx = PHI->getBasicBlockIndex(Pred); 3447 if (Idx == -1) 3448 continue; 3449 3450 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx), 3451 ConstantPool); 3452 if (!ConstVal) 3453 return false; 3454 3455 // Note: If the constant comes from constant-propagating the case value 3456 // through the CaseDest basic block, it will be safe to remove the 3457 // instructions in that block. They cannot be used (except in the phi nodes 3458 // we visit) outside CaseDest, because that block does not dominate its 3459 // successor. If it did, we would not be in this phi node. 3460 3461 // Be conservative about which kinds of constants we support. 3462 if (!ValidLookupTableConstant(ConstVal)) 3463 return false; 3464 3465 Res.push_back(std::make_pair(PHI, ConstVal)); 3466 } 3467 3468 return Res.size() > 0; 3469 } 3470 3471 namespace { 3472 /// SwitchLookupTable - This class represents a lookup table that can be used 3473 /// to replace a switch. 3474 class SwitchLookupTable { 3475 public: 3476 /// SwitchLookupTable - Create a lookup table to use as a switch replacement 3477 /// with the contents of Values, using DefaultValue to fill any holes in the 3478 /// table. 3479 SwitchLookupTable(Module &M, 3480 uint64_t TableSize, 3481 ConstantInt *Offset, 3482 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values, 3483 Constant *DefaultValue, 3484 const DataLayout *DL); 3485 3486 /// BuildLookup - Build instructions with Builder to retrieve the value at 3487 /// the position given by Index in the lookup table. 3488 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 3489 3490 /// WouldFitInRegister - Return true if a table with TableSize elements of 3491 /// type ElementType would fit in a target-legal register. 3492 static bool WouldFitInRegister(const DataLayout *DL, 3493 uint64_t TableSize, 3494 const Type *ElementType); 3495 3496 private: 3497 // Depending on the contents of the table, it can be represented in 3498 // different ways. 3499 enum { 3500 // For tables where each element contains the same value, we just have to 3501 // store that single value and return it for each lookup. 3502 SingleValueKind, 3503 3504 // For small tables with integer elements, we can pack them into a bitmap 3505 // that fits into a target-legal register. Values are retrieved by 3506 // shift and mask operations. 3507 BitMapKind, 3508 3509 // The table is stored as an array of values. Values are retrieved by load 3510 // instructions from the table. 3511 ArrayKind 3512 } Kind; 3513 3514 // For SingleValueKind, this is the single value. 3515 Constant *SingleValue; 3516 3517 // For BitMapKind, this is the bitmap. 3518 ConstantInt *BitMap; 3519 IntegerType *BitMapElementTy; 3520 3521 // For ArrayKind, this is the array. 3522 GlobalVariable *Array; 3523 }; 3524 } 3525 3526 SwitchLookupTable::SwitchLookupTable(Module &M, 3527 uint64_t TableSize, 3528 ConstantInt *Offset, 3529 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values, 3530 Constant *DefaultValue, 3531 const DataLayout *DL) 3532 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr), 3533 Array(nullptr) { 3534 assert(Values.size() && "Can't build lookup table without values!"); 3535 assert(TableSize >= Values.size() && "Can't fit values in table!"); 3536 3537 // If all values in the table are equal, this is that value. 3538 SingleValue = Values.begin()->second; 3539 3540 Type *ValueType = Values.begin()->second->getType(); 3541 3542 // Build up the table contents. 3543 SmallVector<Constant*, 64> TableContents(TableSize); 3544 for (size_t I = 0, E = Values.size(); I != E; ++I) { 3545 ConstantInt *CaseVal = Values[I].first; 3546 Constant *CaseRes = Values[I].second; 3547 assert(CaseRes->getType() == ValueType); 3548 3549 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()) 3550 .getLimitedValue(); 3551 TableContents[Idx] = CaseRes; 3552 3553 if (CaseRes != SingleValue) 3554 SingleValue = nullptr; 3555 } 3556 3557 // Fill in any holes in the table with the default result. 3558 if (Values.size() < TableSize) { 3559 assert(DefaultValue && 3560 "Need a default value to fill the lookup table holes."); 3561 assert(DefaultValue->getType() == ValueType); 3562 for (uint64_t I = 0; I < TableSize; ++I) { 3563 if (!TableContents[I]) 3564 TableContents[I] = DefaultValue; 3565 } 3566 3567 if (DefaultValue != SingleValue) 3568 SingleValue = nullptr; 3569 } 3570 3571 // If each element in the table contains the same value, we only need to store 3572 // that single value. 3573 if (SingleValue) { 3574 Kind = SingleValueKind; 3575 return; 3576 } 3577 3578 // If the type is integer and the table fits in a register, build a bitmap. 3579 if (WouldFitInRegister(DL, TableSize, ValueType)) { 3580 IntegerType *IT = cast<IntegerType>(ValueType); 3581 APInt TableInt(TableSize * IT->getBitWidth(), 0); 3582 for (uint64_t I = TableSize; I > 0; --I) { 3583 TableInt <<= IT->getBitWidth(); 3584 // Insert values into the bitmap. Undef values are set to zero. 3585 if (!isa<UndefValue>(TableContents[I - 1])) { 3586 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 3587 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 3588 } 3589 } 3590 BitMap = ConstantInt::get(M.getContext(), TableInt); 3591 BitMapElementTy = IT; 3592 Kind = BitMapKind; 3593 ++NumBitMaps; 3594 return; 3595 } 3596 3597 // Store the table in an array. 3598 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 3599 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 3600 3601 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true, 3602 GlobalVariable::PrivateLinkage, 3603 Initializer, 3604 "switch.table"); 3605 Array->setUnnamedAddr(true); 3606 Kind = ArrayKind; 3607 } 3608 3609 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 3610 switch (Kind) { 3611 case SingleValueKind: 3612 return SingleValue; 3613 case BitMapKind: { 3614 // Type of the bitmap (e.g. i59). 3615 IntegerType *MapTy = BitMap->getType(); 3616 3617 // Cast Index to the same type as the bitmap. 3618 // Note: The Index is <= the number of elements in the table, so 3619 // truncating it to the width of the bitmask is safe. 3620 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 3621 3622 // Multiply the shift amount by the element width. 3623 ShiftAmt = Builder.CreateMul(ShiftAmt, 3624 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 3625 "switch.shiftamt"); 3626 3627 // Shift down. 3628 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt, 3629 "switch.downshift"); 3630 // Mask off. 3631 return Builder.CreateTrunc(DownShifted, BitMapElementTy, 3632 "switch.masked"); 3633 } 3634 case ArrayKind: { 3635 // Make sure the table index will not overflow when treated as signed. 3636 IntegerType *IT = cast<IntegerType>(Index->getType()); 3637 uint64_t TableSize = Array->getInitializer()->getType() 3638 ->getArrayNumElements(); 3639 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 3640 Index = Builder.CreateZExt(Index, 3641 IntegerType::get(IT->getContext(), 3642 IT->getBitWidth() + 1), 3643 "switch.tableidx.zext"); 3644 3645 Value *GEPIndices[] = { Builder.getInt32(0), Index }; 3646 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices, 3647 "switch.gep"); 3648 return Builder.CreateLoad(GEP, "switch.load"); 3649 } 3650 } 3651 llvm_unreachable("Unknown lookup table kind!"); 3652 } 3653 3654 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL, 3655 uint64_t TableSize, 3656 const Type *ElementType) { 3657 if (!DL) 3658 return false; 3659 const IntegerType *IT = dyn_cast<IntegerType>(ElementType); 3660 if (!IT) 3661 return false; 3662 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 3663 // are <= 15, we could try to narrow the type. 3664 3665 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 3666 if (TableSize >= UINT_MAX/IT->getBitWidth()) 3667 return false; 3668 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth()); 3669 } 3670 3671 /// ShouldBuildLookupTable - Determine whether a lookup table should be built 3672 /// for this switch, based on the number of cases, size of the table and the 3673 /// types of the results. 3674 static bool ShouldBuildLookupTable(SwitchInst *SI, 3675 uint64_t TableSize, 3676 const TargetTransformInfo &TTI, 3677 const DataLayout *DL, 3678 const SmallDenseMap<PHINode*, Type*>& ResultTypes) { 3679 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 3680 return false; // TableSize overflowed, or mul below might overflow. 3681 3682 bool AllTablesFitInRegister = true; 3683 bool HasIllegalType = false; 3684 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(), 3685 E = ResultTypes.end(); I != E; ++I) { 3686 Type *Ty = I->second; 3687 3688 // Saturate this flag to true. 3689 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); 3690 3691 // Saturate this flag to false. 3692 AllTablesFitInRegister = AllTablesFitInRegister && 3693 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 3694 3695 // If both flags saturate, we're done. NOTE: This *only* works with 3696 // saturating flags, and all flags have to saturate first due to the 3697 // non-deterministic behavior of iterating over a dense map. 3698 if (HasIllegalType && !AllTablesFitInRegister) 3699 break; 3700 } 3701 3702 // If each table would fit in a register, we should build it anyway. 3703 if (AllTablesFitInRegister) 3704 return true; 3705 3706 // Don't build a table that doesn't fit in-register if it has illegal types. 3707 if (HasIllegalType) 3708 return false; 3709 3710 // The table density should be at least 40%. This is the same criterion as for 3711 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 3712 // FIXME: Find the best cut-off. 3713 return SI->getNumCases() * 10 >= TableSize * 4; 3714 } 3715 3716 /// SwitchToLookupTable - If the switch is only used to initialize one or more 3717 /// phi nodes in a common successor block with different constant values, 3718 /// replace the switch with lookup tables. 3719 static bool SwitchToLookupTable(SwitchInst *SI, 3720 IRBuilder<> &Builder, 3721 const TargetTransformInfo &TTI, 3722 const DataLayout* DL) { 3723 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 3724 3725 // Only build lookup table when we have a target that supports it. 3726 if (!TTI.shouldBuildLookupTables()) 3727 return false; 3728 3729 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 3730 // split off a dense part and build a lookup table for that. 3731 3732 // FIXME: This creates arrays of GEPs to constant strings, which means each 3733 // GEP needs a runtime relocation in PIC code. We should just build one big 3734 // string and lookup indices into that. 3735 3736 // Ignore switches with less than three cases. Lookup tables will not make them 3737 // faster, so we don't analyze them. 3738 if (SI->getNumCases() < 3) 3739 return false; 3740 3741 // Figure out the corresponding result for each case value and phi node in the 3742 // common destination, as well as the the min and max case values. 3743 assert(SI->case_begin() != SI->case_end()); 3744 SwitchInst::CaseIt CI = SI->case_begin(); 3745 ConstantInt *MinCaseVal = CI.getCaseValue(); 3746 ConstantInt *MaxCaseVal = CI.getCaseValue(); 3747 3748 BasicBlock *CommonDest = nullptr; 3749 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy; 3750 SmallDenseMap<PHINode*, ResultListTy> ResultLists; 3751 SmallDenseMap<PHINode*, Constant*> DefaultResults; 3752 SmallDenseMap<PHINode*, Type*> ResultTypes; 3753 SmallVector<PHINode*, 4> PHIs; 3754 3755 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 3756 ConstantInt *CaseVal = CI.getCaseValue(); 3757 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 3758 MinCaseVal = CaseVal; 3759 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 3760 MaxCaseVal = CaseVal; 3761 3762 // Resulting value at phi nodes for this case value. 3763 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy; 3764 ResultsTy Results; 3765 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest, 3766 Results, DL)) 3767 return false; 3768 3769 // Append the result from this case to the list for each phi. 3770 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) { 3771 if (!ResultLists.count(I->first)) 3772 PHIs.push_back(I->first); 3773 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second)); 3774 } 3775 } 3776 3777 // Keep track of the result types. 3778 for (size_t I = 0, E = PHIs.size(); I != E; ++I) { 3779 PHINode *PHI = PHIs[I]; 3780 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 3781 } 3782 3783 uint64_t NumResults = ResultLists[PHIs[0]].size(); 3784 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 3785 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 3786 bool TableHasHoles = (NumResults < TableSize); 3787 3788 // If the table has holes, we need a constant result for the default case 3789 // or a bitmask that fits in a register. 3790 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList; 3791 bool HasDefaultResults = false; 3792 if (TableHasHoles) { 3793 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(), 3794 &CommonDest, DefaultResultsList, DL); 3795 } 3796 bool NeedMask = (TableHasHoles && !HasDefaultResults); 3797 if (NeedMask) { 3798 // As an extra penalty for the validity test we require more cases. 3799 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 3800 return false; 3801 if (!(DL && DL->fitsInLegalInteger(TableSize))) 3802 return false; 3803 } 3804 3805 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) { 3806 PHINode *PHI = DefaultResultsList[I].first; 3807 Constant *Result = DefaultResultsList[I].second; 3808 DefaultResults[PHI] = Result; 3809 } 3810 3811 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 3812 return false; 3813 3814 // Create the BB that does the lookups. 3815 Module &Mod = *CommonDest->getParent()->getParent(); 3816 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(), 3817 "switch.lookup", 3818 CommonDest->getParent(), 3819 CommonDest); 3820 3821 // Compute the table index value. 3822 Builder.SetInsertPoint(SI); 3823 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 3824 "switch.tableidx"); 3825 3826 // Compute the maximum table size representable by the integer type we are 3827 // switching upon. 3828 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 3829 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 3830 assert(MaxTableSize >= TableSize && 3831 "It is impossible for a switch to have more entries than the max " 3832 "representable value of its input integer type's size."); 3833 3834 // If we have a fully covered lookup table, unconditionally branch to the 3835 // lookup table BB. Otherwise, check if the condition value is within the case 3836 // range. If it is so, branch to the new BB. Otherwise branch to SI's default 3837 // destination. 3838 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize; 3839 if (GeneratingCoveredLookupTable) { 3840 Builder.CreateBr(LookupBB); 3841 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later, 3842 // do not delete PHINodes here. 3843 SI->getDefaultDest()->removePredecessor(SI->getParent(), 3844 true/*DontDeleteUselessPHIs*/); 3845 } else { 3846 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get( 3847 MinCaseVal->getType(), TableSize)); 3848 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 3849 } 3850 3851 // Populate the BB that does the lookups. 3852 Builder.SetInsertPoint(LookupBB); 3853 3854 if (NeedMask) { 3855 // Before doing the lookup we do the hole check. 3856 // The LookupBB is therefore re-purposed to do the hole check 3857 // and we create a new LookupBB. 3858 BasicBlock *MaskBB = LookupBB; 3859 MaskBB->setName("switch.hole_check"); 3860 LookupBB = BasicBlock::Create(Mod.getContext(), 3861 "switch.lookup", 3862 CommonDest->getParent(), 3863 CommonDest); 3864 3865 // Build bitmask; fill in a 1 bit for every case. 3866 APInt MaskInt(TableSize, 0); 3867 APInt One(TableSize, 1); 3868 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 3869 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 3870 uint64_t Idx = (ResultList[I].first->getValue() - 3871 MinCaseVal->getValue()).getLimitedValue(); 3872 MaskInt |= One << Idx; 3873 } 3874 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 3875 3876 // Get the TableIndex'th bit of the bitmask. 3877 // If this bit is 0 (meaning hole) jump to the default destination, 3878 // else continue with table lookup. 3879 IntegerType *MapTy = TableMask->getType(); 3880 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy, 3881 "switch.maskindex"); 3882 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, 3883 "switch.shifted"); 3884 Value *LoBit = Builder.CreateTrunc(Shifted, 3885 Type::getInt1Ty(Mod.getContext()), 3886 "switch.lobit"); 3887 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 3888 3889 Builder.SetInsertPoint(LookupBB); 3890 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); 3891 } 3892 3893 bool ReturnedEarly = false; 3894 for (size_t I = 0, E = PHIs.size(); I != E; ++I) { 3895 PHINode *PHI = PHIs[I]; 3896 3897 // If using a bitmask, use any value to fill the lookup table holes. 3898 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 3899 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI], 3900 DV, DL); 3901 3902 Value *Result = Table.BuildLookup(TableIndex, Builder); 3903 3904 // If the result is used to return immediately from the function, we want to 3905 // do that right here. 3906 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && 3907 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { 3908 Builder.CreateRet(Result); 3909 ReturnedEarly = true; 3910 break; 3911 } 3912 3913 PHI->addIncoming(Result, LookupBB); 3914 } 3915 3916 if (!ReturnedEarly) 3917 Builder.CreateBr(CommonDest); 3918 3919 // Remove the switch. 3920 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 3921 BasicBlock *Succ = SI->getSuccessor(i); 3922 3923 if (Succ == SI->getDefaultDest()) 3924 continue; 3925 Succ->removePredecessor(SI->getParent()); 3926 } 3927 SI->eraseFromParent(); 3928 3929 ++NumLookupTables; 3930 if (NeedMask) 3931 ++NumLookupTablesHoles; 3932 return true; 3933 } 3934 3935 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 3936 BasicBlock *BB = SI->getParent(); 3937 3938 if (isValueEqualityComparison(SI)) { 3939 // If we only have one predecessor, and if it is a branch on this value, 3940 // see if that predecessor totally determines the outcome of this switch. 3941 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 3942 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 3943 return SimplifyCFG(BB, TTI, DL) | true; 3944 3945 Value *Cond = SI->getCondition(); 3946 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 3947 if (SimplifySwitchOnSelect(SI, Select)) 3948 return SimplifyCFG(BB, TTI, DL) | true; 3949 3950 // If the block only contains the switch, see if we can fold the block 3951 // away into any preds. 3952 BasicBlock::iterator BBI = BB->begin(); 3953 // Ignore dbg intrinsics. 3954 while (isa<DbgInfoIntrinsic>(BBI)) 3955 ++BBI; 3956 if (SI == &*BBI) 3957 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 3958 return SimplifyCFG(BB, TTI, DL) | true; 3959 } 3960 3961 // Try to transform the switch into an icmp and a branch. 3962 if (TurnSwitchRangeIntoICmp(SI, Builder)) 3963 return SimplifyCFG(BB, TTI, DL) | true; 3964 3965 // Remove unreachable cases. 3966 if (EliminateDeadSwitchCases(SI)) 3967 return SimplifyCFG(BB, TTI, DL) | true; 3968 3969 if (ForwardSwitchConditionToPHI(SI)) 3970 return SimplifyCFG(BB, TTI, DL) | true; 3971 3972 if (SwitchToLookupTable(SI, Builder, TTI, DL)) 3973 return SimplifyCFG(BB, TTI, DL) | true; 3974 3975 return false; 3976 } 3977 3978 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { 3979 BasicBlock *BB = IBI->getParent(); 3980 bool Changed = false; 3981 3982 // Eliminate redundant destinations. 3983 SmallPtrSet<Value *, 8> Succs; 3984 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 3985 BasicBlock *Dest = IBI->getDestination(i); 3986 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) { 3987 Dest->removePredecessor(BB); 3988 IBI->removeDestination(i); 3989 --i; --e; 3990 Changed = true; 3991 } 3992 } 3993 3994 if (IBI->getNumDestinations() == 0) { 3995 // If the indirectbr has no successors, change it to unreachable. 3996 new UnreachableInst(IBI->getContext(), IBI); 3997 EraseTerminatorInstAndDCECond(IBI); 3998 return true; 3999 } 4000 4001 if (IBI->getNumDestinations() == 1) { 4002 // If the indirectbr has one successor, change it to a direct branch. 4003 BranchInst::Create(IBI->getDestination(0), IBI); 4004 EraseTerminatorInstAndDCECond(IBI); 4005 return true; 4006 } 4007 4008 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 4009 if (SimplifyIndirectBrOnSelect(IBI, SI)) 4010 return SimplifyCFG(BB, TTI, DL) | true; 4011 } 4012 return Changed; 4013 } 4014 4015 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){ 4016 BasicBlock *BB = BI->getParent(); 4017 4018 if (SinkCommon && SinkThenElseCodeToEnd(BI)) 4019 return true; 4020 4021 // If the Terminator is the only non-phi instruction, simplify the block. 4022 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(); 4023 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 4024 TryToSimplifyUncondBranchFromEmptyBlock(BB)) 4025 return true; 4026 4027 // If the only instruction in the block is a seteq/setne comparison 4028 // against a constant, try to simplify the block. 4029 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 4030 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 4031 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 4032 ; 4033 if (I->isTerminator() && 4034 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, DL)) 4035 return true; 4036 } 4037 4038 // If this basic block is ONLY a compare and a branch, and if a predecessor 4039 // branches to us and our successor, fold the comparison into the 4040 // predecessor and use logical operations to update the incoming value 4041 // for PHI nodes in common successor. 4042 if (FoldBranchToCommonDest(BI, DL)) 4043 return SimplifyCFG(BB, TTI, DL) | true; 4044 return false; 4045 } 4046 4047 4048 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 4049 BasicBlock *BB = BI->getParent(); 4050 4051 // Conditional branch 4052 if (isValueEqualityComparison(BI)) { 4053 // If we only have one predecessor, and if it is a branch on this value, 4054 // see if that predecessor totally determines the outcome of this 4055 // switch. 4056 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 4057 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 4058 return SimplifyCFG(BB, TTI, DL) | true; 4059 4060 // This block must be empty, except for the setcond inst, if it exists. 4061 // Ignore dbg intrinsics. 4062 BasicBlock::iterator I = BB->begin(); 4063 // Ignore dbg intrinsics. 4064 while (isa<DbgInfoIntrinsic>(I)) 4065 ++I; 4066 if (&*I == BI) { 4067 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 4068 return SimplifyCFG(BB, TTI, DL) | true; 4069 } else if (&*I == cast<Instruction>(BI->getCondition())){ 4070 ++I; 4071 // Ignore dbg intrinsics. 4072 while (isa<DbgInfoIntrinsic>(I)) 4073 ++I; 4074 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 4075 return SimplifyCFG(BB, TTI, DL) | true; 4076 } 4077 } 4078 4079 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 4080 if (SimplifyBranchOnICmpChain(BI, DL, Builder)) 4081 return true; 4082 4083 // If this basic block is ONLY a compare and a branch, and if a predecessor 4084 // branches to us and one of our successors, fold the comparison into the 4085 // predecessor and use logical operations to pick the right destination. 4086 if (FoldBranchToCommonDest(BI, DL)) 4087 return SimplifyCFG(BB, TTI, DL) | true; 4088 4089 // We have a conditional branch to two blocks that are only reachable 4090 // from BI. We know that the condbr dominates the two blocks, so see if 4091 // there is any identical code in the "then" and "else" blocks. If so, we 4092 // can hoist it up to the branching block. 4093 if (BI->getSuccessor(0)->getSinglePredecessor()) { 4094 if (BI->getSuccessor(1)->getSinglePredecessor()) { 4095 if (HoistThenElseCodeToIf(BI, DL)) 4096 return SimplifyCFG(BB, TTI, DL) | true; 4097 } else { 4098 // If Successor #1 has multiple preds, we may be able to conditionally 4099 // execute Successor #0 if it branches to Successor #1. 4100 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator(); 4101 if (Succ0TI->getNumSuccessors() == 1 && 4102 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 4103 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL)) 4104 return SimplifyCFG(BB, TTI, DL) | true; 4105 } 4106 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 4107 // If Successor #0 has multiple preds, we may be able to conditionally 4108 // execute Successor #1 if it branches to Successor #0. 4109 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator(); 4110 if (Succ1TI->getNumSuccessors() == 1 && 4111 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 4112 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL)) 4113 return SimplifyCFG(BB, TTI, DL) | true; 4114 } 4115 4116 // If this is a branch on a phi node in the current block, thread control 4117 // through this block if any PHI node entries are constants. 4118 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 4119 if (PN->getParent() == BI->getParent()) 4120 if (FoldCondBranchOnPHI(BI, DL)) 4121 return SimplifyCFG(BB, TTI, DL) | true; 4122 4123 // Scan predecessor blocks for conditional branches. 4124 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 4125 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 4126 if (PBI != BI && PBI->isConditional()) 4127 if (SimplifyCondBranchToCondBranch(PBI, BI)) 4128 return SimplifyCFG(BB, TTI, DL) | true; 4129 4130 return false; 4131 } 4132 4133 /// Check if passing a value to an instruction will cause undefined behavior. 4134 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { 4135 Constant *C = dyn_cast<Constant>(V); 4136 if (!C) 4137 return false; 4138 4139 if (I->use_empty()) 4140 return false; 4141 4142 if (C->isNullValue()) { 4143 // Only look at the first use, avoid hurting compile time with long uselists 4144 User *Use = *I->user_begin(); 4145 4146 // Now make sure that there are no instructions in between that can alter 4147 // control flow (eg. calls) 4148 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i) 4149 if (i == I->getParent()->end() || i->mayHaveSideEffects()) 4150 return false; 4151 4152 // Look through GEPs. A load from a GEP derived from NULL is still undefined 4153 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 4154 if (GEP->getPointerOperand() == I) 4155 return passingValueIsAlwaysUndefined(V, GEP); 4156 4157 // Look through bitcasts. 4158 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 4159 return passingValueIsAlwaysUndefined(V, BC); 4160 4161 // Load from null is undefined. 4162 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 4163 if (!LI->isVolatile()) 4164 return LI->getPointerAddressSpace() == 0; 4165 4166 // Store to null is undefined. 4167 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 4168 if (!SI->isVolatile()) 4169 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I; 4170 } 4171 return false; 4172 } 4173 4174 /// If BB has an incoming value that will always trigger undefined behavior 4175 /// (eg. null pointer dereference), remove the branch leading here. 4176 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { 4177 for (BasicBlock::iterator i = BB->begin(); 4178 PHINode *PHI = dyn_cast<PHINode>(i); ++i) 4179 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) 4180 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) { 4181 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator(); 4182 IRBuilder<> Builder(T); 4183 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 4184 BB->removePredecessor(PHI->getIncomingBlock(i)); 4185 // Turn uncoditional branches into unreachables and remove the dead 4186 // destination from conditional branches. 4187 if (BI->isUnconditional()) 4188 Builder.CreateUnreachable(); 4189 else 4190 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) : 4191 BI->getSuccessor(0)); 4192 BI->eraseFromParent(); 4193 return true; 4194 } 4195 // TODO: SwitchInst. 4196 } 4197 4198 return false; 4199 } 4200 4201 bool SimplifyCFGOpt::run(BasicBlock *BB) { 4202 bool Changed = false; 4203 4204 assert(BB && BB->getParent() && "Block not embedded in function!"); 4205 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 4206 4207 // Remove basic blocks that have no predecessors (except the entry block)... 4208 // or that just have themself as a predecessor. These are unreachable. 4209 if ((pred_begin(BB) == pred_end(BB) && 4210 BB != &BB->getParent()->getEntryBlock()) || 4211 BB->getSinglePredecessor() == BB) { 4212 DEBUG(dbgs() << "Removing BB: \n" << *BB); 4213 DeleteDeadBlock(BB); 4214 return true; 4215 } 4216 4217 // Check to see if we can constant propagate this terminator instruction 4218 // away... 4219 Changed |= ConstantFoldTerminator(BB, true); 4220 4221 // Check for and eliminate duplicate PHI nodes in this block. 4222 Changed |= EliminateDuplicatePHINodes(BB); 4223 4224 // Check for and remove branches that will always cause undefined behavior. 4225 Changed |= removeUndefIntroducingPredecessor(BB); 4226 4227 // Merge basic blocks into their predecessor if there is only one distinct 4228 // pred, and if there is only one distinct successor of the predecessor, and 4229 // if there are no PHI nodes. 4230 // 4231 if (MergeBlockIntoPredecessor(BB)) 4232 return true; 4233 4234 IRBuilder<> Builder(BB); 4235 4236 // If there is a trivial two-entry PHI node in this basic block, and we can 4237 // eliminate it, do so now. 4238 if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) 4239 if (PN->getNumIncomingValues() == 2) 4240 Changed |= FoldTwoEntryPHINode(PN, DL); 4241 4242 Builder.SetInsertPoint(BB->getTerminator()); 4243 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 4244 if (BI->isUnconditional()) { 4245 if (SimplifyUncondBranch(BI, Builder)) return true; 4246 } else { 4247 if (SimplifyCondBranch(BI, Builder)) return true; 4248 } 4249 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 4250 if (SimplifyReturn(RI, Builder)) return true; 4251 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { 4252 if (SimplifyResume(RI, Builder)) return true; 4253 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 4254 if (SimplifySwitch(SI, Builder)) return true; 4255 } else if (UnreachableInst *UI = 4256 dyn_cast<UnreachableInst>(BB->getTerminator())) { 4257 if (SimplifyUnreachable(UI)) return true; 4258 } else if (IndirectBrInst *IBI = 4259 dyn_cast<IndirectBrInst>(BB->getTerminator())) { 4260 if (SimplifyIndirectBr(IBI)) return true; 4261 } 4262 4263 return Changed; 4264 } 4265 4266 /// SimplifyCFG - This function is used to do simplification of a CFG. For 4267 /// example, it adjusts branches to branches to eliminate the extra hop, it 4268 /// eliminates unreachable basic blocks, and does other "peephole" optimization 4269 /// of the CFG. It returns true if a modification was made. 4270 /// 4271 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 4272 const DataLayout *DL) { 4273 return SimplifyCFGOpt(TTI, DL).run(BB); 4274 } 4275