LLVM API Documentation
00001 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // Peephole optimize the CFG. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #define DEBUG_TYPE "simplifycfg" 00015 #include "llvm/Transforms/Utils/Local.h" 00016 #include "llvm/ADT/DenseMap.h" 00017 #include "llvm/ADT/STLExtras.h" 00018 #include "llvm/ADT/SetVector.h" 00019 #include "llvm/ADT/SmallPtrSet.h" 00020 #include "llvm/ADT/SmallVector.h" 00021 #include "llvm/ADT/Statistic.h" 00022 #include "llvm/Analysis/InstructionSimplify.h" 00023 #include "llvm/Analysis/TargetTransformInfo.h" 00024 #include "llvm/Analysis/ValueTracking.h" 00025 #include "llvm/IR/Constants.h" 00026 #include "llvm/IR/DataLayout.h" 00027 #include "llvm/IR/DerivedTypes.h" 00028 #include "llvm/IR/GlobalVariable.h" 00029 #include "llvm/IR/IRBuilder.h" 00030 #include "llvm/IR/Instructions.h" 00031 #include "llvm/IR/IntrinsicInst.h" 00032 #include "llvm/IR/LLVMContext.h" 00033 #include "llvm/IR/MDBuilder.h" 00034 #include "llvm/IR/Metadata.h" 00035 #include "llvm/IR/Module.h" 00036 #include "llvm/IR/Operator.h" 00037 #include "llvm/IR/Type.h" 00038 #include "llvm/Support/CFG.h" 00039 #include "llvm/Support/CommandLine.h" 00040 #include "llvm/Support/ConstantRange.h" 00041 #include "llvm/Support/Debug.h" 00042 #include "llvm/Support/NoFolder.h" 00043 #include "llvm/Support/raw_ostream.h" 00044 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00045 #include <algorithm> 00046 #include <map> 00047 #include <set> 00048 using namespace llvm; 00049 00050 static cl::opt<unsigned> 00051 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1), 00052 cl::desc("Control the amount of phi node folding to perform (default = 1)")); 00053 00054 static cl::opt<bool> 00055 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), 00056 cl::desc("Duplicate return instructions into unconditional branches")); 00057 00058 static cl::opt<bool> 00059 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), 00060 cl::desc("Sink common instructions down to the end block")); 00061 00062 static cl::opt<bool> 00063 HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), 00064 cl::desc("Hoist conditional stores if an unconditional store preceeds")); 00065 00066 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); 00067 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables"); 00068 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block"); 00069 STATISTIC(NumSpeculations, "Number of speculative executed instructions"); 00070 00071 namespace { 00072 /// ValueEqualityComparisonCase - Represents a case of a switch. 00073 struct ValueEqualityComparisonCase { 00074 ConstantInt *Value; 00075 BasicBlock *Dest; 00076 00077 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) 00078 : Value(Value), Dest(Dest) {} 00079 00080 bool operator<(ValueEqualityComparisonCase RHS) const { 00081 // Comparing pointers is ok as we only rely on the order for uniquing. 00082 return Value < RHS.Value; 00083 } 00084 00085 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } 00086 }; 00087 00088 class SimplifyCFGOpt { 00089 const TargetTransformInfo &TTI; 00090 const DataLayout *const TD; 00091 00092 Value *isValueEqualityComparison(TerminatorInst *TI); 00093 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI, 00094 std::vector<ValueEqualityComparisonCase> &Cases); 00095 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, 00096 BasicBlock *Pred, 00097 IRBuilder<> &Builder); 00098 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI, 00099 IRBuilder<> &Builder); 00100 00101 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); 00102 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); 00103 bool SimplifyUnreachable(UnreachableInst *UI); 00104 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); 00105 bool SimplifyIndirectBr(IndirectBrInst *IBI); 00106 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder); 00107 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder); 00108 00109 public: 00110 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout *TD) 00111 : TTI(TTI), TD(TD) {} 00112 bool run(BasicBlock *BB); 00113 }; 00114 } 00115 00116 /// SafeToMergeTerminators - Return true if it is safe to merge these two 00117 /// terminator instructions together. 00118 /// 00119 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { 00120 if (SI1 == SI2) return false; // Can't merge with self! 00121 00122 // It is not safe to merge these two switch instructions if they have a common 00123 // successor, and if that successor has a PHI node, and if *that* PHI node has 00124 // conflicting incoming values from the two switch blocks. 00125 BasicBlock *SI1BB = SI1->getParent(); 00126 BasicBlock *SI2BB = SI2->getParent(); 00127 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 00128 00129 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) 00130 if (SI1Succs.count(*I)) 00131 for (BasicBlock::iterator BBI = (*I)->begin(); 00132 isa<PHINode>(BBI); ++BBI) { 00133 PHINode *PN = cast<PHINode>(BBI); 00134 if (PN->getIncomingValueForBlock(SI1BB) != 00135 PN->getIncomingValueForBlock(SI2BB)) 00136 return false; 00137 } 00138 00139 return true; 00140 } 00141 00142 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable 00143 /// to merge these two terminator instructions together, where SI1 is an 00144 /// unconditional branch. PhiNodes will store all PHI nodes in common 00145 /// successors. 00146 /// 00147 static bool isProfitableToFoldUnconditional(BranchInst *SI1, 00148 BranchInst *SI2, 00149 Instruction *Cond, 00150 SmallVectorImpl<PHINode*> &PhiNodes) { 00151 if (SI1 == SI2) return false; // Can't merge with self! 00152 assert(SI1->isUnconditional() && SI2->isConditional()); 00153 00154 // We fold the unconditional branch if we can easily update all PHI nodes in 00155 // common successors: 00156 // 1> We have a constant incoming value for the conditional branch; 00157 // 2> We have "Cond" as the incoming value for the unconditional branch; 00158 // 3> SI2->getCondition() and Cond have same operands. 00159 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); 00160 if (!Ci2) return false; 00161 if (!(Cond->getOperand(0) == Ci2->getOperand(0) && 00162 Cond->getOperand(1) == Ci2->getOperand(1)) && 00163 !(Cond->getOperand(0) == Ci2->getOperand(1) && 00164 Cond->getOperand(1) == Ci2->getOperand(0))) 00165 return false; 00166 00167 BasicBlock *SI1BB = SI1->getParent(); 00168 BasicBlock *SI2BB = SI2->getParent(); 00169 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 00170 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) 00171 if (SI1Succs.count(*I)) 00172 for (BasicBlock::iterator BBI = (*I)->begin(); 00173 isa<PHINode>(BBI); ++BBI) { 00174 PHINode *PN = cast<PHINode>(BBI); 00175 if (PN->getIncomingValueForBlock(SI1BB) != Cond || 00176 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) 00177 return false; 00178 PhiNodes.push_back(PN); 00179 } 00180 return true; 00181 } 00182 00183 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will 00184 /// now be entries in it from the 'NewPred' block. The values that will be 00185 /// flowing into the PHI nodes will be the same as those coming in from 00186 /// ExistPred, an existing predecessor of Succ. 00187 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, 00188 BasicBlock *ExistPred) { 00189 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do 00190 00191 PHINode *PN; 00192 for (BasicBlock::iterator I = Succ->begin(); 00193 (PN = dyn_cast<PHINode>(I)); ++I) 00194 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred); 00195 } 00196 00197 00198 /// GetIfCondition - Given a basic block (BB) with two predecessors (and at 00199 /// least one PHI node in it), check to see if the merge at this block is due 00200 /// to an "if condition". If so, return the boolean condition that determines 00201 /// which entry into BB will be taken. Also, return by references the block 00202 /// that will be entered from if the condition is true, and the block that will 00203 /// be entered if the condition is false. 00204 /// 00205 /// This does no checking to see if the true/false blocks have large or unsavory 00206 /// instructions in them. 00207 static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 00208 BasicBlock *&IfFalse) { 00209 PHINode *SomePHI = cast<PHINode>(BB->begin()); 00210 assert(SomePHI->getNumIncomingValues() == 2 && 00211 "Function can only handle blocks with 2 predecessors!"); 00212 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0); 00213 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1); 00214 00215 // We can only handle branches. Other control flow will be lowered to 00216 // branches if possible anyway. 00217 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 00218 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 00219 if (Pred1Br == 0 || Pred2Br == 0) 00220 return 0; 00221 00222 // Eliminate code duplication by ensuring that Pred1Br is conditional if 00223 // either are. 00224 if (Pred2Br->isConditional()) { 00225 // If both branches are conditional, we don't have an "if statement". In 00226 // reality, we could transform this case, but since the condition will be 00227 // required anyway, we stand no chance of eliminating it, so the xform is 00228 // probably not profitable. 00229 if (Pred1Br->isConditional()) 00230 return 0; 00231 00232 std::swap(Pred1, Pred2); 00233 std::swap(Pred1Br, Pred2Br); 00234 } 00235 00236 if (Pred1Br->isConditional()) { 00237 // The only thing we have to watch out for here is to make sure that Pred2 00238 // doesn't have incoming edges from other blocks. If it does, the condition 00239 // doesn't dominate BB. 00240 if (Pred2->getSinglePredecessor() == 0) 00241 return 0; 00242 00243 // If we found a conditional branch predecessor, make sure that it branches 00244 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 00245 if (Pred1Br->getSuccessor(0) == BB && 00246 Pred1Br->getSuccessor(1) == Pred2) { 00247 IfTrue = Pred1; 00248 IfFalse = Pred2; 00249 } else if (Pred1Br->getSuccessor(0) == Pred2 && 00250 Pred1Br->getSuccessor(1) == BB) { 00251 IfTrue = Pred2; 00252 IfFalse = Pred1; 00253 } else { 00254 // We know that one arm of the conditional goes to BB, so the other must 00255 // go somewhere unrelated, and this must not be an "if statement". 00256 return 0; 00257 } 00258 00259 return Pred1Br->getCondition(); 00260 } 00261 00262 // Ok, if we got here, both predecessors end with an unconditional branch to 00263 // BB. Don't panic! If both blocks only have a single (identical) 00264 // predecessor, and THAT is a conditional branch, then we're all ok! 00265 BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 00266 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor()) 00267 return 0; 00268 00269 // Otherwise, if this is a conditional branch, then we can use it! 00270 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 00271 if (BI == 0) return 0; 00272 00273 assert(BI->isConditional() && "Two successors but not conditional?"); 00274 if (BI->getSuccessor(0) == Pred1) { 00275 IfTrue = Pred1; 00276 IfFalse = Pred2; 00277 } else { 00278 IfTrue = Pred2; 00279 IfFalse = Pred1; 00280 } 00281 return BI->getCondition(); 00282 } 00283 00284 /// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the 00285 /// given instruction, which is assumed to be safe to speculate. 1 means 00286 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive. 00287 static unsigned ComputeSpeculationCost(const User *I) { 00288 assert(isSafeToSpeculativelyExecute(I) && 00289 "Instruction is not safe to speculatively execute!"); 00290 switch (Operator::getOpcode(I)) { 00291 default: 00292 // In doubt, be conservative. 00293 return UINT_MAX; 00294 case Instruction::GetElementPtr: 00295 // GEPs are cheap if all indices are constant. 00296 if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 00297 return UINT_MAX; 00298 return 1; 00299 case Instruction::Load: 00300 case Instruction::Add: 00301 case Instruction::Sub: 00302 case Instruction::And: 00303 case Instruction::Or: 00304 case Instruction::Xor: 00305 case Instruction::Shl: 00306 case Instruction::LShr: 00307 case Instruction::AShr: 00308 case Instruction::ICmp: 00309 case Instruction::Trunc: 00310 case Instruction::ZExt: 00311 case Instruction::SExt: 00312 return 1; // These are all cheap. 00313 00314 case Instruction::Call: 00315 case Instruction::Select: 00316 return 2; 00317 } 00318 } 00319 00320 /// DominatesMergePoint - If we have a merge point of an "if condition" as 00321 /// accepted above, return true if the specified value dominates the block. We 00322 /// don't handle the true generality of domination here, just a special case 00323 /// which works well enough for us. 00324 /// 00325 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to 00326 /// see if V (which must be an instruction) and its recursive operands 00327 /// that do not dominate BB have a combined cost lower than CostRemaining and 00328 /// are non-trapping. If both are true, the instruction is inserted into the 00329 /// set and true is returned. 00330 /// 00331 /// The cost for most non-trapping instructions is defined as 1 except for 00332 /// Select whose cost is 2. 00333 /// 00334 /// After this function returns, CostRemaining is decreased by the cost of 00335 /// V plus its non-dominating operands. If that cost is greater than 00336 /// CostRemaining, false is returned and CostRemaining is undefined. 00337 static bool DominatesMergePoint(Value *V, BasicBlock *BB, 00338 SmallPtrSet<Instruction*, 4> *AggressiveInsts, 00339 unsigned &CostRemaining) { 00340 Instruction *I = dyn_cast<Instruction>(V); 00341 if (!I) { 00342 // Non-instructions all dominate instructions, but not all constantexprs 00343 // can be executed unconditionally. 00344 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) 00345 if (C->canTrap()) 00346 return false; 00347 return true; 00348 } 00349 BasicBlock *PBB = I->getParent(); 00350 00351 // We don't want to allow weird loops that might have the "if condition" in 00352 // the bottom of this block. 00353 if (PBB == BB) return false; 00354 00355 // If this instruction is defined in a block that contains an unconditional 00356 // branch to BB, then it must be in the 'conditional' part of the "if 00357 // statement". If not, it definitely dominates the region. 00358 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); 00359 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB) 00360 return true; 00361 00362 // If we aren't allowing aggressive promotion anymore, then don't consider 00363 // instructions in the 'if region'. 00364 if (AggressiveInsts == 0) return false; 00365 00366 // If we have seen this instruction before, don't count it again. 00367 if (AggressiveInsts->count(I)) return true; 00368 00369 // Okay, it looks like the instruction IS in the "condition". Check to 00370 // see if it's a cheap instruction to unconditionally compute, and if it 00371 // only uses stuff defined outside of the condition. If so, hoist it out. 00372 if (!isSafeToSpeculativelyExecute(I)) 00373 return false; 00374 00375 unsigned Cost = ComputeSpeculationCost(I); 00376 00377 if (Cost > CostRemaining) 00378 return false; 00379 00380 CostRemaining -= Cost; 00381 00382 // Okay, we can only really hoist these out if their operands do 00383 // not take us over the cost threshold. 00384 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) 00385 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining)) 00386 return false; 00387 // Okay, it's safe to do this! Remember this instruction. 00388 AggressiveInsts->insert(I); 00389 return true; 00390 } 00391 00392 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr 00393 /// and PointerNullValue. Return NULL if value is not a constant int. 00394 static ConstantInt *GetConstantInt(Value *V, const DataLayout *TD) { 00395 // Normal constant int. 00396 ConstantInt *CI = dyn_cast<ConstantInt>(V); 00397 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy()) 00398 return CI; 00399 00400 // This is some kind of pointer constant. Turn it into a pointer-sized 00401 // ConstantInt if possible. 00402 IntegerType *PtrTy = cast<IntegerType>(TD->getIntPtrType(V->getType())); 00403 00404 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). 00405 if (isa<ConstantPointerNull>(V)) 00406 return ConstantInt::get(PtrTy, 0); 00407 00408 // IntToPtr const int. 00409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 00410 if (CE->getOpcode() == Instruction::IntToPtr) 00411 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { 00412 // The constant is very likely to have the right type already. 00413 if (CI->getType() == PtrTy) 00414 return CI; 00415 else 00416 return cast<ConstantInt> 00417 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); 00418 } 00419 return 0; 00420 } 00421 00422 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together 00423 /// collection of icmp eq/ne instructions that compare a value against a 00424 /// constant, return the value being compared, and stick the constant into the 00425 /// Values vector. 00426 static Value * 00427 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra, 00428 const DataLayout *TD, bool isEQ, unsigned &UsedICmps) { 00429 Instruction *I = dyn_cast<Instruction>(V); 00430 if (I == 0) return 0; 00431 00432 // If this is an icmp against a constant, handle this as one of the cases. 00433 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) { 00434 if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) { 00435 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) { 00436 UsedICmps++; 00437 Vals.push_back(C); 00438 return I->getOperand(0); 00439 } 00440 00441 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to 00442 // the set. 00443 ConstantRange Span = 00444 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue()); 00445 00446 // If this is an and/!= check then we want to optimize "x ugt 2" into 00447 // x != 0 && x != 1. 00448 if (!isEQ) 00449 Span = Span.inverse(); 00450 00451 // If there are a ton of values, we don't want to make a ginormous switch. 00452 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) 00453 return 0; 00454 00455 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) 00456 Vals.push_back(ConstantInt::get(V->getContext(), Tmp)); 00457 UsedICmps++; 00458 return I->getOperand(0); 00459 } 00460 return 0; 00461 } 00462 00463 // Otherwise, we can only handle an | or &, depending on isEQ. 00464 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And)) 00465 return 0; 00466 00467 unsigned NumValsBeforeLHS = Vals.size(); 00468 unsigned UsedICmpsBeforeLHS = UsedICmps; 00469 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD, 00470 isEQ, UsedICmps)) { 00471 unsigned NumVals = Vals.size(); 00472 unsigned UsedICmpsBeforeRHS = UsedICmps; 00473 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD, 00474 isEQ, UsedICmps)) { 00475 if (LHS == RHS) 00476 return LHS; 00477 Vals.resize(NumVals); 00478 UsedICmps = UsedICmpsBeforeRHS; 00479 } 00480 00481 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet, 00482 // set it and return success. 00483 if (Extra == 0 || Extra == I->getOperand(1)) { 00484 Extra = I->getOperand(1); 00485 return LHS; 00486 } 00487 00488 Vals.resize(NumValsBeforeLHS); 00489 UsedICmps = UsedICmpsBeforeLHS; 00490 return 0; 00491 } 00492 00493 // If the LHS can't be folded in, but Extra is available and RHS can, try to 00494 // use LHS as Extra. 00495 if (Extra == 0 || Extra == I->getOperand(0)) { 00496 Value *OldExtra = Extra; 00497 Extra = I->getOperand(0); 00498 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD, 00499 isEQ, UsedICmps)) 00500 return RHS; 00501 assert(Vals.size() == NumValsBeforeLHS); 00502 Extra = OldExtra; 00503 } 00504 00505 return 0; 00506 } 00507 00508 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) { 00509 Instruction *Cond = 0; 00510 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 00511 Cond = dyn_cast<Instruction>(SI->getCondition()); 00512 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 00513 if (BI->isConditional()) 00514 Cond = dyn_cast<Instruction>(BI->getCondition()); 00515 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { 00516 Cond = dyn_cast<Instruction>(IBI->getAddress()); 00517 } 00518 00519 TI->eraseFromParent(); 00520 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond); 00521 } 00522 00523 /// isValueEqualityComparison - Return true if the specified terminator checks 00524 /// to see if a value is equal to constant integer value. 00525 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) { 00526 Value *CV = 0; 00527 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 00528 // Do not permit merging of large switch instructions into their 00529 // predecessors unless there is only one predecessor. 00530 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()), 00531 pred_end(SI->getParent())) <= 128) 00532 CV = SI->getCondition(); 00533 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 00534 if (BI->isConditional() && BI->getCondition()->hasOneUse()) 00535 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) 00536 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ || 00537 ICI->getPredicate() == ICmpInst::ICMP_NE) && 00538 GetConstantInt(ICI->getOperand(1), TD)) 00539 CV = ICI->getOperand(0); 00540 00541 // Unwrap any lossless ptrtoint cast. 00542 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext())) 00543 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) 00544 CV = PTII->getOperand(0); 00545 return CV; 00546 } 00547 00548 /// GetValueEqualityComparisonCases - Given a value comparison instruction, 00549 /// decode all of the 'cases' that it represents and return the 'default' block. 00550 BasicBlock *SimplifyCFGOpt:: 00551 GetValueEqualityComparisonCases(TerminatorInst *TI, 00552 std::vector<ValueEqualityComparisonCase> 00553 &Cases) { 00554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 00555 Cases.reserve(SI->getNumCases()); 00556 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i) 00557 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(), 00558 i.getCaseSuccessor())); 00559 return SI->getDefaultDest(); 00560 } 00561 00562 BranchInst *BI = cast<BranchInst>(TI); 00563 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 00564 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); 00565 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1), 00566 TD), 00567 Succ)); 00568 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); 00569 } 00570 00571 00572 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries 00573 /// in the list that match the specified block. 00574 static void EliminateBlockCases(BasicBlock *BB, 00575 std::vector<ValueEqualityComparisonCase> &Cases) { 00576 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); 00577 } 00578 00579 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as 00580 /// well. 00581 static bool 00582 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, 00583 std::vector<ValueEqualityComparisonCase > &C2) { 00584 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; 00585 00586 // Make V1 be smaller than V2. 00587 if (V1->size() > V2->size()) 00588 std::swap(V1, V2); 00589 00590 if (V1->size() == 0) return false; 00591 if (V1->size() == 1) { 00592 // Just scan V2. 00593 ConstantInt *TheVal = (*V1)[0].Value; 00594 for (unsigned i = 0, e = V2->size(); i != e; ++i) 00595 if (TheVal == (*V2)[i].Value) 00596 return true; 00597 } 00598 00599 // Otherwise, just sort both lists and compare element by element. 00600 array_pod_sort(V1->begin(), V1->end()); 00601 array_pod_sort(V2->begin(), V2->end()); 00602 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); 00603 while (i1 != e1 && i2 != e2) { 00604 if ((*V1)[i1].Value == (*V2)[i2].Value) 00605 return true; 00606 if ((*V1)[i1].Value < (*V2)[i2].Value) 00607 ++i1; 00608 else 00609 ++i2; 00610 } 00611 return false; 00612 } 00613 00614 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a 00615 /// terminator instruction and its block is known to only have a single 00616 /// predecessor block, check to see if that predecessor is also a value 00617 /// comparison with the same value, and if that comparison determines the 00618 /// outcome of this comparison. If so, simplify TI. This does a very limited 00619 /// form of jump threading. 00620 bool SimplifyCFGOpt:: 00621 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, 00622 BasicBlock *Pred, 00623 IRBuilder<> &Builder) { 00624 Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); 00625 if (!PredVal) return false; // Not a value comparison in predecessor. 00626 00627 Value *ThisVal = isValueEqualityComparison(TI); 00628 assert(ThisVal && "This isn't a value comparison!!"); 00629 if (ThisVal != PredVal) return false; // Different predicates. 00630 00631 // TODO: Preserve branch weight metadata, similarly to how 00632 // FoldValueComparisonIntoPredecessors preserves it. 00633 00634 // Find out information about when control will move from Pred to TI's block. 00635 std::vector<ValueEqualityComparisonCase> PredCases; 00636 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), 00637 PredCases); 00638 EliminateBlockCases(PredDef, PredCases); // Remove default from cases. 00639 00640 // Find information about how control leaves this block. 00641 std::vector<ValueEqualityComparisonCase> ThisCases; 00642 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); 00643 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. 00644 00645 // If TI's block is the default block from Pred's comparison, potentially 00646 // simplify TI based on this knowledge. 00647 if (PredDef == TI->getParent()) { 00648 // If we are here, we know that the value is none of those cases listed in 00649 // PredCases. If there are any cases in ThisCases that are in PredCases, we 00650 // can simplify TI. 00651 if (!ValuesOverlap(PredCases, ThisCases)) 00652 return false; 00653 00654 if (isa<BranchInst>(TI)) { 00655 // Okay, one of the successors of this condbr is dead. Convert it to a 00656 // uncond br. 00657 assert(ThisCases.size() == 1 && "Branch can only have one case!"); 00658 // Insert the new branch. 00659 Instruction *NI = Builder.CreateBr(ThisDef); 00660 (void) NI; 00661 00662 // Remove PHI node entries for the dead edge. 00663 ThisCases[0].Dest->removePredecessor(TI->getParent()); 00664 00665 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 00666 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); 00667 00668 EraseTerminatorInstAndDCECond(TI); 00669 return true; 00670 } 00671 00672 SwitchInst *SI = cast<SwitchInst>(TI); 00673 // Okay, TI has cases that are statically dead, prune them away. 00674 SmallPtrSet<Constant*, 16> DeadCases; 00675 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00676 DeadCases.insert(PredCases[i].Value); 00677 00678 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 00679 << "Through successor TI: " << *TI); 00680 00681 // Collect branch weights into a vector. 00682 SmallVector<uint32_t, 8> Weights; 00683 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof); 00684 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); 00685 if (HasWeight) 00686 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; 00687 ++MD_i) { 00688 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i)); 00689 assert(CI); 00690 Weights.push_back(CI->getValue().getZExtValue()); 00691 } 00692 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { 00693 --i; 00694 if (DeadCases.count(i.getCaseValue())) { 00695 if (HasWeight) { 00696 std::swap(Weights[i.getCaseIndex()+1], Weights.back()); 00697 Weights.pop_back(); 00698 } 00699 i.getCaseSuccessor()->removePredecessor(TI->getParent()); 00700 SI->removeCase(i); 00701 } 00702 } 00703 if (HasWeight && Weights.size() >= 2) 00704 SI->setMetadata(LLVMContext::MD_prof, 00705 MDBuilder(SI->getParent()->getContext()). 00706 createBranchWeights(Weights)); 00707 00708 DEBUG(dbgs() << "Leaving: " << *TI << "\n"); 00709 return true; 00710 } 00711 00712 // Otherwise, TI's block must correspond to some matched value. Find out 00713 // which value (or set of values) this is. 00714 ConstantInt *TIV = 0; 00715 BasicBlock *TIBB = TI->getParent(); 00716 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00717 if (PredCases[i].Dest == TIBB) { 00718 if (TIV != 0) 00719 return false; // Cannot handle multiple values coming to this block. 00720 TIV = PredCases[i].Value; 00721 } 00722 assert(TIV && "No edge from pred to succ?"); 00723 00724 // Okay, we found the one constant that our value can be if we get into TI's 00725 // BB. Find out which successor will unconditionally be branched to. 00726 BasicBlock *TheRealDest = 0; 00727 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) 00728 if (ThisCases[i].Value == TIV) { 00729 TheRealDest = ThisCases[i].Dest; 00730 break; 00731 } 00732 00733 // If not handled by any explicit cases, it is handled by the default case. 00734 if (TheRealDest == 0) TheRealDest = ThisDef; 00735 00736 // Remove PHI node entries for dead edges. 00737 BasicBlock *CheckEdge = TheRealDest; 00738 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) 00739 if (*SI != CheckEdge) 00740 (*SI)->removePredecessor(TIBB); 00741 else 00742 CheckEdge = 0; 00743 00744 // Insert the new branch. 00745 Instruction *NI = Builder.CreateBr(TheRealDest); 00746 (void) NI; 00747 00748 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 00749 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); 00750 00751 EraseTerminatorInstAndDCECond(TI); 00752 return true; 00753 } 00754 00755 namespace { 00756 /// ConstantIntOrdering - This class implements a stable ordering of constant 00757 /// integers that does not depend on their address. This is important for 00758 /// applications that sort ConstantInt's to ensure uniqueness. 00759 struct ConstantIntOrdering { 00760 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { 00761 return LHS->getValue().ult(RHS->getValue()); 00762 } 00763 }; 00764 } 00765 00766 static int ConstantIntSortPredicate(const void *P1, const void *P2) { 00767 const ConstantInt *LHS = *(const ConstantInt*const*)P1; 00768 const ConstantInt *RHS = *(const ConstantInt*const*)P2; 00769 if (LHS->getValue().ult(RHS->getValue())) 00770 return 1; 00771 if (LHS->getValue() == RHS->getValue()) 00772 return 0; 00773 return -1; 00774 } 00775 00776 static inline bool HasBranchWeights(const Instruction* I) { 00777 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof); 00778 if (ProfMD && ProfMD->getOperand(0)) 00779 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) 00780 return MDS->getString().equals("branch_weights"); 00781 00782 return false; 00783 } 00784 00785 /// Get Weights of a given TerminatorInst, the default weight is at the front 00786 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight 00787 /// metadata. 00788 static void GetBranchWeights(TerminatorInst *TI, 00789 SmallVectorImpl<uint64_t> &Weights) { 00790 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof); 00791 assert(MD); 00792 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) { 00793 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(i)); 00794 assert(CI); 00795 Weights.push_back(CI->getValue().getZExtValue()); 00796 } 00797 00798 // If TI is a conditional eq, the default case is the false case, 00799 // and the corresponding branch-weight data is at index 2. We swap the 00800 // default weight to be the first entry. 00801 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) { 00802 assert(Weights.size() == 2); 00803 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 00804 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 00805 std::swap(Weights.front(), Weights.back()); 00806 } 00807 } 00808 00809 /// Sees if any of the weights are too big for a uint32_t, and halves all the 00810 /// weights if any are. 00811 static void FitWeights(MutableArrayRef<uint64_t> Weights) { 00812 bool Halve = false; 00813 for (unsigned i = 0; i < Weights.size(); ++i) 00814 if (Weights[i] > UINT_MAX) { 00815 Halve = true; 00816 break; 00817 } 00818 00819 if (! Halve) 00820 return; 00821 00822 for (unsigned i = 0; i < Weights.size(); ++i) 00823 Weights[i] /= 2; 00824 } 00825 00826 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value 00827 /// equality comparison instruction (either a switch or a branch on "X == c"). 00828 /// See if any of the predecessors of the terminator block are value comparisons 00829 /// on the same value. If so, and if safe to do so, fold them together. 00830 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI, 00831 IRBuilder<> &Builder) { 00832 BasicBlock *BB = TI->getParent(); 00833 Value *CV = isValueEqualityComparison(TI); // CondVal 00834 assert(CV && "Not a comparison?"); 00835 bool Changed = false; 00836 00837 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB)); 00838 while (!Preds.empty()) { 00839 BasicBlock *Pred = Preds.pop_back_val(); 00840 00841 // See if the predecessor is a comparison with the same value. 00842 TerminatorInst *PTI = Pred->getTerminator(); 00843 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal 00844 00845 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { 00846 // Figure out which 'cases' to copy from SI to PSI. 00847 std::vector<ValueEqualityComparisonCase> BBCases; 00848 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); 00849 00850 std::vector<ValueEqualityComparisonCase> PredCases; 00851 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); 00852 00853 // Based on whether the default edge from PTI goes to BB or not, fill in 00854 // PredCases and PredDefault with the new switch cases we would like to 00855 // build. 00856 SmallVector<BasicBlock*, 8> NewSuccessors; 00857 00858 // Update the branch weight metadata along the way 00859 SmallVector<uint64_t, 8> Weights; 00860 bool PredHasWeights = HasBranchWeights(PTI); 00861 bool SuccHasWeights = HasBranchWeights(TI); 00862 00863 if (PredHasWeights) { 00864 GetBranchWeights(PTI, Weights); 00865 // branch-weight metadata is inconsistent here. 00866 if (Weights.size() != 1 + PredCases.size()) 00867 PredHasWeights = SuccHasWeights = false; 00868 } else if (SuccHasWeights) 00869 // If there are no predecessor weights but there are successor weights, 00870 // populate Weights with 1, which will later be scaled to the sum of 00871 // successor's weights 00872 Weights.assign(1 + PredCases.size(), 1); 00873 00874 SmallVector<uint64_t, 8> SuccWeights; 00875 if (SuccHasWeights) { 00876 GetBranchWeights(TI, SuccWeights); 00877 // branch-weight metadata is inconsistent here. 00878 if (SuccWeights.size() != 1 + BBCases.size()) 00879 PredHasWeights = SuccHasWeights = false; 00880 } else if (PredHasWeights) 00881 SuccWeights.assign(1 + BBCases.size(), 1); 00882 00883 if (PredDefault == BB) { 00884 // If this is the default destination from PTI, only the edges in TI 00885 // that don't occur in PTI, or that branch to BB will be activated. 00886 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; 00887 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00888 if (PredCases[i].Dest != BB) 00889 PTIHandled.insert(PredCases[i].Value); 00890 else { 00891 // The default destination is BB, we don't need explicit targets. 00892 std::swap(PredCases[i], PredCases.back()); 00893 00894 if (PredHasWeights || SuccHasWeights) { 00895 // Increase weight for the default case. 00896 Weights[0] += Weights[i+1]; 00897 std::swap(Weights[i+1], Weights.back()); 00898 Weights.pop_back(); 00899 } 00900 00901 PredCases.pop_back(); 00902 --i; --e; 00903 } 00904 00905 // Reconstruct the new switch statement we will be building. 00906 if (PredDefault != BBDefault) { 00907 PredDefault->removePredecessor(Pred); 00908 PredDefault = BBDefault; 00909 NewSuccessors.push_back(BBDefault); 00910 } 00911 00912 unsigned CasesFromPred = Weights.size(); 00913 uint64_t ValidTotalSuccWeight = 0; 00914 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 00915 if (!PTIHandled.count(BBCases[i].Value) && 00916 BBCases[i].Dest != BBDefault) { 00917 PredCases.push_back(BBCases[i]); 00918 NewSuccessors.push_back(BBCases[i].Dest); 00919 if (SuccHasWeights || PredHasWeights) { 00920 // The default weight is at index 0, so weight for the ith case 00921 // should be at index i+1. Scale the cases from successor by 00922 // PredDefaultWeight (Weights[0]). 00923 Weights.push_back(Weights[0] * SuccWeights[i+1]); 00924 ValidTotalSuccWeight += SuccWeights[i+1]; 00925 } 00926 } 00927 00928 if (SuccHasWeights || PredHasWeights) { 00929 ValidTotalSuccWeight += SuccWeights[0]; 00930 // Scale the cases from predecessor by ValidTotalSuccWeight. 00931 for (unsigned i = 1; i < CasesFromPred; ++i) 00932 Weights[i] *= ValidTotalSuccWeight; 00933 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). 00934 Weights[0] *= SuccWeights[0]; 00935 } 00936 } else { 00937 // If this is not the default destination from PSI, only the edges 00938 // in SI that occur in PSI with a destination of BB will be 00939 // activated. 00940 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; 00941 std::map<ConstantInt*, uint64_t> WeightsForHandled; 00942 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00943 if (PredCases[i].Dest == BB) { 00944 PTIHandled.insert(PredCases[i].Value); 00945 00946 if (PredHasWeights || SuccHasWeights) { 00947 WeightsForHandled[PredCases[i].Value] = Weights[i+1]; 00948 std::swap(Weights[i+1], Weights.back()); 00949 Weights.pop_back(); 00950 } 00951 00952 std::swap(PredCases[i], PredCases.back()); 00953 PredCases.pop_back(); 00954 --i; --e; 00955 } 00956 00957 // Okay, now we know which constants were sent to BB from the 00958 // predecessor. Figure out where they will all go now. 00959 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 00960 if (PTIHandled.count(BBCases[i].Value)) { 00961 // If this is one we are capable of getting... 00962 if (PredHasWeights || SuccHasWeights) 00963 Weights.push_back(WeightsForHandled[BBCases[i].Value]); 00964 PredCases.push_back(BBCases[i]); 00965 NewSuccessors.push_back(BBCases[i].Dest); 00966 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of 00967 } 00968 00969 // If there are any constants vectored to BB that TI doesn't handle, 00970 // they must go to the default destination of TI. 00971 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I = 00972 PTIHandled.begin(), 00973 E = PTIHandled.end(); I != E; ++I) { 00974 if (PredHasWeights || SuccHasWeights) 00975 Weights.push_back(WeightsForHandled[*I]); 00976 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault)); 00977 NewSuccessors.push_back(BBDefault); 00978 } 00979 } 00980 00981 // Okay, at this point, we know which new successor Pred will get. Make 00982 // sure we update the number of entries in the PHI nodes for these 00983 // successors. 00984 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i) 00985 AddPredecessorToBlock(NewSuccessors[i], Pred, BB); 00986 00987 Builder.SetInsertPoint(PTI); 00988 // Convert pointer to int before we switch. 00989 if (CV->getType()->isPointerTy()) { 00990 assert(TD && "Cannot switch on pointer without DataLayout"); 00991 CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()), 00992 "magicptr"); 00993 } 00994 00995 // Now that the successors are updated, create the new Switch instruction. 00996 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, 00997 PredCases.size()); 00998 NewSI->setDebugLoc(PTI->getDebugLoc()); 00999 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 01000 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest); 01001 01002 if (PredHasWeights || SuccHasWeights) { 01003 // Halve the weights if any of them cannot fit in an uint32_t 01004 FitWeights(Weights); 01005 01006 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 01007 01008 NewSI->setMetadata(LLVMContext::MD_prof, 01009 MDBuilder(BB->getContext()). 01010 createBranchWeights(MDWeights)); 01011 } 01012 01013 EraseTerminatorInstAndDCECond(PTI); 01014 01015 // Okay, last check. If BB is still a successor of PSI, then we must 01016 // have an infinite loop case. If so, add an infinitely looping block 01017 // to handle the case to preserve the behavior of the code. 01018 BasicBlock *InfLoopBlock = 0; 01019 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) 01020 if (NewSI->getSuccessor(i) == BB) { 01021 if (InfLoopBlock == 0) { 01022 // Insert it at the end of the function, because it's either code, 01023 // or it won't matter if it's hot. :) 01024 InfLoopBlock = BasicBlock::Create(BB->getContext(), 01025 "infloop", BB->getParent()); 01026 BranchInst::Create(InfLoopBlock, InfLoopBlock); 01027 } 01028 NewSI->setSuccessor(i, InfLoopBlock); 01029 } 01030 01031 Changed = true; 01032 } 01033 } 01034 return Changed; 01035 } 01036 01037 // isSafeToHoistInvoke - If we would need to insert a select that uses the 01038 // value of this invoke (comments in HoistThenElseCodeToIf explain why we 01039 // would need to do this), we can't hoist the invoke, as there is nowhere 01040 // to put the select in this case. 01041 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, 01042 Instruction *I1, Instruction *I2) { 01043 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { 01044 PHINode *PN; 01045 for (BasicBlock::iterator BBI = SI->begin(); 01046 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 01047 Value *BB1V = PN->getIncomingValueForBlock(BB1); 01048 Value *BB2V = PN->getIncomingValueForBlock(BB2); 01049 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) { 01050 return false; 01051 } 01052 } 01053 } 01054 return true; 01055 } 01056 01057 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and 01058 /// BB2, hoist any common code in the two blocks up into the branch block. The 01059 /// caller of this function guarantees that BI's block dominates BB1 and BB2. 01060 static bool HoistThenElseCodeToIf(BranchInst *BI) { 01061 // This does very trivial matching, with limited scanning, to find identical 01062 // instructions in the two blocks. In particular, we don't want to get into 01063 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As 01064 // such, we currently just scan for obviously identical instructions in an 01065 // identical order. 01066 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. 01067 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination 01068 01069 BasicBlock::iterator BB1_Itr = BB1->begin(); 01070 BasicBlock::iterator BB2_Itr = BB2->begin(); 01071 01072 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++; 01073 // Skip debug info if it is not identical. 01074 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 01075 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 01076 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 01077 while (isa<DbgInfoIntrinsic>(I1)) 01078 I1 = BB1_Itr++; 01079 while (isa<DbgInfoIntrinsic>(I2)) 01080 I2 = BB2_Itr++; 01081 } 01082 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || 01083 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))) 01084 return false; 01085 01086 // If we get here, we can hoist at least one instruction. 01087 BasicBlock *BIParent = BI->getParent(); 01088 01089 do { 01090 // If we are hoisting the terminator instruction, don't move one (making a 01091 // broken BB), instead clone it, and remove BI. 01092 if (isa<TerminatorInst>(I1)) 01093 goto HoistTerminator; 01094 01095 // For a normal instruction, we just move one to right before the branch, 01096 // then replace all uses of the other with the first. Finally, we remove 01097 // the now redundant second instruction. 01098 BIParent->getInstList().splice(BI, BB1->getInstList(), I1); 01099 if (!I2->use_empty()) 01100 I2->replaceAllUsesWith(I1); 01101 I1->intersectOptionalDataWith(I2); 01102 I2->eraseFromParent(); 01103 01104 I1 = BB1_Itr++; 01105 I2 = BB2_Itr++; 01106 // Skip debug info if it is not identical. 01107 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 01108 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 01109 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 01110 while (isa<DbgInfoIntrinsic>(I1)) 01111 I1 = BB1_Itr++; 01112 while (isa<DbgInfoIntrinsic>(I2)) 01113 I2 = BB2_Itr++; 01114 } 01115 } while (I1->isIdenticalToWhenDefined(I2)); 01116 01117 return true; 01118 01119 HoistTerminator: 01120 // It may not be possible to hoist an invoke. 01121 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) 01122 return true; 01123 01124 // Okay, it is safe to hoist the terminator. 01125 Instruction *NT = I1->clone(); 01126 BIParent->getInstList().insert(BI, NT); 01127 if (!NT->getType()->isVoidTy()) { 01128 I1->replaceAllUsesWith(NT); 01129 I2->replaceAllUsesWith(NT); 01130 NT->takeName(I1); 01131 } 01132 01133 IRBuilder<true, NoFolder> Builder(NT); 01134 // Hoisting one of the terminators from our successor is a great thing. 01135 // Unfortunately, the successors of the if/else blocks may have PHI nodes in 01136 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI 01137 // nodes, so we insert select instruction to compute the final result. 01138 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; 01139 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { 01140 PHINode *PN; 01141 for (BasicBlock::iterator BBI = SI->begin(); 01142 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 01143 Value *BB1V = PN->getIncomingValueForBlock(BB1); 01144 Value *BB2V = PN->getIncomingValueForBlock(BB2); 01145 if (BB1V == BB2V) continue; 01146 01147 // These values do not agree. Insert a select instruction before NT 01148 // that determines the right value. 01149 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; 01150 if (SI == 0) 01151 SI = cast<SelectInst> 01152 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, 01153 BB1V->getName()+"."+BB2V->getName())); 01154 01155 // Make the PHI node use the select for all incoming values for BB1/BB2 01156 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 01157 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) 01158 PN->setIncomingValue(i, SI); 01159 } 01160 } 01161 01162 // Update any PHI nodes in our new successors. 01163 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) 01164 AddPredecessorToBlock(*SI, BIParent, BB1); 01165 01166 EraseTerminatorInstAndDCECond(BI); 01167 return true; 01168 } 01169 01170 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd, 01171 /// check whether BBEnd has only two predecessors and the other predecessor 01172 /// ends with an unconditional branch. If it is true, sink any common code 01173 /// in the two predecessors to BBEnd. 01174 static bool SinkThenElseCodeToEnd(BranchInst *BI1) { 01175 assert(BI1->isUnconditional()); 01176 BasicBlock *BB1 = BI1->getParent(); 01177 BasicBlock *BBEnd = BI1->getSuccessor(0); 01178 01179 // Check that BBEnd has two predecessors and the other predecessor ends with 01180 // an unconditional branch. 01181 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd); 01182 BasicBlock *Pred0 = *PI++; 01183 if (PI == PE) // Only one predecessor. 01184 return false; 01185 BasicBlock *Pred1 = *PI++; 01186 if (PI != PE) // More than two predecessors. 01187 return false; 01188 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0; 01189 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator()); 01190 if (!BI2 || !BI2->isUnconditional()) 01191 return false; 01192 01193 // Gather the PHI nodes in BBEnd. 01194 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2; 01195 Instruction *FirstNonPhiInBBEnd = 0; 01196 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); 01197 I != E; ++I) { 01198 if (PHINode *PN = dyn_cast<PHINode>(I)) { 01199 Value *BB1V = PN->getIncomingValueForBlock(BB1); 01200 Value *BB2V = PN->getIncomingValueForBlock(BB2); 01201 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN); 01202 } else { 01203 FirstNonPhiInBBEnd = &*I; 01204 break; 01205 } 01206 } 01207 if (!FirstNonPhiInBBEnd) 01208 return false; 01209 01210 01211 // This does very trivial matching, with limited scanning, to find identical 01212 // instructions in the two blocks. We scan backward for obviously identical 01213 // instructions in an identical order. 01214 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(), 01215 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(), 01216 RE2 = BB2->getInstList().rend(); 01217 // Skip debug info. 01218 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; 01219 if (RI1 == RE1) 01220 return false; 01221 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; 01222 if (RI2 == RE2) 01223 return false; 01224 // Skip the unconditional branches. 01225 ++RI1; 01226 ++RI2; 01227 01228 bool Changed = false; 01229 while (RI1 != RE1 && RI2 != RE2) { 01230 // Skip debug info. 01231 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; 01232 if (RI1 == RE1) 01233 return Changed; 01234 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; 01235 if (RI2 == RE2) 01236 return Changed; 01237 01238 Instruction *I1 = &*RI1, *I2 = &*RI2; 01239 // I1 and I2 should have a single use in the same PHI node, and they 01240 // perform the same operation. 01241 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 01242 if (isa<PHINode>(I1) || isa<PHINode>(I2) || 01243 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) || 01244 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) || 01245 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) || 01246 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() || 01247 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() || 01248 !I1->hasOneUse() || !I2->hasOneUse() || 01249 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() || 01250 MapValueFromBB1ToBB2[I1].first != I2) 01251 return Changed; 01252 01253 // Check whether we should swap the operands of ICmpInst. 01254 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2); 01255 bool SwapOpnds = false; 01256 if (ICmp1 && ICmp2 && 01257 ICmp1->getOperand(0) != ICmp2->getOperand(0) && 01258 ICmp1->getOperand(1) != ICmp2->getOperand(1) && 01259 (ICmp1->getOperand(0) == ICmp2->getOperand(1) || 01260 ICmp1->getOperand(1) == ICmp2->getOperand(0))) { 01261 ICmp2->swapOperands(); 01262 SwapOpnds = true; 01263 } 01264 if (!I1->isSameOperationAs(I2)) { 01265 if (SwapOpnds) 01266 ICmp2->swapOperands(); 01267 return Changed; 01268 } 01269 01270 // The operands should be either the same or they need to be generated 01271 // with a PHI node after sinking. We only handle the case where there is 01272 // a single pair of different operands. 01273 Value *DifferentOp1 = 0, *DifferentOp2 = 0; 01274 unsigned Op1Idx = 0; 01275 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) { 01276 if (I1->getOperand(I) == I2->getOperand(I)) 01277 continue; 01278 // Early exit if we have more-than one pair of different operands or 01279 // the different operand is already in MapValueFromBB1ToBB2. 01280 // Early exit if we need a PHI node to replace a constant. 01281 if (DifferentOp1 || 01282 MapValueFromBB1ToBB2.find(I1->getOperand(I)) != 01283 MapValueFromBB1ToBB2.end() || 01284 isa<Constant>(I1->getOperand(I)) || 01285 isa<Constant>(I2->getOperand(I))) { 01286 // If we can't sink the instructions, undo the swapping. 01287 if (SwapOpnds) 01288 ICmp2->swapOperands(); 01289 return Changed; 01290 } 01291 DifferentOp1 = I1->getOperand(I); 01292 Op1Idx = I; 01293 DifferentOp2 = I2->getOperand(I); 01294 } 01295 01296 // We insert the pair of different operands to MapValueFromBB1ToBB2 and 01297 // remove (I1, I2) from MapValueFromBB1ToBB2. 01298 if (DifferentOp1) { 01299 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2, 01300 DifferentOp1->getName() + ".sink", 01301 BBEnd->begin()); 01302 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN); 01303 // I1 should use NewPN instead of DifferentOp1. 01304 I1->setOperand(Op1Idx, NewPN); 01305 NewPN->addIncoming(DifferentOp1, BB1); 01306 NewPN->addIncoming(DifferentOp2, BB2); 01307 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";); 01308 } 01309 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second; 01310 MapValueFromBB1ToBB2.erase(I1); 01311 01312 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";); 01313 DEBUG(dbgs() << " " << *I2 << "\n";); 01314 // We need to update RE1 and RE2 if we are going to sink the first 01315 // instruction in the basic block down. 01316 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin()); 01317 // Sink the instruction. 01318 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1); 01319 if (!OldPN->use_empty()) 01320 OldPN->replaceAllUsesWith(I1); 01321 OldPN->eraseFromParent(); 01322 01323 if (!I2->use_empty()) 01324 I2->replaceAllUsesWith(I1); 01325 I1->intersectOptionalDataWith(I2); 01326 I2->eraseFromParent(); 01327 01328 if (UpdateRE1) 01329 RE1 = BB1->getInstList().rend(); 01330 if (UpdateRE2) 01331 RE2 = BB2->getInstList().rend(); 01332 FirstNonPhiInBBEnd = I1; 01333 NumSinkCommons++; 01334 Changed = true; 01335 } 01336 return Changed; 01337 } 01338 01339 /// \brief Determine if we can hoist sink a sole store instruction out of a 01340 /// conditional block. 01341 /// 01342 /// We are looking for code like the following: 01343 /// BrBB: 01344 /// store i32 %add, i32* %arrayidx2 01345 /// ... // No other stores or function calls (we could be calling a memory 01346 /// ... // function). 01347 /// %cmp = icmp ult %x, %y 01348 /// br i1 %cmp, label %EndBB, label %ThenBB 01349 /// ThenBB: 01350 /// store i32 %add5, i32* %arrayidx2 01351 /// br label EndBB 01352 /// EndBB: 01353 /// ... 01354 /// We are going to transform this into: 01355 /// BrBB: 01356 /// store i32 %add, i32* %arrayidx2 01357 /// ... // 01358 /// %cmp = icmp ult %x, %y 01359 /// %add.add5 = select i1 %cmp, i32 %add, %add5 01360 /// store i32 %add.add5, i32* %arrayidx2 01361 /// ... 01362 /// 01363 /// \return The pointer to the value of the previous store if the store can be 01364 /// hoisted into the predecessor block. 0 otherwise. 01365 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, 01366 BasicBlock *StoreBB, BasicBlock *EndBB) { 01367 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); 01368 if (!StoreToHoist) 01369 return 0; 01370 01371 // Volatile or atomic. 01372 if (!StoreToHoist->isSimple()) 01373 return 0; 01374 01375 Value *StorePtr = StoreToHoist->getPointerOperand(); 01376 01377 // Look for a store to the same pointer in BrBB. 01378 unsigned MaxNumInstToLookAt = 10; 01379 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), 01380 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) { 01381 Instruction *CurI = &*RI; 01382 01383 // Could be calling an instruction that effects memory like free(). 01384 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI)) 01385 return 0; 01386 01387 StoreInst *SI = dyn_cast<StoreInst>(CurI); 01388 // Found the previous store make sure it stores to the same location. 01389 if (SI && SI->getPointerOperand() == StorePtr) 01390 // Found the previous store, return its value operand. 01391 return SI->getValueOperand(); 01392 else if (SI) 01393 return 0; // Unknown store. 01394 } 01395 01396 return 0; 01397 } 01398 01399 /// \brief Speculate a conditional basic block flattening the CFG. 01400 /// 01401 /// Note that this is a very risky transform currently. Speculating 01402 /// instructions like this is most often not desirable. Instead, there is an MI 01403 /// pass which can do it with full awareness of the resource constraints. 01404 /// However, some cases are "obvious" and we should do directly. An example of 01405 /// this is speculating a single, reasonably cheap instruction. 01406 /// 01407 /// There is only one distinct advantage to flattening the CFG at the IR level: 01408 /// it makes very common but simplistic optimizations such as are common in 01409 /// instcombine and the DAG combiner more powerful by removing CFG edges and 01410 /// modeling their effects with easier to reason about SSA value graphs. 01411 /// 01412 /// 01413 /// An illustration of this transform is turning this IR: 01414 /// \code 01415 /// BB: 01416 /// %cmp = icmp ult %x, %y 01417 /// br i1 %cmp, label %EndBB, label %ThenBB 01418 /// ThenBB: 01419 /// %sub = sub %x, %y 01420 /// br label BB2 01421 /// EndBB: 01422 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] 01423 /// ... 01424 /// \endcode 01425 /// 01426 /// Into this IR: 01427 /// \code 01428 /// BB: 01429 /// %cmp = icmp ult %x, %y 01430 /// %sub = sub %x, %y 01431 /// %cond = select i1 %cmp, 0, %sub 01432 /// ... 01433 /// \endcode 01434 /// 01435 /// \returns true if the conditional block is removed. 01436 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB) { 01437 // Be conservative for now. FP select instruction can often be expensive. 01438 Value *BrCond = BI->getCondition(); 01439 if (isa<FCmpInst>(BrCond)) 01440 return false; 01441 01442 BasicBlock *BB = BI->getParent(); 01443 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); 01444 01445 // If ThenBB is actually on the false edge of the conditional branch, remember 01446 // to swap the select operands later. 01447 bool Invert = false; 01448 if (ThenBB != BI->getSuccessor(0)) { 01449 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); 01450 Invert = true; 01451 } 01452 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); 01453 01454 // Keep a count of how many times instructions are used within CondBB when 01455 // they are candidates for sinking into CondBB. Specifically: 01456 // - They are defined in BB, and 01457 // - They have no side effects, and 01458 // - All of their uses are in CondBB. 01459 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; 01460 01461 unsigned SpeculationCost = 0; 01462 Value *SpeculatedStoreValue = 0; 01463 StoreInst *SpeculatedStore = 0; 01464 for (BasicBlock::iterator BBI = ThenBB->begin(), 01465 BBE = llvm::prior(ThenBB->end()); 01466 BBI != BBE; ++BBI) { 01467 Instruction *I = BBI; 01468 // Skip debug info. 01469 if (isa<DbgInfoIntrinsic>(I)) 01470 continue; 01471 01472 // Only speculatively execution a single instruction (not counting the 01473 // terminator) for now. 01474 ++SpeculationCost; 01475 if (SpeculationCost > 1) 01476 return false; 01477 01478 // Don't hoist the instruction if it's unsafe or expensive. 01479 if (!isSafeToSpeculativelyExecute(I) && 01480 !(HoistCondStores && 01481 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB, 01482 EndBB)))) 01483 return false; 01484 if (!SpeculatedStoreValue && 01485 ComputeSpeculationCost(I) > PHINodeFoldingThreshold) 01486 return false; 01487 01488 // Store the store speculation candidate. 01489 if (SpeculatedStoreValue) 01490 SpeculatedStore = cast<StoreInst>(I); 01491 01492 // Do not hoist the instruction if any of its operands are defined but not 01493 // used in BB. The transformation will prevent the operand from 01494 // being sunk into the use block. 01495 for (User::op_iterator i = I->op_begin(), e = I->op_end(); 01496 i != e; ++i) { 01497 Instruction *OpI = dyn_cast<Instruction>(*i); 01498 if (!OpI || OpI->getParent() != BB || 01499 OpI->mayHaveSideEffects()) 01500 continue; // Not a candidate for sinking. 01501 01502 ++SinkCandidateUseCounts[OpI]; 01503 } 01504 } 01505 01506 // Consider any sink candidates which are only used in CondBB as costs for 01507 // speculation. Note, while we iterate over a DenseMap here, we are summing 01508 // and so iteration order isn't significant. 01509 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I = 01510 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end(); 01511 I != E; ++I) 01512 if (I->first->getNumUses() == I->second) { 01513 ++SpeculationCost; 01514 if (SpeculationCost > 1) 01515 return false; 01516 } 01517 01518 // Check that the PHI nodes can be converted to selects. 01519 bool HaveRewritablePHIs = false; 01520 for (BasicBlock::iterator I = EndBB->begin(); 01521 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 01522 Value *OrigV = PN->getIncomingValueForBlock(BB); 01523 Value *ThenV = PN->getIncomingValueForBlock(ThenBB); 01524 01525 // Skip PHIs which are trivial. 01526 if (ThenV == OrigV) 01527 continue; 01528 01529 HaveRewritablePHIs = true; 01530 ConstantExpr *CE = dyn_cast<ConstantExpr>(ThenV); 01531 if (!CE) 01532 continue; // Known safe and cheap. 01533 01534 if (!isSafeToSpeculativelyExecute(CE)) 01535 return false; 01536 if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold) 01537 return false; 01538 01539 // Account for the cost of an unfolded ConstantExpr which could end up 01540 // getting expanded into Instructions. 01541 // FIXME: This doesn't account for how many operations are combined in the 01542 // constant expression. 01543 ++SpeculationCost; 01544 if (SpeculationCost > 1) 01545 return false; 01546 } 01547 01548 // If there are no PHIs to process, bail early. This helps ensure idempotence 01549 // as well. 01550 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) 01551 return false; 01552 01553 // If we get here, we can hoist the instruction and if-convert. 01554 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); 01555 01556 // Insert a select of the value of the speculated store. 01557 if (SpeculatedStoreValue) { 01558 IRBuilder<true, NoFolder> Builder(BI); 01559 Value *TrueV = SpeculatedStore->getValueOperand(); 01560 Value *FalseV = SpeculatedStoreValue; 01561 if (Invert) 01562 std::swap(TrueV, FalseV); 01563 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() + 01564 "." + FalseV->getName()); 01565 SpeculatedStore->setOperand(0, S); 01566 } 01567 01568 // Hoist the instructions. 01569 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(), 01570 llvm::prior(ThenBB->end())); 01571 01572 // Insert selects and rewrite the PHI operands. 01573 IRBuilder<true, NoFolder> Builder(BI); 01574 for (BasicBlock::iterator I = EndBB->begin(); 01575 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 01576 unsigned OrigI = PN->getBasicBlockIndex(BB); 01577 unsigned ThenI = PN->getBasicBlockIndex(ThenBB); 01578 Value *OrigV = PN->getIncomingValue(OrigI); 01579 Value *ThenV = PN->getIncomingValue(ThenI); 01580 01581 // Skip PHIs which are trivial. 01582 if (OrigV == ThenV) 01583 continue; 01584 01585 // Create a select whose true value is the speculatively executed value and 01586 // false value is the preexisting value. Swap them if the branch 01587 // destinations were inverted. 01588 Value *TrueV = ThenV, *FalseV = OrigV; 01589 if (Invert) 01590 std::swap(TrueV, FalseV); 01591 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, 01592 TrueV->getName() + "." + FalseV->getName()); 01593 PN->setIncomingValue(OrigI, V); 01594 PN->setIncomingValue(ThenI, V); 01595 } 01596 01597 ++NumSpeculations; 01598 return true; 01599 } 01600 01601 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch 01602 /// across this block. 01603 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { 01604 BranchInst *BI = cast<BranchInst>(BB->getTerminator()); 01605 unsigned Size = 0; 01606 01607 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 01608 if (isa<DbgInfoIntrinsic>(BBI)) 01609 continue; 01610 if (Size > 10) return false; // Don't clone large BB's. 01611 ++Size; 01612 01613 // We can only support instructions that do not define values that are 01614 // live outside of the current basic block. 01615 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end(); 01616 UI != E; ++UI) { 01617 Instruction *U = cast<Instruction>(*UI); 01618 if (U->getParent() != BB || isa<PHINode>(U)) return false; 01619 } 01620 01621 // Looks ok, continue checking. 01622 } 01623 01624 return true; 01625 } 01626 01627 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value 01628 /// that is defined in the same block as the branch and if any PHI entries are 01629 /// constants, thread edges corresponding to that entry to be branches to their 01630 /// ultimate destination. 01631 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *TD) { 01632 BasicBlock *BB = BI->getParent(); 01633 PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); 01634 // NOTE: we currently cannot transform this case if the PHI node is used 01635 // outside of the block. 01636 if (!PN || PN->getParent() != BB || !PN->hasOneUse()) 01637 return false; 01638 01639 // Degenerate case of a single entry PHI. 01640 if (PN->getNumIncomingValues() == 1) { 01641 FoldSingleEntryPHINodes(PN->getParent()); 01642 return true; 01643 } 01644 01645 // Now we know that this block has multiple preds and two succs. 01646 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false; 01647 01648 // Okay, this is a simple enough basic block. See if any phi values are 01649 // constants. 01650 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 01651 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); 01652 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue; 01653 01654 // Okay, we now know that all edges from PredBB should be revectored to 01655 // branch to RealDest. 01656 BasicBlock *PredBB = PN->getIncomingBlock(i); 01657 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); 01658 01659 if (RealDest == BB) continue; // Skip self loops. 01660 // Skip if the predecessor's terminator is an indirect branch. 01661 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue; 01662 01663 // The dest block might have PHI nodes, other predecessors and other 01664 // difficult cases. Instead of being smart about this, just insert a new 01665 // block that jumps to the destination block, effectively splitting 01666 // the edge we are about to create. 01667 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(), 01668 RealDest->getName()+".critedge", 01669 RealDest->getParent(), RealDest); 01670 BranchInst::Create(RealDest, EdgeBB); 01671 01672 // Update PHI nodes. 01673 AddPredecessorToBlock(RealDest, EdgeBB, BB); 01674 01675 // BB may have instructions that are being threaded over. Clone these 01676 // instructions into EdgeBB. We know that there will be no uses of the 01677 // cloned instructions outside of EdgeBB. 01678 BasicBlock::iterator InsertPt = EdgeBB->begin(); 01679 DenseMap<Value*, Value*> TranslateMap; // Track translated values. 01680 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 01681 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 01682 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); 01683 continue; 01684 } 01685 // Clone the instruction. 01686 Instruction *N = BBI->clone(); 01687 if (BBI->hasName()) N->setName(BBI->getName()+".c"); 01688 01689 // Update operands due to translation. 01690 for (User::op_iterator i = N->op_begin(), e = N->op_end(); 01691 i != e; ++i) { 01692 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i); 01693 if (PI != TranslateMap.end()) 01694 *i = PI->second; 01695 } 01696 01697 // Check for trivial simplification. 01698 if (Value *V = SimplifyInstruction(N, TD)) { 01699 TranslateMap[BBI] = V; 01700 delete N; // Instruction folded away, don't need actual inst 01701 } else { 01702 // Insert the new instruction into its new home. 01703 EdgeBB->getInstList().insert(InsertPt, N); 01704 if (!BBI->use_empty()) 01705 TranslateMap[BBI] = N; 01706 } 01707 } 01708 01709 // Loop over all of the edges from PredBB to BB, changing them to branch 01710 // to EdgeBB instead. 01711 TerminatorInst *PredBBTI = PredBB->getTerminator(); 01712 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) 01713 if (PredBBTI->getSuccessor(i) == BB) { 01714 BB->removePredecessor(PredBB); 01715 PredBBTI->setSuccessor(i, EdgeBB); 01716 } 01717 01718 // Recurse, simplifying any other constants. 01719 return FoldCondBranchOnPHI(BI, TD) | true; 01720 } 01721 01722 return false; 01723 } 01724 01725 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry 01726 /// PHI node, see if we can eliminate it. 01727 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *TD) { 01728 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 01729 // statement", which has a very simple dominance structure. Basically, we 01730 // are trying to find the condition that is being branched on, which 01731 // subsequently causes this merge to happen. We really want control 01732 // dependence information for this check, but simplifycfg can't keep it up 01733 // to date, and this catches most of the cases we care about anyway. 01734 BasicBlock *BB = PN->getParent(); 01735 BasicBlock *IfTrue, *IfFalse; 01736 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); 01737 if (!IfCond || 01738 // Don't bother if the branch will be constant folded trivially. 01739 isa<ConstantInt>(IfCond)) 01740 return false; 01741 01742 // Okay, we found that we can merge this two-entry phi node into a select. 01743 // Doing so would require us to fold *all* two entry phi nodes in this block. 01744 // At some point this becomes non-profitable (particularly if the target 01745 // doesn't support cmov's). Only do this transformation if there are two or 01746 // fewer PHI nodes in this block. 01747 unsigned NumPhis = 0; 01748 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) 01749 if (NumPhis > 2) 01750 return false; 01751 01752 // Loop over the PHI's seeing if we can promote them all to select 01753 // instructions. While we are at it, keep track of the instructions 01754 // that need to be moved to the dominating block. 01755 SmallPtrSet<Instruction*, 4> AggressiveInsts; 01756 unsigned MaxCostVal0 = PHINodeFoldingThreshold, 01757 MaxCostVal1 = PHINodeFoldingThreshold; 01758 01759 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { 01760 PHINode *PN = cast<PHINode>(II++); 01761 if (Value *V = SimplifyInstruction(PN, TD)) { 01762 PN->replaceAllUsesWith(V); 01763 PN->eraseFromParent(); 01764 continue; 01765 } 01766 01767 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts, 01768 MaxCostVal0) || 01769 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts, 01770 MaxCostVal1)) 01771 return false; 01772 } 01773 01774 // If we folded the first phi, PN dangles at this point. Refresh it. If 01775 // we ran out of PHIs then we simplified them all. 01776 PN = dyn_cast<PHINode>(BB->begin()); 01777 if (PN == 0) return true; 01778 01779 // Don't fold i1 branches on PHIs which contain binary operators. These can 01780 // often be turned into switches and other things. 01781 if (PN->getType()->isIntegerTy(1) && 01782 (isa<BinaryOperator>(PN->getIncomingValue(0)) || 01783 isa<BinaryOperator>(PN->getIncomingValue(1)) || 01784 isa<BinaryOperator>(IfCond))) 01785 return false; 01786 01787 // If we all PHI nodes are promotable, check to make sure that all 01788 // instructions in the predecessor blocks can be promoted as well. If 01789 // not, we won't be able to get rid of the control flow, so it's not 01790 // worth promoting to select instructions. 01791 BasicBlock *DomBlock = 0; 01792 BasicBlock *IfBlock1 = PN->getIncomingBlock(0); 01793 BasicBlock *IfBlock2 = PN->getIncomingBlock(1); 01794 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { 01795 IfBlock1 = 0; 01796 } else { 01797 DomBlock = *pred_begin(IfBlock1); 01798 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I) 01799 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { 01800 // This is not an aggressive instruction that we can promote. 01801 // Because of this, we won't be able to get rid of the control 01802 // flow, so the xform is not worth it. 01803 return false; 01804 } 01805 } 01806 01807 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { 01808 IfBlock2 = 0; 01809 } else { 01810 DomBlock = *pred_begin(IfBlock2); 01811 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I) 01812 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { 01813 // This is not an aggressive instruction that we can promote. 01814 // Because of this, we won't be able to get rid of the control 01815 // flow, so the xform is not worth it. 01816 return false; 01817 } 01818 } 01819 01820 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: " 01821 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); 01822 01823 // If we can still promote the PHI nodes after this gauntlet of tests, 01824 // do all of the PHI's now. 01825 Instruction *InsertPt = DomBlock->getTerminator(); 01826 IRBuilder<true, NoFolder> Builder(InsertPt); 01827 01828 // Move all 'aggressive' instructions, which are defined in the 01829 // conditional parts of the if's up to the dominating block. 01830 if (IfBlock1) 01831 DomBlock->getInstList().splice(InsertPt, 01832 IfBlock1->getInstList(), IfBlock1->begin(), 01833 IfBlock1->getTerminator()); 01834 if (IfBlock2) 01835 DomBlock->getInstList().splice(InsertPt, 01836 IfBlock2->getInstList(), IfBlock2->begin(), 01837 IfBlock2->getTerminator()); 01838 01839 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 01840 // Change the PHI node into a select instruction. 01841 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); 01842 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); 01843 01844 SelectInst *NV = 01845 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, "")); 01846 PN->replaceAllUsesWith(NV); 01847 NV->takeName(PN); 01848 PN->eraseFromParent(); 01849 } 01850 01851 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement 01852 // has been flattened. Change DomBlock to jump directly to our new block to 01853 // avoid other simplifycfg's kicking in on the diamond. 01854 TerminatorInst *OldTI = DomBlock->getTerminator(); 01855 Builder.SetInsertPoint(OldTI); 01856 Builder.CreateBr(BB); 01857 OldTI->eraseFromParent(); 01858 return true; 01859 } 01860 01861 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes 01862 /// to two returning blocks, try to merge them together into one return, 01863 /// introducing a select if the return values disagree. 01864 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, 01865 IRBuilder<> &Builder) { 01866 assert(BI->isConditional() && "Must be a conditional branch"); 01867 BasicBlock *TrueSucc = BI->getSuccessor(0); 01868 BasicBlock *FalseSucc = BI->getSuccessor(1); 01869 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); 01870 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); 01871 01872 // Check to ensure both blocks are empty (just a return) or optionally empty 01873 // with PHI nodes. If there are other instructions, merging would cause extra 01874 // computation on one path or the other. 01875 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) 01876 return false; 01877 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) 01878 return false; 01879 01880 Builder.SetInsertPoint(BI); 01881 // Okay, we found a branch that is going to two return nodes. If 01882 // there is no return value for this function, just change the 01883 // branch into a return. 01884 if (FalseRet->getNumOperands() == 0) { 01885 TrueSucc->removePredecessor(BI->getParent()); 01886 FalseSucc->removePredecessor(BI->getParent()); 01887 Builder.CreateRetVoid(); 01888 EraseTerminatorInstAndDCECond(BI); 01889 return true; 01890 } 01891 01892 // Otherwise, figure out what the true and false return values are 01893 // so we can insert a new select instruction. 01894 Value *TrueValue = TrueRet->getReturnValue(); 01895 Value *FalseValue = FalseRet->getReturnValue(); 01896 01897 // Unwrap any PHI nodes in the return blocks. 01898 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) 01899 if (TVPN->getParent() == TrueSucc) 01900 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); 01901 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) 01902 if (FVPN->getParent() == FalseSucc) 01903 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); 01904 01905 // In order for this transformation to be safe, we must be able to 01906 // unconditionally execute both operands to the return. This is 01907 // normally the case, but we could have a potentially-trapping 01908 // constant expression that prevents this transformation from being 01909 // safe. 01910 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) 01911 if (TCV->canTrap()) 01912 return false; 01913 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) 01914 if (FCV->canTrap()) 01915 return false; 01916 01917 // Okay, we collected all the mapped values and checked them for sanity, and 01918 // defined to really do this transformation. First, update the CFG. 01919 TrueSucc->removePredecessor(BI->getParent()); 01920 FalseSucc->removePredecessor(BI->getParent()); 01921 01922 // Insert select instructions where needed. 01923 Value *BrCond = BI->getCondition(); 01924 if (TrueValue) { 01925 // Insert a select if the results differ. 01926 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { 01927 } else if (isa<UndefValue>(TrueValue)) { 01928 TrueValue = FalseValue; 01929 } else { 01930 TrueValue = Builder.CreateSelect(BrCond, TrueValue, 01931 FalseValue, "retval"); 01932 } 01933 } 01934 01935 Value *RI = !TrueValue ? 01936 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); 01937 01938 (void) RI; 01939 01940 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 01941 << "\n " << *BI << "NewRet = " << *RI 01942 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc); 01943 01944 EraseTerminatorInstAndDCECond(BI); 01945 01946 return true; 01947 } 01948 01949 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the 01950 /// probabilities of the branch taking each edge. Fills in the two APInt 01951 /// parameters and return true, or returns false if no or invalid metadata was 01952 /// found. 01953 static bool ExtractBranchMetadata(BranchInst *BI, 01954 uint64_t &ProbTrue, uint64_t &ProbFalse) { 01955 assert(BI->isConditional() && 01956 "Looking for probabilities on unconditional branch?"); 01957 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof); 01958 if (!ProfileData || ProfileData->getNumOperands() != 3) return false; 01959 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1)); 01960 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2)); 01961 if (!CITrue || !CIFalse) return false; 01962 ProbTrue = CITrue->getValue().getZExtValue(); 01963 ProbFalse = CIFalse->getValue().getZExtValue(); 01964 return true; 01965 } 01966 01967 /// checkCSEInPredecessor - Return true if the given instruction is available 01968 /// in its predecessor block. If yes, the instruction will be removed. 01969 /// 01970 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) { 01971 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) 01972 return false; 01973 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) { 01974 Instruction *PBI = &*I; 01975 // Check whether Inst and PBI generate the same value. 01976 if (Inst->isIdenticalTo(PBI)) { 01977 Inst->replaceAllUsesWith(PBI); 01978 Inst->eraseFromParent(); 01979 return true; 01980 } 01981 } 01982 return false; 01983 } 01984 01985 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a 01986 /// predecessor branches to us and one of our successors, fold the block into 01987 /// the predecessor and use logical operations to pick the right destination. 01988 bool llvm::FoldBranchToCommonDest(BranchInst *BI) { 01989 BasicBlock *BB = BI->getParent(); 01990 01991 Instruction *Cond = 0; 01992 if (BI->isConditional()) 01993 Cond = dyn_cast<Instruction>(BI->getCondition()); 01994 else { 01995 // For unconditional branch, check for a simple CFG pattern, where 01996 // BB has a single predecessor and BB's successor is also its predecessor's 01997 // successor. If such pattern exisits, check for CSE between BB and its 01998 // predecessor. 01999 if (BasicBlock *PB = BB->getSinglePredecessor()) 02000 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) 02001 if (PBI->isConditional() && 02002 (BI->getSuccessor(0) == PBI->getSuccessor(0) || 02003 BI->getSuccessor(0) == PBI->getSuccessor(1))) { 02004 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); 02005 I != E; ) { 02006 Instruction *Curr = I++; 02007 if (isa<CmpInst>(Curr)) { 02008 Cond = Curr; 02009 break; 02010 } 02011 // Quit if we can't remove this instruction. 02012 if (!checkCSEInPredecessor(Curr, PB)) 02013 return false; 02014 } 02015 } 02016 02017 if (Cond == 0) 02018 return false; 02019 } 02020 02021 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 02022 Cond->getParent() != BB || !Cond->hasOneUse()) 02023 return false; 02024 02025 // Only allow this if the condition is a simple instruction that can be 02026 // executed unconditionally. It must be in the same block as the branch, and 02027 // must be at the front of the block. 02028 BasicBlock::iterator FrontIt = BB->front(); 02029 02030 // Ignore dbg intrinsics. 02031 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt; 02032 02033 // Allow a single instruction to be hoisted in addition to the compare 02034 // that feeds the branch. We later ensure that any values that _it_ uses 02035 // were also live in the predecessor, so that we don't unnecessarily create 02036 // register pressure or inhibit out-of-order execution. 02037 Instruction *BonusInst = 0; 02038 if (&*FrontIt != Cond && 02039 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond && 02040 isSafeToSpeculativelyExecute(FrontIt)) { 02041 BonusInst = &*FrontIt; 02042 ++FrontIt; 02043 02044 // Ignore dbg intrinsics. 02045 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt; 02046 } 02047 02048 // Only a single bonus inst is allowed. 02049 if (&*FrontIt != Cond) 02050 return false; 02051 02052 // Make sure the instruction after the condition is the cond branch. 02053 BasicBlock::iterator CondIt = Cond; ++CondIt; 02054 02055 // Ingore dbg intrinsics. 02056 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt; 02057 02058 if (&*CondIt != BI) 02059 return false; 02060 02061 // Cond is known to be a compare or binary operator. Check to make sure that 02062 // neither operand is a potentially-trapping constant expression. 02063 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 02064 if (CE->canTrap()) 02065 return false; 02066 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 02067 if (CE->canTrap()) 02068 return false; 02069 02070 // Finally, don't infinitely unroll conditional loops. 02071 BasicBlock *TrueDest = BI->getSuccessor(0); 02072 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : 0; 02073 if (TrueDest == BB || FalseDest == BB) 02074 return false; 02075 02076 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 02077 BasicBlock *PredBlock = *PI; 02078 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 02079 02080 // Check that we have two conditional branches. If there is a PHI node in 02081 // the common successor, verify that the same value flows in from both 02082 // blocks. 02083 SmallVector<PHINode*, 4> PHIs; 02084 if (PBI == 0 || PBI->isUnconditional() || 02085 (BI->isConditional() && 02086 !SafeToMergeTerminators(BI, PBI)) || 02087 (!BI->isConditional() && 02088 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) 02089 continue; 02090 02091 // Determine if the two branches share a common destination. 02092 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; 02093 bool InvertPredCond = false; 02094 02095 if (BI->isConditional()) { 02096 if (PBI->getSuccessor(0) == TrueDest) 02097 Opc = Instruction::Or; 02098 else if (PBI->getSuccessor(1) == FalseDest) 02099 Opc = Instruction::And; 02100 else if (PBI->getSuccessor(0) == FalseDest) 02101 Opc = Instruction::And, InvertPredCond = true; 02102 else if (PBI->getSuccessor(1) == TrueDest) 02103 Opc = Instruction::Or, InvertPredCond = true; 02104 else 02105 continue; 02106 } else { 02107 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) 02108 continue; 02109 } 02110 02111 // Ensure that any values used in the bonus instruction are also used 02112 // by the terminator of the predecessor. This means that those values 02113 // must already have been resolved, so we won't be inhibiting the 02114 // out-of-order core by speculating them earlier. 02115 if (BonusInst) { 02116 // Collect the values used by the bonus inst 02117 SmallPtrSet<Value*, 4> UsedValues; 02118 for (Instruction::op_iterator OI = BonusInst->op_begin(), 02119 OE = BonusInst->op_end(); OI != OE; ++OI) { 02120 Value *V = *OI; 02121 if (!isa<Constant>(V)) 02122 UsedValues.insert(V); 02123 } 02124 02125 SmallVector<std::pair<Value*, unsigned>, 4> Worklist; 02126 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0)); 02127 02128 // Walk up to four levels back up the use-def chain of the predecessor's 02129 // terminator to see if all those values were used. The choice of four 02130 // levels is arbitrary, to provide a compile-time-cost bound. 02131 while (!Worklist.empty()) { 02132 std::pair<Value*, unsigned> Pair = Worklist.back(); 02133 Worklist.pop_back(); 02134 02135 if (Pair.second >= 4) continue; 02136 UsedValues.erase(Pair.first); 02137 if (UsedValues.empty()) break; 02138 02139 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) { 02140 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 02141 OI != OE; ++OI) 02142 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1)); 02143 } 02144 } 02145 02146 if (!UsedValues.empty()) return false; 02147 } 02148 02149 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 02150 IRBuilder<> Builder(PBI); 02151 02152 // If we need to invert the condition in the pred block to match, do so now. 02153 if (InvertPredCond) { 02154 Value *NewCond = PBI->getCondition(); 02155 02156 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 02157 CmpInst *CI = cast<CmpInst>(NewCond); 02158 CI->setPredicate(CI->getInversePredicate()); 02159 } else { 02160 NewCond = Builder.CreateNot(NewCond, 02161 PBI->getCondition()->getName()+".not"); 02162 } 02163 02164 PBI->setCondition(NewCond); 02165 PBI->swapSuccessors(); 02166 } 02167 02168 // If we have a bonus inst, clone it into the predecessor block. 02169 Instruction *NewBonus = 0; 02170 if (BonusInst) { 02171 NewBonus = BonusInst->clone(); 02172 PredBlock->getInstList().insert(PBI, NewBonus); 02173 NewBonus->takeName(BonusInst); 02174 BonusInst->setName(BonusInst->getName()+".old"); 02175 } 02176 02177 // Clone Cond into the predecessor basic block, and or/and the 02178 // two conditions together. 02179 Instruction *New = Cond->clone(); 02180 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus); 02181 PredBlock->getInstList().insert(PBI, New); 02182 New->takeName(Cond); 02183 Cond->setName(New->getName()+".old"); 02184 02185 if (BI->isConditional()) { 02186 Instruction *NewCond = 02187 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(), 02188 New, "or.cond")); 02189 PBI->setCondition(NewCond); 02190 02191 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 02192 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, 02193 PredFalseWeight); 02194 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, 02195 SuccFalseWeight); 02196 SmallVector<uint64_t, 8> NewWeights; 02197 02198 if (PBI->getSuccessor(0) == BB) { 02199 if (PredHasWeights && SuccHasWeights) { 02200 // PBI: br i1 %x, BB, FalseDest 02201 // BI: br i1 %y, TrueDest, FalseDest 02202 //TrueWeight is TrueWeight for PBI * TrueWeight for BI. 02203 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 02204 //FalseWeight is FalseWeight for PBI * TotalWeight for BI + 02205 // TrueWeight for PBI * FalseWeight for BI. 02206 // We assume that total weights of a BranchInst can fit into 32 bits. 02207 // Therefore, we will not have overflow using 64-bit arithmetic. 02208 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight + 02209 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight); 02210 } 02211 AddPredecessorToBlock(TrueDest, PredBlock, BB); 02212 PBI->setSuccessor(0, TrueDest); 02213 } 02214 if (PBI->getSuccessor(1) == BB) { 02215 if (PredHasWeights && SuccHasWeights) { 02216 // PBI: br i1 %x, TrueDest, BB 02217 // BI: br i1 %y, TrueDest, FalseDest 02218 //TrueWeight is TrueWeight for PBI * TotalWeight for BI + 02219 // FalseWeight for PBI * TrueWeight for BI. 02220 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + 02221 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight); 02222 //FalseWeight is FalseWeight for PBI * FalseWeight for BI. 02223 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 02224 } 02225 AddPredecessorToBlock(FalseDest, PredBlock, BB); 02226 PBI->setSuccessor(1, FalseDest); 02227 } 02228 if (NewWeights.size() == 2) { 02229 // Halve the weights if any of them cannot fit in an uint32_t 02230 FitWeights(NewWeights); 02231 02232 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end()); 02233 PBI->setMetadata(LLVMContext::MD_prof, 02234 MDBuilder(BI->getContext()). 02235 createBranchWeights(MDWeights)); 02236 } else 02237 PBI->setMetadata(LLVMContext::MD_prof, NULL); 02238 } else { 02239 // Update PHI nodes in the common successors. 02240 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { 02241 ConstantInt *PBI_C = cast<ConstantInt>( 02242 PHIs[i]->getIncomingValueForBlock(PBI->getParent())); 02243 assert(PBI_C->getType()->isIntegerTy(1)); 02244 Instruction *MergedCond = 0; 02245 if (PBI->getSuccessor(0) == TrueDest) { 02246 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) 02247 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) 02248 // is false: !PBI_Cond and BI_Value 02249 Instruction *NotCond = 02250 cast<Instruction>(Builder.CreateNot(PBI->getCondition(), 02251 "not.cond")); 02252 MergedCond = 02253 cast<Instruction>(Builder.CreateBinOp(Instruction::And, 02254 NotCond, New, 02255 "and.cond")); 02256 if (PBI_C->isOne()) 02257 MergedCond = 02258 cast<Instruction>(Builder.CreateBinOp(Instruction::Or, 02259 PBI->getCondition(), MergedCond, 02260 "or.cond")); 02261 } else { 02262 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) 02263 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) 02264 // is false: PBI_Cond and BI_Value 02265 MergedCond = 02266 cast<Instruction>(Builder.CreateBinOp(Instruction::And, 02267 PBI->getCondition(), New, 02268 "and.cond")); 02269 if (PBI_C->isOne()) { 02270 Instruction *NotCond = 02271 cast<Instruction>(Builder.CreateNot(PBI->getCondition(), 02272 "not.cond")); 02273 MergedCond = 02274 cast<Instruction>(Builder.CreateBinOp(Instruction::Or, 02275 NotCond, MergedCond, 02276 "or.cond")); 02277 } 02278 } 02279 // Update PHI Node. 02280 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()), 02281 MergedCond); 02282 } 02283 // Change PBI from Conditional to Unconditional. 02284 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); 02285 EraseTerminatorInstAndDCECond(PBI); 02286 PBI = New_PBI; 02287 } 02288 02289 // TODO: If BB is reachable from all paths through PredBlock, then we 02290 // could replace PBI's branch probabilities with BI's. 02291 02292 // Copy any debug value intrinsics into the end of PredBlock. 02293 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 02294 if (isa<DbgInfoIntrinsic>(*I)) 02295 I->clone()->insertBefore(PBI); 02296 02297 return true; 02298 } 02299 return false; 02300 } 02301 02302 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a 02303 /// predecessor of another block, this function tries to simplify it. We know 02304 /// that PBI and BI are both conditional branches, and BI is in one of the 02305 /// successor blocks of PBI - PBI branches to BI. 02306 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) { 02307 assert(PBI->isConditional() && BI->isConditional()); 02308 BasicBlock *BB = BI->getParent(); 02309 02310 // If this block ends with a branch instruction, and if there is a 02311 // predecessor that ends on a branch of the same condition, make 02312 // this conditional branch redundant. 02313 if (PBI->getCondition() == BI->getCondition() && 02314 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 02315 // Okay, the outcome of this conditional branch is statically 02316 // knowable. If this block had a single pred, handle specially. 02317 if (BB->getSinglePredecessor()) { 02318 // Turn this into a branch on constant. 02319 bool CondIsTrue = PBI->getSuccessor(0) == BB; 02320 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 02321 CondIsTrue)); 02322 return true; // Nuke the branch on constant. 02323 } 02324 02325 // Otherwise, if there are multiple predecessors, insert a PHI that merges 02326 // in the constant and simplify the block result. Subsequent passes of 02327 // simplifycfg will thread the block. 02328 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 02329 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 02330 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()), 02331 std::distance(PB, PE), 02332 BI->getCondition()->getName() + ".pr", 02333 BB->begin()); 02334 // Okay, we're going to insert the PHI node. Since PBI is not the only 02335 // predecessor, compute the PHI'd conditional value for all of the preds. 02336 // Any predecessor where the condition is not computable we keep symbolic. 02337 for (pred_iterator PI = PB; PI != PE; ++PI) { 02338 BasicBlock *P = *PI; 02339 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && 02340 PBI != BI && PBI->isConditional() && 02341 PBI->getCondition() == BI->getCondition() && 02342 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 02343 bool CondIsTrue = PBI->getSuccessor(0) == BB; 02344 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 02345 CondIsTrue), P); 02346 } else { 02347 NewPN->addIncoming(BI->getCondition(), P); 02348 } 02349 } 02350 02351 BI->setCondition(NewPN); 02352 return true; 02353 } 02354 } 02355 02356 // If this is a conditional branch in an empty block, and if any 02357 // predecessors is a conditional branch to one of our destinations, 02358 // fold the conditions into logical ops and one cond br. 02359 BasicBlock::iterator BBI = BB->begin(); 02360 // Ignore dbg intrinsics. 02361 while (isa<DbgInfoIntrinsic>(BBI)) 02362 ++BBI; 02363 if (&*BBI != BI) 02364 return false; 02365 02366 02367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 02368 if (CE->canTrap()) 02369 return false; 02370 02371 int PBIOp, BIOp; 02372 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) 02373 PBIOp = BIOp = 0; 02374 else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) 02375 PBIOp = 0, BIOp = 1; 02376 else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) 02377 PBIOp = 1, BIOp = 0; 02378 else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) 02379 PBIOp = BIOp = 1; 02380 else 02381 return false; 02382 02383 // Check to make sure that the other destination of this branch 02384 // isn't BB itself. If so, this is an infinite loop that will 02385 // keep getting unwound. 02386 if (PBI->getSuccessor(PBIOp) == BB) 02387 return false; 02388 02389 // Do not perform this transformation if it would require 02390 // insertion of a large number of select instructions. For targets 02391 // without predication/cmovs, this is a big pessimization. 02392 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 02393 02394 unsigned NumPhis = 0; 02395 for (BasicBlock::iterator II = CommonDest->begin(); 02396 isa<PHINode>(II); ++II, ++NumPhis) 02397 if (NumPhis > 2) // Disable this xform. 02398 return false; 02399 02400 // Finally, if everything is ok, fold the branches to logical ops. 02401 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 02402 02403 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 02404 << "AND: " << *BI->getParent()); 02405 02406 02407 // If OtherDest *is* BB, then BB is a basic block with a single conditional 02408 // branch in it, where one edge (OtherDest) goes back to itself but the other 02409 // exits. We don't *know* that the program avoids the infinite loop 02410 // (even though that seems likely). If we do this xform naively, we'll end up 02411 // recursively unpeeling the loop. Since we know that (after the xform is 02412 // done) that the block *is* infinite if reached, we just make it an obviously 02413 // infinite loop with no cond branch. 02414 if (OtherDest == BB) { 02415 // Insert it at the end of the function, because it's either code, 02416 // or it won't matter if it's hot. :) 02417 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(), 02418 "infloop", BB->getParent()); 02419 BranchInst::Create(InfLoopBlock, InfLoopBlock); 02420 OtherDest = InfLoopBlock; 02421 } 02422 02423 DEBUG(dbgs() << *PBI->getParent()->getParent()); 02424 02425 // BI may have other predecessors. Because of this, we leave 02426 // it alone, but modify PBI. 02427 02428 // Make sure we get to CommonDest on True&True directions. 02429 Value *PBICond = PBI->getCondition(); 02430 IRBuilder<true, NoFolder> Builder(PBI); 02431 if (PBIOp) 02432 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not"); 02433 02434 Value *BICond = BI->getCondition(); 02435 if (BIOp) 02436 BICond = Builder.CreateNot(BICond, BICond->getName()+".not"); 02437 02438 // Merge the conditions. 02439 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); 02440 02441 // Modify PBI to branch on the new condition to the new dests. 02442 PBI->setCondition(Cond); 02443 PBI->setSuccessor(0, CommonDest); 02444 PBI->setSuccessor(1, OtherDest); 02445 02446 // Update branch weight for PBI. 02447 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 02448 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, 02449 PredFalseWeight); 02450 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, 02451 SuccFalseWeight); 02452 if (PredHasWeights && SuccHasWeights) { 02453 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 02454 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight; 02455 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 02456 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 02457 // The weight to CommonDest should be PredCommon * SuccTotal + 02458 // PredOther * SuccCommon. 02459 // The weight to OtherDest should be PredOther * SuccOther. 02460 SmallVector<uint64_t, 2> NewWeights; 02461 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) + 02462 PredOther * SuccCommon); 02463 NewWeights.push_back(PredOther * SuccOther); 02464 // Halve the weights if any of them cannot fit in an uint32_t 02465 FitWeights(NewWeights); 02466 02467 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end()); 02468 PBI->setMetadata(LLVMContext::MD_prof, 02469 MDBuilder(BI->getContext()). 02470 createBranchWeights(MDWeights)); 02471 } 02472 02473 // OtherDest may have phi nodes. If so, add an entry from PBI's 02474 // block that are identical to the entries for BI's block. 02475 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 02476 02477 // We know that the CommonDest already had an edge from PBI to 02478 // it. If it has PHIs though, the PHIs may have different 02479 // entries for BB and PBI's BB. If so, insert a select to make 02480 // them agree. 02481 PHINode *PN; 02482 for (BasicBlock::iterator II = CommonDest->begin(); 02483 (PN = dyn_cast<PHINode>(II)); ++II) { 02484 Value *BIV = PN->getIncomingValueForBlock(BB); 02485 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 02486 Value *PBIV = PN->getIncomingValue(PBBIdx); 02487 if (BIV != PBIV) { 02488 // Insert a select in PBI to pick the right value. 02489 Value *NV = cast<SelectInst> 02490 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux")); 02491 PN->setIncomingValue(PBBIdx, NV); 02492 } 02493 } 02494 02495 DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 02496 DEBUG(dbgs() << *PBI->getParent()->getParent()); 02497 02498 // This basic block is probably dead. We know it has at least 02499 // one fewer predecessor. 02500 return true; 02501 } 02502 02503 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a 02504 // branch to TrueBB if Cond is true or to FalseBB if Cond is false. 02505 // Takes care of updating the successors and removing the old terminator. 02506 // Also makes sure not to introduce new successors by assuming that edges to 02507 // non-successor TrueBBs and FalseBBs aren't reachable. 02508 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, 02509 BasicBlock *TrueBB, BasicBlock *FalseBB, 02510 uint32_t TrueWeight, 02511 uint32_t FalseWeight){ 02512 // Remove any superfluous successor edges from the CFG. 02513 // First, figure out which successors to preserve. 02514 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 02515 // successor. 02516 BasicBlock *KeepEdge1 = TrueBB; 02517 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0; 02518 02519 // Then remove the rest. 02520 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) { 02521 BasicBlock *Succ = OldTerm->getSuccessor(I); 02522 // Make sure only to keep exactly one copy of each edge. 02523 if (Succ == KeepEdge1) 02524 KeepEdge1 = 0; 02525 else if (Succ == KeepEdge2) 02526 KeepEdge2 = 0; 02527 else 02528 Succ->removePredecessor(OldTerm->getParent()); 02529 } 02530 02531 IRBuilder<> Builder(OldTerm); 02532 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 02533 02534 // Insert an appropriate new terminator. 02535 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) { 02536 if (TrueBB == FalseBB) 02537 // We were only looking for one successor, and it was present. 02538 // Create an unconditional branch to it. 02539 Builder.CreateBr(TrueBB); 02540 else { 02541 // We found both of the successors we were looking for. 02542 // Create a conditional branch sharing the condition of the select. 02543 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 02544 if (TrueWeight != FalseWeight) 02545 NewBI->setMetadata(LLVMContext::MD_prof, 02546 MDBuilder(OldTerm->getContext()). 02547 createBranchWeights(TrueWeight, FalseWeight)); 02548 } 02549 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 02550 // Neither of the selected blocks were successors, so this 02551 // terminator must be unreachable. 02552 new UnreachableInst(OldTerm->getContext(), OldTerm); 02553 } else { 02554 // One of the selected values was a successor, but the other wasn't. 02555 // Insert an unconditional branch to the one that was found; 02556 // the edge to the one that wasn't must be unreachable. 02557 if (KeepEdge1 == 0) 02558 // Only TrueBB was found. 02559 Builder.CreateBr(TrueBB); 02560 else 02561 // Only FalseBB was found. 02562 Builder.CreateBr(FalseBB); 02563 } 02564 02565 EraseTerminatorInstAndDCECond(OldTerm); 02566 return true; 02567 } 02568 02569 // SimplifySwitchOnSelect - Replaces 02570 // (switch (select cond, X, Y)) on constant X, Y 02571 // with a branch - conditional if X and Y lead to distinct BBs, 02572 // unconditional otherwise. 02573 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { 02574 // Check for constant integer values in the select. 02575 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 02576 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 02577 if (!TrueVal || !FalseVal) 02578 return false; 02579 02580 // Find the relevant condition and destinations. 02581 Value *Condition = Select->getCondition(); 02582 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor(); 02583 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor(); 02584 02585 // Get weight for TrueBB and FalseBB. 02586 uint32_t TrueWeight = 0, FalseWeight = 0; 02587 SmallVector<uint64_t, 8> Weights; 02588 bool HasWeights = HasBranchWeights(SI); 02589 if (HasWeights) { 02590 GetBranchWeights(SI, Weights); 02591 if (Weights.size() == 1 + SI->getNumCases()) { 02592 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal). 02593 getSuccessorIndex()]; 02594 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal). 02595 getSuccessorIndex()]; 02596 } 02597 } 02598 02599 // Perform the actual simplification. 02600 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, 02601 TrueWeight, FalseWeight); 02602 } 02603 02604 // SimplifyIndirectBrOnSelect - Replaces 02605 // (indirectbr (select cond, blockaddress(@fn, BlockA), 02606 // blockaddress(@fn, BlockB))) 02607 // with 02608 // (br cond, BlockA, BlockB). 02609 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { 02610 // Check that both operands of the select are block addresses. 02611 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 02612 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 02613 if (!TBA || !FBA) 02614 return false; 02615 02616 // Extract the actual blocks. 02617 BasicBlock *TrueBB = TBA->getBasicBlock(); 02618 BasicBlock *FalseBB = FBA->getBasicBlock(); 02619 02620 // Perform the actual simplification. 02621 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 02622 0, 0); 02623 } 02624 02625 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp 02626 /// instruction (a seteq/setne with a constant) as the only instruction in a 02627 /// block that ends with an uncond branch. We are looking for a very specific 02628 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 02629 /// this case, we merge the first two "or's of icmp" into a switch, but then the 02630 /// default value goes to an uncond block with a seteq in it, we get something 02631 /// like: 02632 /// 02633 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 02634 /// DEFAULT: 02635 /// %tmp = icmp eq i8 %A, 92 02636 /// br label %end 02637 /// end: 02638 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 02639 /// 02640 /// We prefer to split the edge to 'end' so that there is a true/false entry to 02641 /// the PHI, merging the third icmp into the switch. 02642 static bool TryToSimplifyUncondBranchWithICmpInIt( 02643 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI, 02644 const DataLayout *TD) { 02645 BasicBlock *BB = ICI->getParent(); 02646 02647 // If the block has any PHIs in it or the icmp has multiple uses, it is too 02648 // complex. 02649 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false; 02650 02651 Value *V = ICI->getOperand(0); 02652 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 02653 02654 // The pattern we're looking for is where our only predecessor is a switch on 02655 // 'V' and this block is the default case for the switch. In this case we can 02656 // fold the compared value into the switch to simplify things. 02657 BasicBlock *Pred = BB->getSinglePredecessor(); 02658 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false; 02659 02660 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 02661 if (SI->getCondition() != V) 02662 return false; 02663 02664 // If BB is reachable on a non-default case, then we simply know the value of 02665 // V in this block. Substitute it and constant fold the icmp instruction 02666 // away. 02667 if (SI->getDefaultDest() != BB) { 02668 ConstantInt *VVal = SI->findCaseDest(BB); 02669 assert(VVal && "Should have a unique destination value"); 02670 ICI->setOperand(0, VVal); 02671 02672 if (Value *V = SimplifyInstruction(ICI, TD)) { 02673 ICI->replaceAllUsesWith(V); 02674 ICI->eraseFromParent(); 02675 } 02676 // BB is now empty, so it is likely to simplify away. 02677 return SimplifyCFG(BB, TTI, TD) | true; 02678 } 02679 02680 // Ok, the block is reachable from the default dest. If the constant we're 02681 // comparing exists in one of the other edges, then we can constant fold ICI 02682 // and zap it. 02683 if (SI->findCaseValue(Cst) != SI->case_default()) { 02684 Value *V; 02685 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 02686 V = ConstantInt::getFalse(BB->getContext()); 02687 else 02688 V = ConstantInt::getTrue(BB->getContext()); 02689 02690 ICI->replaceAllUsesWith(V); 02691 ICI->eraseFromParent(); 02692 // BB is now empty, so it is likely to simplify away. 02693 return SimplifyCFG(BB, TTI, TD) | true; 02694 } 02695 02696 // The use of the icmp has to be in the 'end' block, by the only PHI node in 02697 // the block. 02698 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 02699 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back()); 02700 if (PHIUse == 0 || PHIUse != &SuccBlock->front() || 02701 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 02702 return false; 02703 02704 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 02705 // true in the PHI. 02706 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 02707 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 02708 02709 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 02710 std::swap(DefaultCst, NewCst); 02711 02712 // Replace ICI (which is used by the PHI for the default value) with true or 02713 // false depending on if it is EQ or NE. 02714 ICI->replaceAllUsesWith(DefaultCst); 02715 ICI->eraseFromParent(); 02716 02717 // Okay, the switch goes to this block on a default value. Add an edge from 02718 // the switch to the merge point on the compared value. 02719 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge", 02720 BB->getParent(), BB); 02721 SmallVector<uint64_t, 8> Weights; 02722 bool HasWeights = HasBranchWeights(SI); 02723 if (HasWeights) { 02724 GetBranchWeights(SI, Weights); 02725 if (Weights.size() == 1 + SI->getNumCases()) { 02726 // Split weight for default case to case for "Cst". 02727 Weights[0] = (Weights[0]+1) >> 1; 02728 Weights.push_back(Weights[0]); 02729 02730 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 02731 SI->setMetadata(LLVMContext::MD_prof, 02732 MDBuilder(SI->getContext()). 02733 createBranchWeights(MDWeights)); 02734 } 02735 } 02736 SI->addCase(Cst, NewBB); 02737 02738 // NewBB branches to the phi block, add the uncond branch and the phi entry. 02739 Builder.SetInsertPoint(NewBB); 02740 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 02741 Builder.CreateBr(SuccBlock); 02742 PHIUse->addIncoming(NewCst, NewBB); 02743 return true; 02744 } 02745 02746 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch. 02747 /// Check to see if it is branching on an or/and chain of icmp instructions, and 02748 /// fold it into a switch instruction if so. 02749 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *TD, 02750 IRBuilder<> &Builder) { 02751 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 02752 if (Cond == 0) return false; 02753 02754 02755 // Change br (X == 0 | X == 1), T, F into a switch instruction. 02756 // If this is a bunch of seteq's or'd together, or if it's a bunch of 02757 // 'setne's and'ed together, collect them. 02758 Value *CompVal = 0; 02759 std::vector<ConstantInt*> Values; 02760 bool TrueWhenEqual = true; 02761 Value *ExtraCase = 0; 02762 unsigned UsedICmps = 0; 02763 02764 if (Cond->getOpcode() == Instruction::Or) { 02765 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true, 02766 UsedICmps); 02767 } else if (Cond->getOpcode() == Instruction::And) { 02768 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false, 02769 UsedICmps); 02770 TrueWhenEqual = false; 02771 } 02772 02773 // If we didn't have a multiply compared value, fail. 02774 if (CompVal == 0) return false; 02775 02776 // Avoid turning single icmps into a switch. 02777 if (UsedICmps <= 1) 02778 return false; 02779 02780 // There might be duplicate constants in the list, which the switch 02781 // instruction can't handle, remove them now. 02782 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 02783 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 02784 02785 // If Extra was used, we require at least two switch values to do the 02786 // transformation. A switch with one value is just an cond branch. 02787 if (ExtraCase && Values.size() < 2) return false; 02788 02789 // TODO: Preserve branch weight metadata, similarly to how 02790 // FoldValueComparisonIntoPredecessors preserves it. 02791 02792 // Figure out which block is which destination. 02793 BasicBlock *DefaultBB = BI->getSuccessor(1); 02794 BasicBlock *EdgeBB = BI->getSuccessor(0); 02795 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); 02796 02797 BasicBlock *BB = BI->getParent(); 02798 02799 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 02800 << " cases into SWITCH. BB is:\n" << *BB); 02801 02802 // If there are any extra values that couldn't be folded into the switch 02803 // then we evaluate them with an explicit branch first. Split the block 02804 // right before the condbr to handle it. 02805 if (ExtraCase) { 02806 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test"); 02807 // Remove the uncond branch added to the old block. 02808 TerminatorInst *OldTI = BB->getTerminator(); 02809 Builder.SetInsertPoint(OldTI); 02810 02811 if (TrueWhenEqual) 02812 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 02813 else 02814 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 02815 02816 OldTI->eraseFromParent(); 02817 02818 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 02819 // for the edge we just added. 02820 AddPredecessorToBlock(EdgeBB, BB, NewBB); 02821 02822 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 02823 << "\nEXTRABB = " << *BB); 02824 BB = NewBB; 02825 } 02826 02827 Builder.SetInsertPoint(BI); 02828 // Convert pointer to int before we switch. 02829 if (CompVal->getType()->isPointerTy()) { 02830 assert(TD && "Cannot switch on pointer without DataLayout"); 02831 CompVal = Builder.CreatePtrToInt(CompVal, 02832 TD->getIntPtrType(CompVal->getContext()), 02833 "magicptr"); 02834 } 02835 02836 // Create the new switch instruction now. 02837 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 02838 02839 // Add all of the 'cases' to the switch instruction. 02840 for (unsigned i = 0, e = Values.size(); i != e; ++i) 02841 New->addCase(Values[i], EdgeBB); 02842 02843 // We added edges from PI to the EdgeBB. As such, if there were any 02844 // PHI nodes in EdgeBB, they need entries to be added corresponding to 02845 // the number of edges added. 02846 for (BasicBlock::iterator BBI = EdgeBB->begin(); 02847 isa<PHINode>(BBI); ++BBI) { 02848 PHINode *PN = cast<PHINode>(BBI); 02849 Value *InVal = PN->getIncomingValueForBlock(BB); 02850 for (unsigned i = 0, e = Values.size()-1; i != e; ++i) 02851 PN->addIncoming(InVal, BB); 02852 } 02853 02854 // Erase the old branch instruction. 02855 EraseTerminatorInstAndDCECond(BI); 02856 02857 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 02858 return true; 02859 } 02860 02861 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 02862 // If this is a trivial landing pad that just continues unwinding the caught 02863 // exception then zap the landing pad, turning its invokes into calls. 02864 BasicBlock *BB = RI->getParent(); 02865 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); 02866 if (RI->getValue() != LPInst) 02867 // Not a landing pad, or the resume is not unwinding the exception that 02868 // caused control to branch here. 02869 return false; 02870 02871 // Check that there are no other instructions except for debug intrinsics. 02872 BasicBlock::iterator I = LPInst, E = RI; 02873 while (++I != E) 02874 if (!isa<DbgInfoIntrinsic>(I)) 02875 return false; 02876 02877 // Turn all invokes that unwind here into calls and delete the basic block. 02878 bool InvokeRequiresTableEntry = false; 02879 bool Changed = false; 02880 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 02881 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator()); 02882 02883 if (II->hasFnAttr(Attribute::UWTable)) { 02884 // Don't remove an `invoke' instruction if the ABI requires an entry into 02885 // the table. 02886 InvokeRequiresTableEntry = true; 02887 continue; 02888 } 02889 02890 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3); 02891 02892 // Insert a call instruction before the invoke. 02893 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II); 02894 Call->takeName(II); 02895 Call->setCallingConv(II->getCallingConv()); 02896 Call->setAttributes(II->getAttributes()); 02897 Call->setDebugLoc(II->getDebugLoc()); 02898 02899 // Anything that used the value produced by the invoke instruction now uses 02900 // the value produced by the call instruction. Note that we do this even 02901 // for void functions and calls with no uses so that the callgraph edge is 02902 // updated. 02903 II->replaceAllUsesWith(Call); 02904 BB->removePredecessor(II->getParent()); 02905 02906 // Insert a branch to the normal destination right before the invoke. 02907 BranchInst::Create(II->getNormalDest(), II); 02908 02909 // Finally, delete the invoke instruction! 02910 II->eraseFromParent(); 02911 Changed = true; 02912 } 02913 02914 if (!InvokeRequiresTableEntry) 02915 // The landingpad is now unreachable. Zap it. 02916 BB->eraseFromParent(); 02917 02918 return Changed; 02919 } 02920 02921 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { 02922 BasicBlock *BB = RI->getParent(); 02923 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false; 02924 02925 // Find predecessors that end with branches. 02926 SmallVector<BasicBlock*, 8> UncondBranchPreds; 02927 SmallVector<BranchInst*, 8> CondBranchPreds; 02928 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 02929 BasicBlock *P = *PI; 02930 TerminatorInst *PTI = P->getTerminator(); 02931 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { 02932 if (BI->isUnconditional()) 02933 UncondBranchPreds.push_back(P); 02934 else 02935 CondBranchPreds.push_back(BI); 02936 } 02937 } 02938 02939 // If we found some, do the transformation! 02940 if (!UncondBranchPreds.empty() && DupRet) { 02941 while (!UncondBranchPreds.empty()) { 02942 BasicBlock *Pred = UncondBranchPreds.pop_back_val(); 02943 DEBUG(dbgs() << "FOLDING: " << *BB 02944 << "INTO UNCOND BRANCH PRED: " << *Pred); 02945 (void)FoldReturnIntoUncondBranch(RI, BB, Pred); 02946 } 02947 02948 // If we eliminated all predecessors of the block, delete the block now. 02949 if (pred_begin(BB) == pred_end(BB)) 02950 // We know there are no successors, so just nuke the block. 02951 BB->eraseFromParent(); 02952 02953 return true; 02954 } 02955 02956 // Check out all of the conditional branches going to this return 02957 // instruction. If any of them just select between returns, change the 02958 // branch itself into a select/return pair. 02959 while (!CondBranchPreds.empty()) { 02960 BranchInst *BI = CondBranchPreds.pop_back_val(); 02961 02962 // Check to see if the non-BB successor is also a return block. 02963 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && 02964 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && 02965 SimplifyCondBranchToTwoReturns(BI, Builder)) 02966 return true; 02967 } 02968 return false; 02969 } 02970 02971 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { 02972 BasicBlock *BB = UI->getParent(); 02973 02974 bool Changed = false; 02975 02976 // If there are any instructions immediately before the unreachable that can 02977 // be removed, do so. 02978 while (UI != BB->begin()) { 02979 BasicBlock::iterator BBI = UI; 02980 --BBI; 02981 // Do not delete instructions that can have side effects which might cause 02982 // the unreachable to not be reachable; specifically, calls and volatile 02983 // operations may have this effect. 02984 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break; 02985 02986 if (BBI->mayHaveSideEffects()) { 02987 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { 02988 if (SI->isVolatile()) 02989 break; 02990 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 02991 if (LI->isVolatile()) 02992 break; 02993 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { 02994 if (RMWI->isVolatile()) 02995 break; 02996 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { 02997 if (CXI->isVolatile()) 02998 break; 02999 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && 03000 !isa<LandingPadInst>(BBI)) { 03001 break; 03002 } 03003 // Note that deleting LandingPad's here is in fact okay, although it 03004 // involves a bit of subtle reasoning. If this inst is a LandingPad, 03005 // all the predecessors of this block will be the unwind edges of Invokes, 03006 // and we can therefore guarantee this block will be erased. 03007 } 03008 03009 // Delete this instruction (any uses are guaranteed to be dead) 03010 if (!BBI->use_empty()) 03011 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 03012 BBI->eraseFromParent(); 03013 Changed = true; 03014 } 03015 03016 // If the unreachable instruction is the first in the block, take a gander 03017 // at all of the predecessors of this instruction, and simplify them. 03018 if (&BB->front() != UI) return Changed; 03019 03020 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB)); 03021 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 03022 TerminatorInst *TI = Preds[i]->getTerminator(); 03023 IRBuilder<> Builder(TI); 03024 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 03025 if (BI->isUnconditional()) { 03026 if (BI->getSuccessor(0) == BB) { 03027 new UnreachableInst(TI->getContext(), TI); 03028 TI->eraseFromParent(); 03029 Changed = true; 03030 } 03031 } else { 03032 if (BI->getSuccessor(0) == BB) { 03033 Builder.CreateBr(BI->getSuccessor(1)); 03034 EraseTerminatorInstAndDCECond(BI); 03035 } else if (BI->getSuccessor(1) == BB) { 03036 Builder.CreateBr(BI->getSuccessor(0)); 03037 EraseTerminatorInstAndDCECond(BI); 03038 Changed = true; 03039 } 03040 } 03041 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 03042 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 03043 i != e; ++i) 03044 if (i.getCaseSuccessor() == BB) { 03045 BB->removePredecessor(SI->getParent()); 03046 SI->removeCase(i); 03047 --i; --e; 03048 Changed = true; 03049 } 03050 // If the default value is unreachable, figure out the most popular 03051 // destination and make it the default. 03052 if (SI->getDefaultDest() == BB) { 03053 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity; 03054 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 03055 i != e; ++i) { 03056 std::pair<unsigned, unsigned> &entry = 03057 Popularity[i.getCaseSuccessor()]; 03058 if (entry.first == 0) { 03059 entry.first = 1; 03060 entry.second = i.getCaseIndex(); 03061 } else { 03062 entry.first++; 03063 } 03064 } 03065 03066 // Find the most popular block. 03067 unsigned MaxPop = 0; 03068 unsigned MaxIndex = 0; 03069 BasicBlock *MaxBlock = 0; 03070 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator 03071 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) { 03072 if (I->second.first > MaxPop || 03073 (I->second.first == MaxPop && MaxIndex > I->second.second)) { 03074 MaxPop = I->second.first; 03075 MaxIndex = I->second.second; 03076 MaxBlock = I->first; 03077 } 03078 } 03079 if (MaxBlock) { 03080 // Make this the new default, allowing us to delete any explicit 03081 // edges to it. 03082 SI->setDefaultDest(MaxBlock); 03083 Changed = true; 03084 03085 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from 03086 // it. 03087 if (isa<PHINode>(MaxBlock->begin())) 03088 for (unsigned i = 0; i != MaxPop-1; ++i) 03089 MaxBlock->removePredecessor(SI->getParent()); 03090 03091 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 03092 i != e; ++i) 03093 if (i.getCaseSuccessor() == MaxBlock) { 03094 SI->removeCase(i); 03095 --i; --e; 03096 } 03097 } 03098 } 03099 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { 03100 if (II->getUnwindDest() == BB) { 03101 // Convert the invoke to a call instruction. This would be a good 03102 // place to note that the call does not throw though. 03103 BranchInst *BI = Builder.CreateBr(II->getNormalDest()); 03104 II->removeFromParent(); // Take out of symbol table 03105 03106 // Insert the call now... 03107 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3); 03108 Builder.SetInsertPoint(BI); 03109 CallInst *CI = Builder.CreateCall(II->getCalledValue(), 03110 Args, II->getName()); 03111 CI->setCallingConv(II->getCallingConv()); 03112 CI->setAttributes(II->getAttributes()); 03113 // If the invoke produced a value, the call does now instead. 03114 II->replaceAllUsesWith(CI); 03115 delete II; 03116 Changed = true; 03117 } 03118 } 03119 } 03120 03121 // If this block is now dead, remove it. 03122 if (pred_begin(BB) == pred_end(BB) && 03123 BB != &BB->getParent()->getEntryBlock()) { 03124 // We know there are no successors, so just nuke the block. 03125 BB->eraseFromParent(); 03126 return true; 03127 } 03128 03129 return Changed; 03130 } 03131 03132 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a 03133 /// integer range comparison into a sub, an icmp and a branch. 03134 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { 03135 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 03136 03137 // Make sure all cases point to the same destination and gather the values. 03138 SmallVector<ConstantInt *, 16> Cases; 03139 SwitchInst::CaseIt I = SI->case_begin(); 03140 Cases.push_back(I.getCaseValue()); 03141 SwitchInst::CaseIt PrevI = I++; 03142 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) { 03143 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor()) 03144 return false; 03145 Cases.push_back(I.getCaseValue()); 03146 } 03147 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered"); 03148 03149 // Sort the case values, then check if they form a range we can transform. 03150 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 03151 for (unsigned I = 1, E = Cases.size(); I != E; ++I) { 03152 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1) 03153 return false; 03154 } 03155 03156 Constant *Offset = ConstantExpr::getNeg(Cases.back()); 03157 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()); 03158 03159 Value *Sub = SI->getCondition(); 03160 if (!Offset->isNullValue()) 03161 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off"); 03162 Value *Cmp; 03163 // If NumCases overflowed, then all possible values jump to the successor. 03164 if (NumCases->isNullValue() && SI->getNumCases() != 0) 03165 Cmp = ConstantInt::getTrue(SI->getContext()); 03166 else 03167 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 03168 BranchInst *NewBI = Builder.CreateCondBr( 03169 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest()); 03170 03171 // Update weight for the newly-created conditional branch. 03172 SmallVector<uint64_t, 8> Weights; 03173 bool HasWeights = HasBranchWeights(SI); 03174 if (HasWeights) { 03175 GetBranchWeights(SI, Weights); 03176 if (Weights.size() == 1 + SI->getNumCases()) { 03177 // Combine all weights for the cases to be the true weight of NewBI. 03178 // We assume that the sum of all weights for a Terminator can fit into 32 03179 // bits. 03180 uint32_t NewTrueWeight = 0; 03181 for (unsigned I = 1, E = Weights.size(); I != E; ++I) 03182 NewTrueWeight += (uint32_t)Weights[I]; 03183 NewBI->setMetadata(LLVMContext::MD_prof, 03184 MDBuilder(SI->getContext()). 03185 createBranchWeights(NewTrueWeight, 03186 (uint32_t)Weights[0])); 03187 } 03188 } 03189 03190 // Prune obsolete incoming values off the successor's PHI nodes. 03191 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin(); 03192 isa<PHINode>(BBI); ++BBI) { 03193 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I) 03194 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 03195 } 03196 SI->eraseFromParent(); 03197 03198 return true; 03199 } 03200 03201 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch 03202 /// and use it to remove dead cases. 03203 static bool EliminateDeadSwitchCases(SwitchInst *SI) { 03204 Value *Cond = SI->getCondition(); 03205 unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth(); 03206 APInt KnownZero(Bits, 0), KnownOne(Bits, 0); 03207 ComputeMaskedBits(Cond, KnownZero, KnownOne); 03208 03209 // Gather dead cases. 03210 SmallVector<ConstantInt*, 8> DeadCases; 03211 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { 03212 if ((I.getCaseValue()->getValue() & KnownZero) != 0 || 03213 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) { 03214 DeadCases.push_back(I.getCaseValue()); 03215 DEBUG(dbgs() << "SimplifyCFG: switch case '" 03216 << I.getCaseValue() << "' is dead.\n"); 03217 } 03218 } 03219 03220 SmallVector<uint64_t, 8> Weights; 03221 bool HasWeight = HasBranchWeights(SI); 03222 if (HasWeight) { 03223 GetBranchWeights(SI, Weights); 03224 HasWeight = (Weights.size() == 1 + SI->getNumCases()); 03225 } 03226 03227 // Remove dead cases from the switch. 03228 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) { 03229 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]); 03230 assert(Case != SI->case_default() && 03231 "Case was not found. Probably mistake in DeadCases forming."); 03232 if (HasWeight) { 03233 std::swap(Weights[Case.getCaseIndex()+1], Weights.back()); 03234 Weights.pop_back(); 03235 } 03236 03237 // Prune unused values from PHI nodes. 03238 Case.getCaseSuccessor()->removePredecessor(SI->getParent()); 03239 SI->removeCase(Case); 03240 } 03241 if (HasWeight) { 03242 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 03243 SI->setMetadata(LLVMContext::MD_prof, 03244 MDBuilder(SI->getParent()->getContext()). 03245 createBranchWeights(MDWeights)); 03246 } 03247 03248 return !DeadCases.empty(); 03249 } 03250 03251 /// FindPHIForConditionForwarding - If BB would be eligible for simplification 03252 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 03253 /// by an unconditional branch), look at the phi node for BB in the successor 03254 /// block and see if the incoming value is equal to CaseValue. If so, return 03255 /// the phi node, and set PhiIndex to BB's index in the phi node. 03256 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 03257 BasicBlock *BB, 03258 int *PhiIndex) { 03259 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 03260 return NULL; // BB must be empty to be a candidate for simplification. 03261 if (!BB->getSinglePredecessor()) 03262 return NULL; // BB must be dominated by the switch. 03263 03264 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 03265 if (!Branch || !Branch->isUnconditional()) 03266 return NULL; // Terminator must be unconditional branch. 03267 03268 BasicBlock *Succ = Branch->getSuccessor(0); 03269 03270 BasicBlock::iterator I = Succ->begin(); 03271 while (PHINode *PHI = dyn_cast<PHINode>(I++)) { 03272 int Idx = PHI->getBasicBlockIndex(BB); 03273 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 03274 03275 Value *InValue = PHI->getIncomingValue(Idx); 03276 if (InValue != CaseValue) continue; 03277 03278 *PhiIndex = Idx; 03279 return PHI; 03280 } 03281 03282 return NULL; 03283 } 03284 03285 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch 03286 /// instruction to a phi node dominated by the switch, if that would mean that 03287 /// some of the destination blocks of the switch can be folded away. 03288 /// Returns true if a change is made. 03289 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 03290 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap; 03291 ForwardingNodesMap ForwardingNodes; 03292 03293 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { 03294 ConstantInt *CaseValue = I.getCaseValue(); 03295 BasicBlock *CaseDest = I.getCaseSuccessor(); 03296 03297 int PhiIndex; 03298 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest, 03299 &PhiIndex); 03300 if (!PHI) continue; 03301 03302 ForwardingNodes[PHI].push_back(PhiIndex); 03303 } 03304 03305 bool Changed = false; 03306 03307 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(), 03308 E = ForwardingNodes.end(); I != E; ++I) { 03309 PHINode *Phi = I->first; 03310 SmallVector<int,4> &Indexes = I->second; 03311 03312 if (Indexes.size() < 2) continue; 03313 03314 for (size_t I = 0, E = Indexes.size(); I != E; ++I) 03315 Phi->setIncomingValue(Indexes[I], SI->getCondition()); 03316 Changed = true; 03317 } 03318 03319 return Changed; 03320 } 03321 03322 /// ValidLookupTableConstant - Return true if the backend will be able to handle 03323 /// initializing an array of constants like C. 03324 static bool ValidLookupTableConstant(Constant *C) { 03325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 03326 return CE->isGEPWithNoNotionalOverIndexing(); 03327 03328 return isa<ConstantFP>(C) || 03329 isa<ConstantInt>(C) || 03330 isa<ConstantPointerNull>(C) || 03331 isa<GlobalValue>(C) || 03332 isa<UndefValue>(C); 03333 } 03334 03335 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up 03336 /// its constant value in ConstantPool, returning 0 if it's not there. 03337 static Constant *LookupConstant(Value *V, 03338 const SmallDenseMap<Value*, Constant*>& ConstantPool) { 03339 if (Constant *C = dyn_cast<Constant>(V)) 03340 return C; 03341 return ConstantPool.lookup(V); 03342 } 03343 03344 /// ConstantFold - Try to fold instruction I into a constant. This works for 03345 /// simple instructions such as binary operations where both operands are 03346 /// constant or can be replaced by constants from the ConstantPool. Returns the 03347 /// resulting constant on success, 0 otherwise. 03348 static Constant *ConstantFold(Instruction *I, 03349 const SmallDenseMap<Value*, Constant*>& ConstantPool) { 03350 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 03351 Constant *A = LookupConstant(BO->getOperand(0), ConstantPool); 03352 if (!A) 03353 return 0; 03354 Constant *B = LookupConstant(BO->getOperand(1), ConstantPool); 03355 if (!B) 03356 return 0; 03357 return ConstantExpr::get(BO->getOpcode(), A, B); 03358 } 03359 03360 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 03361 Constant *A = LookupConstant(I->getOperand(0), ConstantPool); 03362 if (!A) 03363 return 0; 03364 Constant *B = LookupConstant(I->getOperand(1), ConstantPool); 03365 if (!B) 03366 return 0; 03367 return ConstantExpr::getCompare(Cmp->getPredicate(), A, B); 03368 } 03369 03370 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 03371 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 03372 if (!A) 03373 return 0; 03374 if (A->isAllOnesValue()) 03375 return LookupConstant(Select->getTrueValue(), ConstantPool); 03376 if (A->isNullValue()) 03377 return LookupConstant(Select->getFalseValue(), ConstantPool); 03378 return 0; 03379 } 03380 03381 if (CastInst *Cast = dyn_cast<CastInst>(I)) { 03382 Constant *A = LookupConstant(I->getOperand(0), ConstantPool); 03383 if (!A) 03384 return 0; 03385 return ConstantExpr::getCast(Cast->getOpcode(), A, Cast->getDestTy()); 03386 } 03387 03388 return 0; 03389 } 03390 03391 /// GetCaseResults - Try to determine the resulting constant values in phi nodes 03392 /// at the common destination basic block, *CommonDest, for one of the case 03393 /// destionations CaseDest corresponding to value CaseVal (0 for the default 03394 /// case), of a switch instruction SI. 03395 static bool GetCaseResults(SwitchInst *SI, 03396 ConstantInt *CaseVal, 03397 BasicBlock *CaseDest, 03398 BasicBlock **CommonDest, 03399 SmallVector<std::pair<PHINode*,Constant*>, 4> &Res) { 03400 // The block from which we enter the common destination. 03401 BasicBlock *Pred = SI->getParent(); 03402 03403 // If CaseDest is empty except for some side-effect free instructions through 03404 // which we can constant-propagate the CaseVal, continue to its successor. 03405 SmallDenseMap<Value*, Constant*> ConstantPool; 03406 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 03407 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E; 03408 ++I) { 03409 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) { 03410 // If the terminator is a simple branch, continue to the next block. 03411 if (T->getNumSuccessors() != 1) 03412 return false; 03413 Pred = CaseDest; 03414 CaseDest = T->getSuccessor(0); 03415 } else if (isa<DbgInfoIntrinsic>(I)) { 03416 // Skip debug intrinsic. 03417 continue; 03418 } else if (Constant *C = ConstantFold(I, ConstantPool)) { 03419 // Instruction is side-effect free and constant. 03420 ConstantPool.insert(std::make_pair(I, C)); 03421 } else { 03422 break; 03423 } 03424 } 03425 03426 // If we did not have a CommonDest before, use the current one. 03427 if (!*CommonDest) 03428 *CommonDest = CaseDest; 03429 // If the destination isn't the common one, abort. 03430 if (CaseDest != *CommonDest) 03431 return false; 03432 03433 // Get the values for this case from phi nodes in the destination block. 03434 BasicBlock::iterator I = (*CommonDest)->begin(); 03435 while (PHINode *PHI = dyn_cast<PHINode>(I++)) { 03436 int Idx = PHI->getBasicBlockIndex(Pred); 03437 if (Idx == -1) 03438 continue; 03439 03440 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx), 03441 ConstantPool); 03442 if (!ConstVal) 03443 return false; 03444 03445 // Note: If the constant comes from constant-propagating the case value 03446 // through the CaseDest basic block, it will be safe to remove the 03447 // instructions in that block. They cannot be used (except in the phi nodes 03448 // we visit) outside CaseDest, because that block does not dominate its 03449 // successor. If it did, we would not be in this phi node. 03450 03451 // Be conservative about which kinds of constants we support. 03452 if (!ValidLookupTableConstant(ConstVal)) 03453 return false; 03454 03455 Res.push_back(std::make_pair(PHI, ConstVal)); 03456 } 03457 03458 return true; 03459 } 03460 03461 namespace { 03462 /// SwitchLookupTable - This class represents a lookup table that can be used 03463 /// to replace a switch. 03464 class SwitchLookupTable { 03465 public: 03466 /// SwitchLookupTable - Create a lookup table to use as a switch replacement 03467 /// with the contents of Values, using DefaultValue to fill any holes in the 03468 /// table. 03469 SwitchLookupTable(Module &M, 03470 uint64_t TableSize, 03471 ConstantInt *Offset, 03472 const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values, 03473 Constant *DefaultValue, 03474 const DataLayout *TD); 03475 03476 /// BuildLookup - Build instructions with Builder to retrieve the value at 03477 /// the position given by Index in the lookup table. 03478 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 03479 03480 /// WouldFitInRegister - Return true if a table with TableSize elements of 03481 /// type ElementType would fit in a target-legal register. 03482 static bool WouldFitInRegister(const DataLayout *TD, 03483 uint64_t TableSize, 03484 const Type *ElementType); 03485 03486 private: 03487 // Depending on the contents of the table, it can be represented in 03488 // different ways. 03489 enum { 03490 // For tables where each element contains the same value, we just have to 03491 // store that single value and return it for each lookup. 03492 SingleValueKind, 03493 03494 // For small tables with integer elements, we can pack them into a bitmap 03495 // that fits into a target-legal register. Values are retrieved by 03496 // shift and mask operations. 03497 BitMapKind, 03498 03499 // The table is stored as an array of values. Values are retrieved by load 03500 // instructions from the table. 03501 ArrayKind 03502 } Kind; 03503 03504 // For SingleValueKind, this is the single value. 03505 Constant *SingleValue; 03506 03507 // For BitMapKind, this is the bitmap. 03508 ConstantInt *BitMap; 03509 IntegerType *BitMapElementTy; 03510 03511 // For ArrayKind, this is the array. 03512 GlobalVariable *Array; 03513 }; 03514 } 03515 03516 SwitchLookupTable::SwitchLookupTable(Module &M, 03517 uint64_t TableSize, 03518 ConstantInt *Offset, 03519 const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values, 03520 Constant *DefaultValue, 03521 const DataLayout *TD) 03522 : SingleValue(0), BitMap(0), BitMapElementTy(0), Array(0) { 03523 assert(Values.size() && "Can't build lookup table without values!"); 03524 assert(TableSize >= Values.size() && "Can't fit values in table!"); 03525 03526 // If all values in the table are equal, this is that value. 03527 SingleValue = Values.begin()->second; 03528 03529 // Build up the table contents. 03530 SmallVector<Constant*, 64> TableContents(TableSize); 03531 for (size_t I = 0, E = Values.size(); I != E; ++I) { 03532 ConstantInt *CaseVal = Values[I].first; 03533 Constant *CaseRes = Values[I].second; 03534 assert(CaseRes->getType() == DefaultValue->getType()); 03535 03536 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()) 03537 .getLimitedValue(); 03538 TableContents[Idx] = CaseRes; 03539 03540 if (CaseRes != SingleValue) 03541 SingleValue = 0; 03542 } 03543 03544 // Fill in any holes in the table with the default result. 03545 if (Values.size() < TableSize) { 03546 for (uint64_t I = 0; I < TableSize; ++I) { 03547 if (!TableContents[I]) 03548 TableContents[I] = DefaultValue; 03549 } 03550 03551 if (DefaultValue != SingleValue) 03552 SingleValue = 0; 03553 } 03554 03555 // If each element in the table contains the same value, we only need to store 03556 // that single value. 03557 if (SingleValue) { 03558 Kind = SingleValueKind; 03559 return; 03560 } 03561 03562 // If the type is integer and the table fits in a register, build a bitmap. 03563 if (WouldFitInRegister(TD, TableSize, DefaultValue->getType())) { 03564 IntegerType *IT = cast<IntegerType>(DefaultValue->getType()); 03565 APInt TableInt(TableSize * IT->getBitWidth(), 0); 03566 for (uint64_t I = TableSize; I > 0; --I) { 03567 TableInt <<= IT->getBitWidth(); 03568 // Insert values into the bitmap. Undef values are set to zero. 03569 if (!isa<UndefValue>(TableContents[I - 1])) { 03570 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 03571 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 03572 } 03573 } 03574 BitMap = ConstantInt::get(M.getContext(), TableInt); 03575 BitMapElementTy = IT; 03576 Kind = BitMapKind; 03577 ++NumBitMaps; 03578 return; 03579 } 03580 03581 // Store the table in an array. 03582 ArrayType *ArrayTy = ArrayType::get(DefaultValue->getType(), TableSize); 03583 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 03584 03585 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true, 03586 GlobalVariable::PrivateLinkage, 03587 Initializer, 03588 "switch.table"); 03589 Array->setUnnamedAddr(true); 03590 Kind = ArrayKind; 03591 } 03592 03593 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 03594 switch (Kind) { 03595 case SingleValueKind: 03596 return SingleValue; 03597 case BitMapKind: { 03598 // Type of the bitmap (e.g. i59). 03599 IntegerType *MapTy = BitMap->getType(); 03600 03601 // Cast Index to the same type as the bitmap. 03602 // Note: The Index is <= the number of elements in the table, so 03603 // truncating it to the width of the bitmask is safe. 03604 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 03605 03606 // Multiply the shift amount by the element width. 03607 ShiftAmt = Builder.CreateMul(ShiftAmt, 03608 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 03609 "switch.shiftamt"); 03610 03611 // Shift down. 03612 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt, 03613 "switch.downshift"); 03614 // Mask off. 03615 return Builder.CreateTrunc(DownShifted, BitMapElementTy, 03616 "switch.masked"); 03617 } 03618 case ArrayKind: { 03619 Value *GEPIndices[] = { Builder.getInt32(0), Index }; 03620 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices, 03621 "switch.gep"); 03622 return Builder.CreateLoad(GEP, "switch.load"); 03623 } 03624 } 03625 llvm_unreachable("Unknown lookup table kind!"); 03626 } 03627 03628 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *TD, 03629 uint64_t TableSize, 03630 const Type *ElementType) { 03631 if (!TD) 03632 return false; 03633 const IntegerType *IT = dyn_cast<IntegerType>(ElementType); 03634 if (!IT) 03635 return false; 03636 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 03637 // are <= 15, we could try to narrow the type. 03638 03639 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 03640 if (TableSize >= UINT_MAX/IT->getBitWidth()) 03641 return false; 03642 return TD->fitsInLegalInteger(TableSize * IT->getBitWidth()); 03643 } 03644 03645 /// ShouldBuildLookupTable - Determine whether a lookup table should be built 03646 /// for this switch, based on the number of caes, size of the table and the 03647 /// types of the results. 03648 static bool ShouldBuildLookupTable(SwitchInst *SI, 03649 uint64_t TableSize, 03650 const TargetTransformInfo &TTI, 03651 const DataLayout *TD, 03652 const SmallDenseMap<PHINode*, Type*>& ResultTypes) { 03653 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 03654 return false; // TableSize overflowed, or mul below might overflow. 03655 03656 bool AllTablesFitInRegister = true; 03657 bool HasIllegalType = false; 03658 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(), 03659 E = ResultTypes.end(); I != E; ++I) { 03660 Type *Ty = I->second; 03661 03662 // Saturate this flag to true. 03663 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); 03664 03665 // Saturate this flag to false. 03666 AllTablesFitInRegister = AllTablesFitInRegister && 03667 SwitchLookupTable::WouldFitInRegister(TD, TableSize, Ty); 03668 03669 // If both flags saturate, we're done. NOTE: This *only* works with 03670 // saturating flags, and all flags have to saturate first due to the 03671 // non-deterministic behavior of iterating over a dense map. 03672 if (HasIllegalType && !AllTablesFitInRegister) 03673 break; 03674 } 03675 03676 // If each table would fit in a register, we should build it anyway. 03677 if (AllTablesFitInRegister) 03678 return true; 03679 03680 // Don't build a table that doesn't fit in-register if it has illegal types. 03681 if (HasIllegalType) 03682 return false; 03683 03684 // The table density should be at least 40%. This is the same criterion as for 03685 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 03686 // FIXME: Find the best cut-off. 03687 return SI->getNumCases() * 10 >= TableSize * 4; 03688 } 03689 03690 /// SwitchToLookupTable - If the switch is only used to initialize one or more 03691 /// phi nodes in a common successor block with different constant values, 03692 /// replace the switch with lookup tables. 03693 static bool SwitchToLookupTable(SwitchInst *SI, 03694 IRBuilder<> &Builder, 03695 const TargetTransformInfo &TTI, 03696 const DataLayout* TD) { 03697 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 03698 03699 // Only build lookup table when we have a target that supports it. 03700 if (!TTI.shouldBuildLookupTables()) 03701 return false; 03702 03703 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 03704 // split off a dense part and build a lookup table for that. 03705 03706 // FIXME: This creates arrays of GEPs to constant strings, which means each 03707 // GEP needs a runtime relocation in PIC code. We should just build one big 03708 // string and lookup indices into that. 03709 03710 // Ignore the switch if the number of cases is too small. 03711 // This is similar to the check when building jump tables in 03712 // SelectionDAGBuilder::handleJTSwitchCase. 03713 // FIXME: Determine the best cut-off. 03714 if (SI->getNumCases() < 4) 03715 return false; 03716 03717 // Figure out the corresponding result for each case value and phi node in the 03718 // common destination, as well as the the min and max case values. 03719 assert(SI->case_begin() != SI->case_end()); 03720 SwitchInst::CaseIt CI = SI->case_begin(); 03721 ConstantInt *MinCaseVal = CI.getCaseValue(); 03722 ConstantInt *MaxCaseVal = CI.getCaseValue(); 03723 03724 BasicBlock *CommonDest = 0; 03725 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy; 03726 SmallDenseMap<PHINode*, ResultListTy> ResultLists; 03727 SmallDenseMap<PHINode*, Constant*> DefaultResults; 03728 SmallDenseMap<PHINode*, Type*> ResultTypes; 03729 SmallVector<PHINode*, 4> PHIs; 03730 03731 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 03732 ConstantInt *CaseVal = CI.getCaseValue(); 03733 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 03734 MinCaseVal = CaseVal; 03735 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 03736 MaxCaseVal = CaseVal; 03737 03738 // Resulting value at phi nodes for this case value. 03739 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy; 03740 ResultsTy Results; 03741 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest, 03742 Results)) 03743 return false; 03744 03745 // Append the result from this case to the list for each phi. 03746 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) { 03747 if (!ResultLists.count(I->first)) 03748 PHIs.push_back(I->first); 03749 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second)); 03750 } 03751 } 03752 03753 // Get the resulting values for the default case. 03754 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList; 03755 if (!GetCaseResults(SI, 0, SI->getDefaultDest(), &CommonDest, 03756 DefaultResultsList)) 03757 return false; 03758 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) { 03759 PHINode *PHI = DefaultResultsList[I].first; 03760 Constant *Result = DefaultResultsList[I].second; 03761 DefaultResults[PHI] = Result; 03762 ResultTypes[PHI] = Result->getType(); 03763 } 03764 03765 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 03766 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 03767 if (!ShouldBuildLookupTable(SI, TableSize, TTI, TD, ResultTypes)) 03768 return false; 03769 03770 // Create the BB that does the lookups. 03771 Module &Mod = *CommonDest->getParent()->getParent(); 03772 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(), 03773 "switch.lookup", 03774 CommonDest->getParent(), 03775 CommonDest); 03776 03777 // Check whether the condition value is within the case range, and branch to 03778 // the new BB. 03779 Builder.SetInsertPoint(SI); 03780 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 03781 "switch.tableidx"); 03782 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get( 03783 MinCaseVal->getType(), TableSize)); 03784 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 03785 03786 // Populate the BB that does the lookups. 03787 Builder.SetInsertPoint(LookupBB); 03788 bool ReturnedEarly = false; 03789 for (size_t I = 0, E = PHIs.size(); I != E; ++I) { 03790 PHINode *PHI = PHIs[I]; 03791 03792 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI], 03793 DefaultResults[PHI], TD); 03794 03795 Value *Result = Table.BuildLookup(TableIndex, Builder); 03796 03797 // If the result is used to return immediately from the function, we want to 03798 // do that right here. 03799 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->use_begin()) && 03800 *PHI->use_begin() == CommonDest->getFirstNonPHIOrDbg()) { 03801 Builder.CreateRet(Result); 03802 ReturnedEarly = true; 03803 break; 03804 } 03805 03806 PHI->addIncoming(Result, LookupBB); 03807 } 03808 03809 if (!ReturnedEarly) 03810 Builder.CreateBr(CommonDest); 03811 03812 // Remove the switch. 03813 for (unsigned i = 0; i < SI->getNumSuccessors(); ++i) { 03814 BasicBlock *Succ = SI->getSuccessor(i); 03815 if (Succ == SI->getDefaultDest()) continue; 03816 Succ->removePredecessor(SI->getParent()); 03817 } 03818 SI->eraseFromParent(); 03819 03820 ++NumLookupTables; 03821 return true; 03822 } 03823 03824 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 03825 BasicBlock *BB = SI->getParent(); 03826 03827 if (isValueEqualityComparison(SI)) { 03828 // If we only have one predecessor, and if it is a branch on this value, 03829 // see if that predecessor totally determines the outcome of this switch. 03830 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 03831 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 03832 return SimplifyCFG(BB, TTI, TD) | true; 03833 03834 Value *Cond = SI->getCondition(); 03835 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 03836 if (SimplifySwitchOnSelect(SI, Select)) 03837 return SimplifyCFG(BB, TTI, TD) | true; 03838 03839 // If the block only contains the switch, see if we can fold the block 03840 // away into any preds. 03841 BasicBlock::iterator BBI = BB->begin(); 03842 // Ignore dbg intrinsics. 03843 while (isa<DbgInfoIntrinsic>(BBI)) 03844 ++BBI; 03845 if (SI == &*BBI) 03846 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 03847 return SimplifyCFG(BB, TTI, TD) | true; 03848 } 03849 03850 // Try to transform the switch into an icmp and a branch. 03851 if (TurnSwitchRangeIntoICmp(SI, Builder)) 03852 return SimplifyCFG(BB, TTI, TD) | true; 03853 03854 // Remove unreachable cases. 03855 if (EliminateDeadSwitchCases(SI)) 03856 return SimplifyCFG(BB, TTI, TD) | true; 03857 03858 if (ForwardSwitchConditionToPHI(SI)) 03859 return SimplifyCFG(BB, TTI, TD) | true; 03860 03861 if (SwitchToLookupTable(SI, Builder, TTI, TD)) 03862 return SimplifyCFG(BB, TTI, TD) | true; 03863 03864 return false; 03865 } 03866 03867 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { 03868 BasicBlock *BB = IBI->getParent(); 03869 bool Changed = false; 03870 03871 // Eliminate redundant destinations. 03872 SmallPtrSet<Value *, 8> Succs; 03873 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 03874 BasicBlock *Dest = IBI->getDestination(i); 03875 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) { 03876 Dest->removePredecessor(BB); 03877 IBI->removeDestination(i); 03878 --i; --e; 03879 Changed = true; 03880 } 03881 } 03882 03883 if (IBI->getNumDestinations() == 0) { 03884 // If the indirectbr has no successors, change it to unreachable. 03885 new UnreachableInst(IBI->getContext(), IBI); 03886 EraseTerminatorInstAndDCECond(IBI); 03887 return true; 03888 } 03889 03890 if (IBI->getNumDestinations() == 1) { 03891 // If the indirectbr has one successor, change it to a direct branch. 03892 BranchInst::Create(IBI->getDestination(0), IBI); 03893 EraseTerminatorInstAndDCECond(IBI); 03894 return true; 03895 } 03896 03897 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 03898 if (SimplifyIndirectBrOnSelect(IBI, SI)) 03899 return SimplifyCFG(BB, TTI, TD) | true; 03900 } 03901 return Changed; 03902 } 03903 03904 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){ 03905 BasicBlock *BB = BI->getParent(); 03906 03907 if (SinkCommon && SinkThenElseCodeToEnd(BI)) 03908 return true; 03909 03910 // If the Terminator is the only non-phi instruction, simplify the block. 03911 BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime(); 03912 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 03913 TryToSimplifyUncondBranchFromEmptyBlock(BB)) 03914 return true; 03915 03916 // If the only instruction in the block is a seteq/setne comparison 03917 // against a constant, try to simplify the block. 03918 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 03919 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 03920 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 03921 ; 03922 if (I->isTerminator() && 03923 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, TD)) 03924 return true; 03925 } 03926 03927 // If this basic block is ONLY a compare and a branch, and if a predecessor 03928 // branches to us and our successor, fold the comparison into the 03929 // predecessor and use logical operations to update the incoming value 03930 // for PHI nodes in common successor. 03931 if (FoldBranchToCommonDest(BI)) 03932 return SimplifyCFG(BB, TTI, TD) | true; 03933 return false; 03934 } 03935 03936 03937 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 03938 BasicBlock *BB = BI->getParent(); 03939 03940 // Conditional branch 03941 if (isValueEqualityComparison(BI)) { 03942 // If we only have one predecessor, and if it is a branch on this value, 03943 // see if that predecessor totally determines the outcome of this 03944 // switch. 03945 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 03946 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 03947 return SimplifyCFG(BB, TTI, TD) | true; 03948 03949 // This block must be empty, except for the setcond inst, if it exists. 03950 // Ignore dbg intrinsics. 03951 BasicBlock::iterator I = BB->begin(); 03952 // Ignore dbg intrinsics. 03953 while (isa<DbgInfoIntrinsic>(I)) 03954 ++I; 03955 if (&*I == BI) { 03956 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 03957 return SimplifyCFG(BB, TTI, TD) | true; 03958 } else if (&*I == cast<Instruction>(BI->getCondition())){ 03959 ++I; 03960 // Ignore dbg intrinsics. 03961 while (isa<DbgInfoIntrinsic>(I)) 03962 ++I; 03963 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 03964 return SimplifyCFG(BB, TTI, TD) | true; 03965 } 03966 } 03967 03968 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 03969 if (SimplifyBranchOnICmpChain(BI, TD, Builder)) 03970 return true; 03971 03972 // If this basic block is ONLY a compare and a branch, and if a predecessor 03973 // branches to us and one of our successors, fold the comparison into the 03974 // predecessor and use logical operations to pick the right destination. 03975 if (FoldBranchToCommonDest(BI)) 03976 return SimplifyCFG(BB, TTI, TD) | true; 03977 03978 // We have a conditional branch to two blocks that are only reachable 03979 // from BI. We know that the condbr dominates the two blocks, so see if 03980 // there is any identical code in the "then" and "else" blocks. If so, we 03981 // can hoist it up to the branching block. 03982 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) { 03983 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) { 03984 if (HoistThenElseCodeToIf(BI)) 03985 return SimplifyCFG(BB, TTI, TD) | true; 03986 } else { 03987 // If Successor #1 has multiple preds, we may be able to conditionally 03988 // execute Successor #0 if it branches to successor #1. 03989 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator(); 03990 if (Succ0TI->getNumSuccessors() == 1 && 03991 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 03992 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0))) 03993 return SimplifyCFG(BB, TTI, TD) | true; 03994 } 03995 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) { 03996 // If Successor #0 has multiple preds, we may be able to conditionally 03997 // execute Successor #1 if it branches to successor #0. 03998 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator(); 03999 if (Succ1TI->getNumSuccessors() == 1 && 04000 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 04001 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1))) 04002 return SimplifyCFG(BB, TTI, TD) | true; 04003 } 04004 04005 // If this is a branch on a phi node in the current block, thread control 04006 // through this block if any PHI node entries are constants. 04007 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 04008 if (PN->getParent() == BI->getParent()) 04009 if (FoldCondBranchOnPHI(BI, TD)) 04010 return SimplifyCFG(BB, TTI, TD) | true; 04011 04012 // Scan predecessor blocks for conditional branches. 04013 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 04014 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 04015 if (PBI != BI && PBI->isConditional()) 04016 if (SimplifyCondBranchToCondBranch(PBI, BI)) 04017 return SimplifyCFG(BB, TTI, TD) | true; 04018 04019 return false; 04020 } 04021 04022 /// Check if passing a value to an instruction will cause undefined behavior. 04023 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { 04024 Constant *C = dyn_cast<Constant>(V); 04025 if (!C) 04026 return false; 04027 04028 if (I->use_empty()) 04029 return false; 04030 04031 if (C->isNullValue()) { 04032 // Only look at the first use, avoid hurting compile time with long uselists 04033 User *Use = *I->use_begin(); 04034 04035 // Now make sure that there are no instructions in between that can alter 04036 // control flow (eg. calls) 04037 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i) 04038 if (i == I->getParent()->end() || i->mayHaveSideEffects()) 04039 return false; 04040 04041 // Look through GEPs. A load from a GEP derived from NULL is still undefined 04042 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 04043 if (GEP->getPointerOperand() == I) 04044 return passingValueIsAlwaysUndefined(V, GEP); 04045 04046 // Look through bitcasts. 04047 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 04048 return passingValueIsAlwaysUndefined(V, BC); 04049 04050 // Load from null is undefined. 04051 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 04052 if (!LI->isVolatile()) 04053 return LI->getPointerAddressSpace() == 0; 04054 04055 // Store to null is undefined. 04056 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 04057 if (!SI->isVolatile()) 04058 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I; 04059 } 04060 return false; 04061 } 04062 04063 /// If BB has an incoming value that will always trigger undefined behavior 04064 /// (eg. null pointer dereference), remove the branch leading here. 04065 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { 04066 for (BasicBlock::iterator i = BB->begin(); 04067 PHINode *PHI = dyn_cast<PHINode>(i); ++i) 04068 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) 04069 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) { 04070 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator(); 04071 IRBuilder<> Builder(T); 04072 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 04073 BB->removePredecessor(PHI->getIncomingBlock(i)); 04074 // Turn uncoditional branches into unreachables and remove the dead 04075 // destination from conditional branches. 04076 if (BI->isUnconditional()) 04077 Builder.CreateUnreachable(); 04078 else 04079 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) : 04080 BI->getSuccessor(0)); 04081 BI->eraseFromParent(); 04082 return true; 04083 } 04084 // TODO: SwitchInst. 04085 } 04086 04087 return false; 04088 } 04089 04090 bool SimplifyCFGOpt::run(BasicBlock *BB) { 04091 bool Changed = false; 04092 04093 assert(BB && BB->getParent() && "Block not embedded in function!"); 04094 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 04095 04096 // Remove basic blocks that have no predecessors (except the entry block)... 04097 // or that just have themself as a predecessor. These are unreachable. 04098 if ((pred_begin(BB) == pred_end(BB) && 04099 BB != &BB->getParent()->getEntryBlock()) || 04100 BB->getSinglePredecessor() == BB) { 04101 DEBUG(dbgs() << "Removing BB: \n" << *BB); 04102 DeleteDeadBlock(BB); 04103 return true; 04104 } 04105 04106 // Check to see if we can constant propagate this terminator instruction 04107 // away... 04108 Changed |= ConstantFoldTerminator(BB, true); 04109 04110 // Check for and eliminate duplicate PHI nodes in this block. 04111 Changed |= EliminateDuplicatePHINodes(BB); 04112 04113 // Check for and remove branches that will always cause undefined behavior. 04114 Changed |= removeUndefIntroducingPredecessor(BB); 04115 04116 // Merge basic blocks into their predecessor if there is only one distinct 04117 // pred, and if there is only one distinct successor of the predecessor, and 04118 // if there are no PHI nodes. 04119 // 04120 if (MergeBlockIntoPredecessor(BB)) 04121 return true; 04122 04123 IRBuilder<> Builder(BB); 04124 04125 // If there is a trivial two-entry PHI node in this basic block, and we can 04126 // eliminate it, do so now. 04127 if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) 04128 if (PN->getNumIncomingValues() == 2) 04129 Changed |= FoldTwoEntryPHINode(PN, TD); 04130 04131 Builder.SetInsertPoint(BB->getTerminator()); 04132 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 04133 if (BI->isUnconditional()) { 04134 if (SimplifyUncondBranch(BI, Builder)) return true; 04135 } else { 04136 if (SimplifyCondBranch(BI, Builder)) return true; 04137 } 04138 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 04139 if (SimplifyReturn(RI, Builder)) return true; 04140 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { 04141 if (SimplifyResume(RI, Builder)) return true; 04142 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 04143 if (SimplifySwitch(SI, Builder)) return true; 04144 } else if (UnreachableInst *UI = 04145 dyn_cast<UnreachableInst>(BB->getTerminator())) { 04146 if (SimplifyUnreachable(UI)) return true; 04147 } else if (IndirectBrInst *IBI = 04148 dyn_cast<IndirectBrInst>(BB->getTerminator())) { 04149 if (SimplifyIndirectBr(IBI)) return true; 04150 } 04151 04152 return Changed; 04153 } 04154 04155 /// SimplifyCFG - This function is used to do simplification of a CFG. For 04156 /// example, it adjusts branches to branches to eliminate the extra hop, it 04157 /// eliminates unreachable basic blocks, and does other "peephole" optimization 04158 /// of the CFG. It returns true if a modification was made. 04159 /// 04160 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 04161 const DataLayout *TD) { 04162 return SimplifyCFGOpt(TTI, TD).run(BB); 04163 }