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/GlobalsModRef.h" 17 #include "llvm/Analysis/InstructionSimplify.h" 18 #include "llvm/Analysis/LazyValueInfo.h" 19 #include "llvm/IR/CFG.h" 20 #include "llvm/IR/Constants.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/Pass.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include "llvm/Transforms/Utils/Local.h" 28 using namespace llvm; 29 30 #define DEBUG_TYPE "correlated-value-propagation" 31 32 STATISTIC(NumPhis, "Number of phis propagated"); 33 STATISTIC(NumSelects, "Number of selects propagated"); 34 STATISTIC(NumMemAccess, "Number of memory access targets propagated"); 35 STATISTIC(NumCmps, "Number of comparisons propagated"); 36 STATISTIC(NumReturns, "Number of return values propagated"); 37 STATISTIC(NumDeadCases, "Number of switch cases removed"); 38 STATISTIC(NumSDivs, "Number of sdiv converted to udiv"); 39 40 namespace { 41 class CorrelatedValuePropagation : public FunctionPass { 42 LazyValueInfo *LVI; 43 44 bool processSelect(SelectInst *SI); 45 bool processPHI(PHINode *P); 46 bool processMemAccess(Instruction *I); 47 bool processCmp(CmpInst *C); 48 bool processSwitch(SwitchInst *SI); 49 bool processCallSite(CallSite CS); 50 bool processSDiv(BinaryOperator *SDI); 51 52 /// Return a constant value for V usable at At and everything it 53 /// dominates. If no such Constant can be found, return nullptr. 54 Constant *getConstantAt(Value *V, Instruction *At); 55 56 public: 57 static char ID; 58 CorrelatedValuePropagation(): FunctionPass(ID) { 59 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry()); 60 } 61 62 bool runOnFunction(Function &F) override; 63 64 void getAnalysisUsage(AnalysisUsage &AU) const override { 65 AU.addRequired<LazyValueInfo>(); 66 AU.addPreserved<GlobalsAAWrapperPass>(); 67 } 68 }; 69 } 70 71 char CorrelatedValuePropagation::ID = 0; 72 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation", 73 "Value Propagation", false, false) 74 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo) 75 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation", 76 "Value Propagation", false, false) 77 78 // Public interface to the Value Propagation pass 79 Pass *llvm::createCorrelatedValuePropagationPass() { 80 return new CorrelatedValuePropagation(); 81 } 82 83 bool CorrelatedValuePropagation::processSelect(SelectInst *S) { 84 if (S->getType()->isVectorTy()) return false; 85 if (isa<Constant>(S->getOperand(0))) return false; 86 87 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S); 88 if (!C) return false; 89 90 ConstantInt *CI = dyn_cast<ConstantInt>(C); 91 if (!CI) return false; 92 93 Value *ReplaceWith = S->getOperand(1); 94 Value *Other = S->getOperand(2); 95 if (!CI->isOne()) std::swap(ReplaceWith, Other); 96 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType()); 97 98 S->replaceAllUsesWith(ReplaceWith); 99 S->eraseFromParent(); 100 101 ++NumSelects; 102 103 return true; 104 } 105 106 bool CorrelatedValuePropagation::processPHI(PHINode *P) { 107 bool Changed = false; 108 109 BasicBlock *BB = P->getParent(); 110 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) { 111 Value *Incoming = P->getIncomingValue(i); 112 if (isa<Constant>(Incoming)) continue; 113 114 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P); 115 116 // Look if the incoming value is a select with a scalar condition for which 117 // LVI can tells us the value. In that case replace the incoming value with 118 // the appropriate value of the select. This often allows us to remove the 119 // select later. 120 if (!V) { 121 SelectInst *SI = dyn_cast<SelectInst>(Incoming); 122 if (!SI) continue; 123 124 Value *Condition = SI->getCondition(); 125 if (!Condition->getType()->isVectorTy()) { 126 if (Constant *C = LVI->getConstantOnEdge( 127 Condition, P->getIncomingBlock(i), BB, P)) { 128 if (C->isOneValue()) { 129 V = SI->getTrueValue(); 130 } else if (C->isZeroValue()) { 131 V = SI->getFalseValue(); 132 } 133 // Once LVI learns to handle vector types, we could also add support 134 // for vector type constants that are not all zeroes or all ones. 135 } 136 } 137 138 // Look if the select has a constant but LVI tells us that the incoming 139 // value can never be that constant. In that case replace the incoming 140 // value with the other value of the select. This often allows us to 141 // remove the select later. 142 if (!V) { 143 Constant *C = dyn_cast<Constant>(SI->getFalseValue()); 144 if (!C) continue; 145 146 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, 147 P->getIncomingBlock(i), BB, P) != 148 LazyValueInfo::False) 149 continue; 150 V = SI->getTrueValue(); 151 } 152 153 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n'); 154 } 155 156 P->setIncomingValue(i, V); 157 Changed = true; 158 } 159 160 // FIXME: Provide TLI, DT, AT to SimplifyInstruction. 161 const DataLayout &DL = BB->getModule()->getDataLayout(); 162 if (Value *V = SimplifyInstruction(P, DL)) { 163 P->replaceAllUsesWith(V); 164 P->eraseFromParent(); 165 Changed = true; 166 } 167 168 if (Changed) 169 ++NumPhis; 170 171 return Changed; 172 } 173 174 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) { 175 Value *Pointer = nullptr; 176 if (LoadInst *L = dyn_cast<LoadInst>(I)) 177 Pointer = L->getPointerOperand(); 178 else 179 Pointer = cast<StoreInst>(I)->getPointerOperand(); 180 181 if (isa<Constant>(Pointer)) return false; 182 183 Constant *C = LVI->getConstant(Pointer, I->getParent(), I); 184 if (!C) return false; 185 186 ++NumMemAccess; 187 I->replaceUsesOfWith(Pointer, C); 188 return true; 189 } 190 191 /// processCmp - See if LazyValueInfo's ability to exploit edge conditions, 192 /// or range information is sufficient to prove this comparison. Even for 193 /// local conditions, this can sometimes prove conditions instcombine can't by 194 /// exploiting range information. 195 bool CorrelatedValuePropagation::processCmp(CmpInst *C) { 196 Value *Op0 = C->getOperand(0); 197 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); 198 if (!Op1) return false; 199 200 // As a policy choice, we choose not to waste compile time on anything where 201 // the comparison is testing local values. While LVI can sometimes reason 202 // about such cases, it's not its primary purpose. We do make sure to do 203 // the block local query for uses from terminator instructions, but that's 204 // handled in the code for each terminator. 205 auto *I = dyn_cast<Instruction>(Op0); 206 if (I && I->getParent() == C->getParent()) 207 return false; 208 209 LazyValueInfo::Tristate Result = 210 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C); 211 if (Result == LazyValueInfo::Unknown) return false; 212 213 ++NumCmps; 214 if (Result == LazyValueInfo::True) 215 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext())); 216 else 217 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext())); 218 C->eraseFromParent(); 219 220 return true; 221 } 222 223 /// processSwitch - Simplify a switch instruction by removing cases which can 224 /// never fire. If the uselessness of a case could be determined locally then 225 /// constant propagation would already have figured it out. Instead, walk the 226 /// predecessors and statically evaluate cases based on information available 227 /// on that edge. Cases that cannot fire no matter what the incoming edge can 228 /// safely be removed. If a case fires on every incoming edge then the entire 229 /// switch can be removed and replaced with a branch to the case destination. 230 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) { 231 Value *Cond = SI->getCondition(); 232 BasicBlock *BB = SI->getParent(); 233 234 // If the condition was defined in same block as the switch then LazyValueInfo 235 // currently won't say anything useful about it, though in theory it could. 236 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB) 237 return false; 238 239 // If the switch is unreachable then trying to improve it is a waste of time. 240 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 241 if (PB == PE) return false; 242 243 // Analyse each switch case in turn. This is done in reverse order so that 244 // removing a case doesn't cause trouble for the iteration. 245 bool Changed = false; 246 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE; 247 ) { 248 ConstantInt *Case = CI.getCaseValue(); 249 250 // Check to see if the switch condition is equal to/not equal to the case 251 // value on every incoming edge, equal/not equal being the same each time. 252 LazyValueInfo::Tristate State = LazyValueInfo::Unknown; 253 for (pred_iterator PI = PB; PI != PE; ++PI) { 254 // Is the switch condition equal to the case value? 255 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ, 256 Cond, Case, *PI, 257 BB, SI); 258 // Give up on this case if nothing is known. 259 if (Value == LazyValueInfo::Unknown) { 260 State = LazyValueInfo::Unknown; 261 break; 262 } 263 264 // If this was the first edge to be visited, record that all other edges 265 // need to give the same result. 266 if (PI == PB) { 267 State = Value; 268 continue; 269 } 270 271 // If this case is known to fire for some edges and known not to fire for 272 // others then there is nothing we can do - give up. 273 if (Value != State) { 274 State = LazyValueInfo::Unknown; 275 break; 276 } 277 } 278 279 if (State == LazyValueInfo::False) { 280 // This case never fires - remove it. 281 CI.getCaseSuccessor()->removePredecessor(BB); 282 SI->removeCase(CI); // Does not invalidate the iterator. 283 284 // The condition can be modified by removePredecessor's PHI simplification 285 // logic. 286 Cond = SI->getCondition(); 287 288 ++NumDeadCases; 289 Changed = true; 290 } else if (State == LazyValueInfo::True) { 291 // This case always fires. Arrange for the switch to be turned into an 292 // unconditional branch by replacing the switch condition with the case 293 // value. 294 SI->setCondition(Case); 295 NumDeadCases += SI->getNumCases(); 296 Changed = true; 297 break; 298 } 299 } 300 301 if (Changed) 302 // If the switch has been simplified to the point where it can be replaced 303 // by a branch then do so now. 304 ConstantFoldTerminator(BB); 305 306 return Changed; 307 } 308 309 /// processCallSite - Infer nonnull attributes for the arguments at the 310 /// specified callsite. 311 bool CorrelatedValuePropagation::processCallSite(CallSite CS) { 312 SmallVector<unsigned, 4> Indices; 313 unsigned ArgNo = 0; 314 315 for (Value *V : CS.args()) { 316 PointerType *Type = dyn_cast<PointerType>(V->getType()); 317 // Try to mark pointer typed parameters as non-null. We skip the 318 // relatively expensive analysis for constants which are obviously either 319 // null or non-null to start with. 320 if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) && 321 !isa<Constant>(V) && 322 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V, 323 ConstantPointerNull::get(Type), 324 CS.getInstruction()) == LazyValueInfo::False) 325 Indices.push_back(ArgNo + 1); 326 ArgNo++; 327 } 328 329 assert(ArgNo == CS.arg_size() && "sanity check"); 330 331 if (Indices.empty()) 332 return false; 333 334 AttributeSet AS = CS.getAttributes(); 335 LLVMContext &Ctx = CS.getInstruction()->getContext(); 336 AS = AS.addAttribute(Ctx, Indices, Attribute::get(Ctx, Attribute::NonNull)); 337 CS.setAttributes(AS); 338 339 return true; 340 } 341 342 /// See if LazyValueInfo's ability to exploit edge conditions, or range 343 /// information is sufficient to prove the both operands of this SDiv are 344 /// positive. If this is the case, replace the SDiv with a UDiv. Even for local 345 /// conditions, this can sometimes prove conditions instcombine can't by 346 /// exploiting range information. 347 bool CorrelatedValuePropagation::processSDiv(BinaryOperator *SDI) { 348 if (SDI->getType()->isVectorTy()) 349 return false; 350 351 for (Value *O : SDI->operands()) { 352 // As a policy choice, we choose not to waste compile time on anything where 353 // the operands are local defs. While LVI can sometimes reason about such 354 // cases, it's not its primary purpose. 355 auto *I = dyn_cast<Instruction>(O); 356 if (I && I->getParent() == SDI->getParent()) 357 return false; 358 } 359 360 Constant *Zero = ConstantInt::get(SDI->getType(), 0); 361 for (Value *O : SDI->operands()) { 362 LazyValueInfo::Tristate Result = 363 LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI); 364 if (Result != LazyValueInfo::True) 365 return false; 366 } 367 368 ++NumSDivs; 369 auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1), 370 SDI->getName(), SDI); 371 BO->setIsExact(SDI->isExact()); 372 SDI->replaceAllUsesWith(BO); 373 SDI->eraseFromParent(); 374 375 return true; 376 } 377 378 Constant *CorrelatedValuePropagation::getConstantAt(Value *V, Instruction *At) { 379 if (Constant *C = LVI->getConstant(V, At->getParent(), At)) 380 return C; 381 382 // TODO: The following really should be sunk inside LVI's core algorithm, or 383 // at least the outer shims around such. 384 auto *C = dyn_cast<CmpInst>(V); 385 if (!C) return nullptr; 386 387 Value *Op0 = C->getOperand(0); 388 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); 389 if (!Op1) return nullptr; 390 391 LazyValueInfo::Tristate Result = 392 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At); 393 if (Result == LazyValueInfo::Unknown) 394 return nullptr; 395 396 return (Result == LazyValueInfo::True) ? 397 ConstantInt::getTrue(C->getContext()) : 398 ConstantInt::getFalse(C->getContext()); 399 } 400 401 bool CorrelatedValuePropagation::runOnFunction(Function &F) { 402 if (skipOptnoneFunction(F)) 403 return false; 404 405 LVI = &getAnalysis<LazyValueInfo>(); 406 407 bool FnChanged = false; 408 409 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { 410 bool BBChanged = false; 411 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) { 412 Instruction *II = &*BI++; 413 switch (II->getOpcode()) { 414 case Instruction::Select: 415 BBChanged |= processSelect(cast<SelectInst>(II)); 416 break; 417 case Instruction::PHI: 418 BBChanged |= processPHI(cast<PHINode>(II)); 419 break; 420 case Instruction::ICmp: 421 case Instruction::FCmp: 422 BBChanged |= processCmp(cast<CmpInst>(II)); 423 break; 424 case Instruction::Load: 425 case Instruction::Store: 426 BBChanged |= processMemAccess(II); 427 break; 428 case Instruction::Call: 429 case Instruction::Invoke: 430 BBChanged |= processCallSite(CallSite(II)); 431 break; 432 case Instruction::SDiv: 433 BBChanged |= processSDiv(cast<BinaryOperator>(II)); 434 break; 435 } 436 } 437 438 Instruction *Term = FI->getTerminator(); 439 switch (Term->getOpcode()) { 440 case Instruction::Switch: 441 BBChanged |= processSwitch(cast<SwitchInst>(Term)); 442 break; 443 case Instruction::Ret: { 444 auto *RI = cast<ReturnInst>(Term); 445 // Try to determine the return value if we can. This is mainly here to 446 // simplify the writing of unit tests, but also helps to enable IPO by 447 // constant folding the return values of callees. 448 auto *RetVal = RI->getReturnValue(); 449 if (!RetVal) break; // handle "ret void" 450 if (isa<Constant>(RetVal)) break; // nothing to do 451 if (auto *C = getConstantAt(RetVal, RI)) { 452 ++NumReturns; 453 RI->replaceUsesOfWith(RetVal, C); 454 BBChanged = true; 455 } 456 } 457 }; 458 459 FnChanged |= BBChanged; 460 } 461 462 return FnChanged; 463 } 464