1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Correlated Value Propagation pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/Analysis/LazyValueInfo.h" 18 #include "llvm/IR/CFG.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/Function.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/Pass.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Transforms/Utils/Local.h" 27 using namespace llvm; 28 29 #define DEBUG_TYPE "correlated-value-propagation" 30 31 STATISTIC(NumPhis, "Number of phis propagated"); 32 STATISTIC(NumSelects, "Number of selects propagated"); 33 STATISTIC(NumMemAccess, "Number of memory access targets propagated"); 34 STATISTIC(NumCmps, "Number of comparisons propagated"); 35 STATISTIC(NumDeadCases, "Number of switch cases removed"); 36 37 namespace { 38 class CorrelatedValuePropagation : public FunctionPass { 39 LazyValueInfo *LVI; 40 41 bool processSelect(SelectInst *SI); 42 bool processPHI(PHINode *P); 43 bool processMemAccess(Instruction *I); 44 bool processCmp(CmpInst *C); 45 bool processSwitch(SwitchInst *SI); 46 47 public: 48 static char ID; 49 CorrelatedValuePropagation(): FunctionPass(ID) { 50 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry()); 51 } 52 53 bool runOnFunction(Function &F) override; 54 55 void getAnalysisUsage(AnalysisUsage &AU) const override { 56 AU.addRequired<LazyValueInfo>(); 57 } 58 }; 59 } 60 61 char CorrelatedValuePropagation::ID = 0; 62 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation", 63 "Value Propagation", false, false) 64 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo) 65 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation", 66 "Value Propagation", false, false) 67 68 // Public interface to the Value Propagation pass 69 Pass *llvm::createCorrelatedValuePropagationPass() { 70 return new CorrelatedValuePropagation(); 71 } 72 73 bool CorrelatedValuePropagation::processSelect(SelectInst *S) { 74 if (S->getType()->isVectorTy()) return false; 75 if (isa<Constant>(S->getOperand(0))) return false; 76 77 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S); 78 if (!C) return false; 79 80 ConstantInt *CI = dyn_cast<ConstantInt>(C); 81 if (!CI) return false; 82 83 Value *ReplaceWith = S->getOperand(1); 84 Value *Other = S->getOperand(2); 85 if (!CI->isOne()) std::swap(ReplaceWith, Other); 86 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType()); 87 88 S->replaceAllUsesWith(ReplaceWith); 89 S->eraseFromParent(); 90 91 ++NumSelects; 92 93 return true; 94 } 95 96 bool CorrelatedValuePropagation::processPHI(PHINode *P) { 97 bool Changed = false; 98 99 BasicBlock *BB = P->getParent(); 100 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) { 101 Value *Incoming = P->getIncomingValue(i); 102 if (isa<Constant>(Incoming)) continue; 103 104 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P); 105 106 // Look if the incoming value is a select with a constant but LVI tells us 107 // that the incoming value can never be that constant. In that case replace 108 // the incoming value with the other value of the select. This often allows 109 // us to remove the select later. 110 if (!V) { 111 SelectInst *SI = dyn_cast<SelectInst>(Incoming); 112 if (!SI) continue; 113 114 Constant *C = dyn_cast<Constant>(SI->getFalseValue()); 115 if (!C) continue; 116 117 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, 118 P->getIncomingBlock(i), BB, P) != 119 LazyValueInfo::False) 120 continue; 121 122 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n'); 123 V = SI->getTrueValue(); 124 } 125 126 P->setIncomingValue(i, V); 127 Changed = true; 128 } 129 130 // FIXME: Provide TLI, DT, AT to SimplifyInstruction. 131 const DataLayout &DL = BB->getModule()->getDataLayout(); 132 if (Value *V = SimplifyInstruction(P, DL)) { 133 P->replaceAllUsesWith(V); 134 P->eraseFromParent(); 135 Changed = true; 136 } 137 138 if (Changed) 139 ++NumPhis; 140 141 return Changed; 142 } 143 144 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) { 145 Value *Pointer = nullptr; 146 if (LoadInst *L = dyn_cast<LoadInst>(I)) 147 Pointer = L->getPointerOperand(); 148 else 149 Pointer = cast<StoreInst>(I)->getPointerOperand(); 150 151 if (isa<Constant>(Pointer)) return false; 152 153 Constant *C = LVI->getConstant(Pointer, I->getParent(), I); 154 if (!C) return false; 155 156 ++NumMemAccess; 157 I->replaceUsesOfWith(Pointer, C); 158 return true; 159 } 160 161 /// processCmp - If the value of this comparison could be determined locally, 162 /// constant propagation would already have figured it out. Instead, walk 163 /// the predecessors and statically evaluate the comparison based on information 164 /// available on that edge. If a given static evaluation is true on ALL 165 /// incoming edges, then it's true universally and we can simplify the compare. 166 bool CorrelatedValuePropagation::processCmp(CmpInst *C) { 167 Value *Op0 = C->getOperand(0); 168 if (isa<Instruction>(Op0) && 169 cast<Instruction>(Op0)->getParent() == C->getParent()) 170 return false; 171 172 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); 173 if (!Op1) return false; 174 175 pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent()); 176 if (PI == PE) return false; 177 178 LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(), 179 C->getOperand(0), Op1, *PI, 180 C->getParent(), C); 181 if (Result == LazyValueInfo::Unknown) return false; 182 183 ++PI; 184 while (PI != PE) { 185 LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(), 186 C->getOperand(0), Op1, *PI, 187 C->getParent(), C); 188 if (Res != Result) return false; 189 ++PI; 190 } 191 192 ++NumCmps; 193 194 if (Result == LazyValueInfo::True) 195 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext())); 196 else 197 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext())); 198 199 C->eraseFromParent(); 200 201 return true; 202 } 203 204 /// processSwitch - Simplify a switch instruction by removing cases which can 205 /// never fire. If the uselessness of a case could be determined locally then 206 /// constant propagation would already have figured it out. Instead, walk the 207 /// predecessors and statically evaluate cases based on information available 208 /// on that edge. Cases that cannot fire no matter what the incoming edge can 209 /// safely be removed. If a case fires on every incoming edge then the entire 210 /// switch can be removed and replaced with a branch to the case destination. 211 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) { 212 Value *Cond = SI->getCondition(); 213 BasicBlock *BB = SI->getParent(); 214 215 // If the condition was defined in same block as the switch then LazyValueInfo 216 // currently won't say anything useful about it, though in theory it could. 217 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB) 218 return false; 219 220 // If the switch is unreachable then trying to improve it is a waste of time. 221 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 222 if (PB == PE) return false; 223 224 // Analyse each switch case in turn. This is done in reverse order so that 225 // removing a case doesn't cause trouble for the iteration. 226 bool Changed = false; 227 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE; 228 ) { 229 ConstantInt *Case = CI.getCaseValue(); 230 231 // Check to see if the switch condition is equal to/not equal to the case 232 // value on every incoming edge, equal/not equal being the same each time. 233 LazyValueInfo::Tristate State = LazyValueInfo::Unknown; 234 for (pred_iterator PI = PB; PI != PE; ++PI) { 235 // Is the switch condition equal to the case value? 236 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ, 237 Cond, Case, *PI, 238 BB, SI); 239 // Give up on this case if nothing is known. 240 if (Value == LazyValueInfo::Unknown) { 241 State = LazyValueInfo::Unknown; 242 break; 243 } 244 245 // If this was the first edge to be visited, record that all other edges 246 // need to give the same result. 247 if (PI == PB) { 248 State = Value; 249 continue; 250 } 251 252 // If this case is known to fire for some edges and known not to fire for 253 // others then there is nothing we can do - give up. 254 if (Value != State) { 255 State = LazyValueInfo::Unknown; 256 break; 257 } 258 } 259 260 if (State == LazyValueInfo::False) { 261 // This case never fires - remove it. 262 CI.getCaseSuccessor()->removePredecessor(BB); 263 SI->removeCase(CI); // Does not invalidate the iterator. 264 265 // The condition can be modified by removePredecessor's PHI simplification 266 // logic. 267 Cond = SI->getCondition(); 268 269 ++NumDeadCases; 270 Changed = true; 271 } else if (State == LazyValueInfo::True) { 272 // This case always fires. Arrange for the switch to be turned into an 273 // unconditional branch by replacing the switch condition with the case 274 // value. 275 SI->setCondition(Case); 276 NumDeadCases += SI->getNumCases(); 277 Changed = true; 278 break; 279 } 280 } 281 282 if (Changed) 283 // If the switch has been simplified to the point where it can be replaced 284 // by a branch then do so now. 285 ConstantFoldTerminator(BB); 286 287 return Changed; 288 } 289 290 bool CorrelatedValuePropagation::runOnFunction(Function &F) { 291 if (skipOptnoneFunction(F)) 292 return false; 293 294 LVI = &getAnalysis<LazyValueInfo>(); 295 296 bool FnChanged = false; 297 298 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { 299 bool BBChanged = false; 300 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) { 301 Instruction *II = BI++; 302 switch (II->getOpcode()) { 303 case Instruction::Select: 304 BBChanged |= processSelect(cast<SelectInst>(II)); 305 break; 306 case Instruction::PHI: 307 BBChanged |= processPHI(cast<PHINode>(II)); 308 break; 309 case Instruction::ICmp: 310 case Instruction::FCmp: 311 BBChanged |= processCmp(cast<CmpInst>(II)); 312 break; 313 case Instruction::Load: 314 case Instruction::Store: 315 BBChanged |= processMemAccess(II); 316 break; 317 } 318 } 319 320 Instruction *Term = FI->getTerminator(); 321 switch (Term->getOpcode()) { 322 case Instruction::Switch: 323 BBChanged |= processSwitch(cast<SwitchInst>(Term)); 324 break; 325 } 326 327 FnChanged |= BBChanged; 328 } 329 330 return FnChanged; 331 } 332