1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Correlated Value Propagation pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" 14 #include "llvm/ADT/DepthFirstIterator.h" 15 #include "llvm/ADT/Optional.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/Analysis/DomTreeUpdater.h" 19 #include "llvm/Analysis/GlobalsModRef.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/LazyValueInfo.h" 22 #include "llvm/IR/Attributes.h" 23 #include "llvm/IR/BasicBlock.h" 24 #include "llvm/IR/CFG.h" 25 #include "llvm/IR/CallSite.h" 26 #include "llvm/IR/Constant.h" 27 #include "llvm/IR/ConstantRange.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/IRBuilder.h" 32 #include "llvm/IR/InstrTypes.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/IntrinsicInst.h" 36 #include "llvm/IR/Operator.h" 37 #include "llvm/IR/PassManager.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/InitializePasses.h" 41 #include "llvm/Pass.h" 42 #include "llvm/Support/Casting.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Transforms/Scalar.h" 47 #include "llvm/Transforms/Utils/Local.h" 48 #include <cassert> 49 #include <utility> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "correlated-value-propagation" 54 55 STATISTIC(NumPhis, "Number of phis propagated"); 56 STATISTIC(NumPhiCommon, "Number of phis deleted via common incoming value"); 57 STATISTIC(NumSelects, "Number of selects propagated"); 58 STATISTIC(NumMemAccess, "Number of memory access targets propagated"); 59 STATISTIC(NumCmps, "Number of comparisons propagated"); 60 STATISTIC(NumReturns, "Number of return values propagated"); 61 STATISTIC(NumDeadCases, "Number of switch cases removed"); 62 STATISTIC(NumSDivs, "Number of sdiv converted to udiv"); 63 STATISTIC(NumUDivs, "Number of udivs whose width was decreased"); 64 STATISTIC(NumAShrs, "Number of ashr converted to lshr"); 65 STATISTIC(NumSRems, "Number of srem converted to urem"); 66 STATISTIC(NumSExt, "Number of sext converted to zext"); 67 STATISTIC(NumAnd, "Number of ands removed"); 68 STATISTIC(NumNW, "Number of no-wrap deductions"); 69 STATISTIC(NumNSW, "Number of no-signed-wrap deductions"); 70 STATISTIC(NumNUW, "Number of no-unsigned-wrap deductions"); 71 STATISTIC(NumAddNW, "Number of no-wrap deductions for add"); 72 STATISTIC(NumAddNSW, "Number of no-signed-wrap deductions for add"); 73 STATISTIC(NumAddNUW, "Number of no-unsigned-wrap deductions for add"); 74 STATISTIC(NumSubNW, "Number of no-wrap deductions for sub"); 75 STATISTIC(NumSubNSW, "Number of no-signed-wrap deductions for sub"); 76 STATISTIC(NumSubNUW, "Number of no-unsigned-wrap deductions for sub"); 77 STATISTIC(NumMulNW, "Number of no-wrap deductions for mul"); 78 STATISTIC(NumMulNSW, "Number of no-signed-wrap deductions for mul"); 79 STATISTIC(NumMulNUW, "Number of no-unsigned-wrap deductions for mul"); 80 STATISTIC(NumShlNW, "Number of no-wrap deductions for shl"); 81 STATISTIC(NumShlNSW, "Number of no-signed-wrap deductions for shl"); 82 STATISTIC(NumShlNUW, "Number of no-unsigned-wrap deductions for shl"); 83 STATISTIC(NumOverflows, "Number of overflow checks removed"); 84 STATISTIC(NumSaturating, 85 "Number of saturating arithmetics converted to normal arithmetics"); 86 87 static cl::opt<bool> DontAddNoWrapFlags("cvp-dont-add-nowrap-flags", cl::init(false)); 88 89 namespace { 90 91 class CorrelatedValuePropagation : public FunctionPass { 92 public: 93 static char ID; 94 95 CorrelatedValuePropagation(): FunctionPass(ID) { 96 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry()); 97 } 98 99 bool runOnFunction(Function &F) override; 100 101 void getAnalysisUsage(AnalysisUsage &AU) const override { 102 AU.addRequired<DominatorTreeWrapperPass>(); 103 AU.addRequired<LazyValueInfoWrapperPass>(); 104 AU.addPreserved<GlobalsAAWrapperPass>(); 105 AU.addPreserved<DominatorTreeWrapperPass>(); 106 AU.addPreserved<LazyValueInfoWrapperPass>(); 107 } 108 }; 109 110 } // end anonymous namespace 111 112 char CorrelatedValuePropagation::ID = 0; 113 114 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation", 115 "Value Propagation", false, false) 116 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 117 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 118 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation", 119 "Value Propagation", false, false) 120 121 // Public interface to the Value Propagation pass 122 Pass *llvm::createCorrelatedValuePropagationPass() { 123 return new CorrelatedValuePropagation(); 124 } 125 126 static bool processSelect(SelectInst *S, LazyValueInfo *LVI) { 127 if (S->getType()->isVectorTy()) return false; 128 if (isa<Constant>(S->getCondition())) return false; 129 130 Constant *C = LVI->getConstant(S->getCondition(), S->getParent(), S); 131 if (!C) return false; 132 133 ConstantInt *CI = dyn_cast<ConstantInt>(C); 134 if (!CI) return false; 135 136 Value *ReplaceWith = CI->isOne() ? S->getTrueValue() : S->getFalseValue(); 137 S->replaceAllUsesWith(ReplaceWith); 138 S->eraseFromParent(); 139 140 ++NumSelects; 141 142 return true; 143 } 144 145 /// Try to simplify a phi with constant incoming values that match the edge 146 /// values of a non-constant value on all other edges: 147 /// bb0: 148 /// %isnull = icmp eq i8* %x, null 149 /// br i1 %isnull, label %bb2, label %bb1 150 /// bb1: 151 /// br label %bb2 152 /// bb2: 153 /// %r = phi i8* [ %x, %bb1 ], [ null, %bb0 ] 154 /// --> 155 /// %r = %x 156 static bool simplifyCommonValuePhi(PHINode *P, LazyValueInfo *LVI, 157 DominatorTree *DT) { 158 // Collect incoming constants and initialize possible common value. 159 SmallVector<std::pair<Constant *, unsigned>, 4> IncomingConstants; 160 Value *CommonValue = nullptr; 161 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) { 162 Value *Incoming = P->getIncomingValue(i); 163 if (auto *IncomingConstant = dyn_cast<Constant>(Incoming)) { 164 IncomingConstants.push_back(std::make_pair(IncomingConstant, i)); 165 } else if (!CommonValue) { 166 // The potential common value is initialized to the first non-constant. 167 CommonValue = Incoming; 168 } else if (Incoming != CommonValue) { 169 // There can be only one non-constant common value. 170 return false; 171 } 172 } 173 174 if (!CommonValue || IncomingConstants.empty()) 175 return false; 176 177 // The common value must be valid in all incoming blocks. 178 BasicBlock *ToBB = P->getParent(); 179 if (auto *CommonInst = dyn_cast<Instruction>(CommonValue)) 180 if (!DT->dominates(CommonInst, ToBB)) 181 return false; 182 183 // We have a phi with exactly 1 variable incoming value and 1 or more constant 184 // incoming values. See if all constant incoming values can be mapped back to 185 // the same incoming variable value. 186 for (auto &IncomingConstant : IncomingConstants) { 187 Constant *C = IncomingConstant.first; 188 BasicBlock *IncomingBB = P->getIncomingBlock(IncomingConstant.second); 189 if (C != LVI->getConstantOnEdge(CommonValue, IncomingBB, ToBB, P)) 190 return false; 191 } 192 193 // All constant incoming values map to the same variable along the incoming 194 // edges of the phi. The phi is unnecessary. However, we must drop all 195 // poison-generating flags to ensure that no poison is propagated to the phi 196 // location by performing this substitution. 197 // Warning: If the underlying analysis changes, this may not be enough to 198 // guarantee that poison is not propagated. 199 // TODO: We may be able to re-infer flags by re-analyzing the instruction. 200 if (auto *CommonInst = dyn_cast<Instruction>(CommonValue)) 201 CommonInst->dropPoisonGeneratingFlags(); 202 P->replaceAllUsesWith(CommonValue); 203 P->eraseFromParent(); 204 ++NumPhiCommon; 205 return true; 206 } 207 208 static bool processPHI(PHINode *P, LazyValueInfo *LVI, DominatorTree *DT, 209 const SimplifyQuery &SQ) { 210 bool Changed = false; 211 212 BasicBlock *BB = P->getParent(); 213 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) { 214 Value *Incoming = P->getIncomingValue(i); 215 if (isa<Constant>(Incoming)) continue; 216 217 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P); 218 219 // Look if the incoming value is a select with a scalar condition for which 220 // LVI can tells us the value. In that case replace the incoming value with 221 // the appropriate value of the select. This often allows us to remove the 222 // select later. 223 if (!V) { 224 SelectInst *SI = dyn_cast<SelectInst>(Incoming); 225 if (!SI) continue; 226 227 Value *Condition = SI->getCondition(); 228 if (!Condition->getType()->isVectorTy()) { 229 if (Constant *C = LVI->getConstantOnEdge( 230 Condition, P->getIncomingBlock(i), BB, P)) { 231 if (C->isOneValue()) { 232 V = SI->getTrueValue(); 233 } else if (C->isZeroValue()) { 234 V = SI->getFalseValue(); 235 } 236 // Once LVI learns to handle vector types, we could also add support 237 // for vector type constants that are not all zeroes or all ones. 238 } 239 } 240 241 // Look if the select has a constant but LVI tells us that the incoming 242 // value can never be that constant. In that case replace the incoming 243 // value with the other value of the select. This often allows us to 244 // remove the select later. 245 if (!V) { 246 Constant *C = dyn_cast<Constant>(SI->getFalseValue()); 247 if (!C) continue; 248 249 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, 250 P->getIncomingBlock(i), BB, P) != 251 LazyValueInfo::False) 252 continue; 253 V = SI->getTrueValue(); 254 } 255 256 LLVM_DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n'); 257 } 258 259 P->setIncomingValue(i, V); 260 Changed = true; 261 } 262 263 if (Value *V = SimplifyInstruction(P, SQ)) { 264 P->replaceAllUsesWith(V); 265 P->eraseFromParent(); 266 Changed = true; 267 } 268 269 if (!Changed) 270 Changed = simplifyCommonValuePhi(P, LVI, DT); 271 272 if (Changed) 273 ++NumPhis; 274 275 return Changed; 276 } 277 278 static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) { 279 Value *Pointer = nullptr; 280 if (LoadInst *L = dyn_cast<LoadInst>(I)) 281 Pointer = L->getPointerOperand(); 282 else 283 Pointer = cast<StoreInst>(I)->getPointerOperand(); 284 285 if (isa<Constant>(Pointer)) return false; 286 287 Constant *C = LVI->getConstant(Pointer, I->getParent(), I); 288 if (!C) return false; 289 290 ++NumMemAccess; 291 I->replaceUsesOfWith(Pointer, C); 292 return true; 293 } 294 295 /// See if LazyValueInfo's ability to exploit edge conditions or range 296 /// information is sufficient to prove this comparison. Even for local 297 /// conditions, this can sometimes prove conditions instcombine can't by 298 /// exploiting range information. 299 static bool processCmp(CmpInst *Cmp, LazyValueInfo *LVI) { 300 Value *Op0 = Cmp->getOperand(0); 301 auto *C = dyn_cast<Constant>(Cmp->getOperand(1)); 302 if (!C) 303 return false; 304 305 // As a policy choice, we choose not to waste compile time on anything where 306 // the comparison is testing local values. While LVI can sometimes reason 307 // about such cases, it's not its primary purpose. We do make sure to do 308 // the block local query for uses from terminator instructions, but that's 309 // handled in the code for each terminator. As an exception, we allow phi 310 // nodes, for which LVI can thread the condition into predecessors. 311 auto *I = dyn_cast<Instruction>(Op0); 312 if (I && I->getParent() == Cmp->getParent() && !isa<PHINode>(I)) 313 return false; 314 315 LazyValueInfo::Tristate Result = 316 LVI->getPredicateAt(Cmp->getPredicate(), Op0, C, Cmp); 317 if (Result == LazyValueInfo::Unknown) 318 return false; 319 320 ++NumCmps; 321 Constant *TorF = ConstantInt::get(Type::getInt1Ty(Cmp->getContext()), Result); 322 Cmp->replaceAllUsesWith(TorF); 323 Cmp->eraseFromParent(); 324 return true; 325 } 326 327 /// Simplify a switch instruction by removing cases which can never fire. If the 328 /// uselessness of a case could be determined locally then constant propagation 329 /// would already have figured it out. Instead, walk the predecessors and 330 /// statically evaluate cases based on information available on that edge. Cases 331 /// that cannot fire no matter what the incoming edge can safely be removed. If 332 /// a case fires on every incoming edge then the entire switch can be removed 333 /// and replaced with a branch to the case destination. 334 static bool processSwitch(SwitchInst *I, LazyValueInfo *LVI, 335 DominatorTree *DT) { 336 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 337 Value *Cond = I->getCondition(); 338 BasicBlock *BB = I->getParent(); 339 340 // If the condition was defined in same block as the switch then LazyValueInfo 341 // currently won't say anything useful about it, though in theory it could. 342 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB) 343 return false; 344 345 // If the switch is unreachable then trying to improve it is a waste of time. 346 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 347 if (PB == PE) return false; 348 349 // Analyse each switch case in turn. 350 bool Changed = false; 351 DenseMap<BasicBlock*, int> SuccessorsCount; 352 for (auto *Succ : successors(BB)) 353 SuccessorsCount[Succ]++; 354 355 { // Scope for SwitchInstProfUpdateWrapper. It must not live during 356 // ConstantFoldTerminator() as the underlying SwitchInst can be changed. 357 SwitchInstProfUpdateWrapper SI(*I); 358 359 for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) { 360 ConstantInt *Case = CI->getCaseValue(); 361 362 // Check to see if the switch condition is equal to/not equal to the case 363 // value on every incoming edge, equal/not equal being the same each time. 364 LazyValueInfo::Tristate State = LazyValueInfo::Unknown; 365 for (pred_iterator PI = PB; PI != PE; ++PI) { 366 // Is the switch condition equal to the case value? 367 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ, 368 Cond, Case, *PI, 369 BB, SI); 370 // Give up on this case if nothing is known. 371 if (Value == LazyValueInfo::Unknown) { 372 State = LazyValueInfo::Unknown; 373 break; 374 } 375 376 // If this was the first edge to be visited, record that all other edges 377 // need to give the same result. 378 if (PI == PB) { 379 State = Value; 380 continue; 381 } 382 383 // If this case is known to fire for some edges and known not to fire for 384 // others then there is nothing we can do - give up. 385 if (Value != State) { 386 State = LazyValueInfo::Unknown; 387 break; 388 } 389 } 390 391 if (State == LazyValueInfo::False) { 392 // This case never fires - remove it. 393 BasicBlock *Succ = CI->getCaseSuccessor(); 394 Succ->removePredecessor(BB); 395 CI = SI.removeCase(CI); 396 CE = SI->case_end(); 397 398 // The condition can be modified by removePredecessor's PHI simplification 399 // logic. 400 Cond = SI->getCondition(); 401 402 ++NumDeadCases; 403 Changed = true; 404 if (--SuccessorsCount[Succ] == 0) 405 DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, Succ}}); 406 continue; 407 } 408 if (State == LazyValueInfo::True) { 409 // This case always fires. Arrange for the switch to be turned into an 410 // unconditional branch by replacing the switch condition with the case 411 // value. 412 SI->setCondition(Case); 413 NumDeadCases += SI->getNumCases(); 414 Changed = true; 415 break; 416 } 417 418 // Increment the case iterator since we didn't delete it. 419 ++CI; 420 } 421 } 422 423 if (Changed) 424 // If the switch has been simplified to the point where it can be replaced 425 // by a branch then do so now. 426 ConstantFoldTerminator(BB, /*DeleteDeadConditions = */ false, 427 /*TLI = */ nullptr, &DTU); 428 return Changed; 429 } 430 431 // See if we can prove that the given binary op intrinsic will not overflow. 432 static bool willNotOverflow(BinaryOpIntrinsic *BO, LazyValueInfo *LVI) { 433 ConstantRange LRange = LVI->getConstantRange( 434 BO->getLHS(), BO->getParent(), BO); 435 ConstantRange RRange = LVI->getConstantRange( 436 BO->getRHS(), BO->getParent(), BO); 437 ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 438 BO->getBinaryOp(), RRange, BO->getNoWrapKind()); 439 return NWRegion.contains(LRange); 440 } 441 442 static void setDeducedOverflowingFlags(Value *V, Instruction::BinaryOps Opcode, 443 bool NewNSW, bool NewNUW) { 444 Statistic *OpcNW, *OpcNSW, *OpcNUW; 445 switch (Opcode) { 446 case Instruction::Add: 447 OpcNW = &NumAddNW; 448 OpcNSW = &NumAddNSW; 449 OpcNUW = &NumAddNUW; 450 break; 451 case Instruction::Sub: 452 OpcNW = &NumSubNW; 453 OpcNSW = &NumSubNSW; 454 OpcNUW = &NumSubNUW; 455 break; 456 case Instruction::Mul: 457 OpcNW = &NumMulNW; 458 OpcNSW = &NumMulNSW; 459 OpcNUW = &NumMulNUW; 460 break; 461 case Instruction::Shl: 462 OpcNW = &NumShlNW; 463 OpcNSW = &NumShlNSW; 464 OpcNUW = &NumShlNUW; 465 break; 466 default: 467 llvm_unreachable("Will not be called with other binops"); 468 } 469 470 auto *Inst = dyn_cast<Instruction>(V); 471 if (NewNSW) { 472 ++NumNW; 473 ++*OpcNW; 474 ++NumNSW; 475 ++*OpcNSW; 476 if (Inst) 477 Inst->setHasNoSignedWrap(); 478 } 479 if (NewNUW) { 480 ++NumNW; 481 ++*OpcNW; 482 ++NumNUW; 483 ++*OpcNUW; 484 if (Inst) 485 Inst->setHasNoUnsignedWrap(); 486 } 487 } 488 489 static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI); 490 491 // Rewrite this with.overflow intrinsic as non-overflowing. 492 static void processOverflowIntrinsic(WithOverflowInst *WO, LazyValueInfo *LVI) { 493 IRBuilder<> B(WO); 494 Instruction::BinaryOps Opcode = WO->getBinaryOp(); 495 bool NSW = WO->isSigned(); 496 bool NUW = !WO->isSigned(); 497 498 Value *NewOp = 499 B.CreateBinOp(Opcode, WO->getLHS(), WO->getRHS(), WO->getName()); 500 setDeducedOverflowingFlags(NewOp, Opcode, NSW, NUW); 501 502 StructType *ST = cast<StructType>(WO->getType()); 503 Constant *Struct = ConstantStruct::get(ST, 504 { UndefValue::get(ST->getElementType(0)), 505 ConstantInt::getFalse(ST->getElementType(1)) }); 506 Value *NewI = B.CreateInsertValue(Struct, NewOp, 0); 507 WO->replaceAllUsesWith(NewI); 508 WO->eraseFromParent(); 509 ++NumOverflows; 510 511 // See if we can infer the other no-wrap too. 512 if (auto *BO = dyn_cast<BinaryOperator>(NewOp)) 513 processBinOp(BO, LVI); 514 } 515 516 static void processSaturatingInst(SaturatingInst *SI, LazyValueInfo *LVI) { 517 Instruction::BinaryOps Opcode = SI->getBinaryOp(); 518 bool NSW = SI->isSigned(); 519 bool NUW = !SI->isSigned(); 520 BinaryOperator *BinOp = BinaryOperator::Create( 521 Opcode, SI->getLHS(), SI->getRHS(), SI->getName(), SI); 522 BinOp->setDebugLoc(SI->getDebugLoc()); 523 setDeducedOverflowingFlags(BinOp, Opcode, NSW, NUW); 524 525 SI->replaceAllUsesWith(BinOp); 526 SI->eraseFromParent(); 527 ++NumSaturating; 528 529 // See if we can infer the other no-wrap too. 530 if (auto *BO = dyn_cast<BinaryOperator>(BinOp)) 531 processBinOp(BO, LVI); 532 } 533 534 /// Infer nonnull attributes for the arguments at the specified callsite. 535 static bool processCallSite(CallSite CS, LazyValueInfo *LVI) { 536 SmallVector<unsigned, 4> ArgNos; 537 unsigned ArgNo = 0; 538 539 if (auto *WO = dyn_cast<WithOverflowInst>(CS.getInstruction())) { 540 if (WO->getLHS()->getType()->isIntegerTy() && willNotOverflow(WO, LVI)) { 541 processOverflowIntrinsic(WO, LVI); 542 return true; 543 } 544 } 545 546 if (auto *SI = dyn_cast<SaturatingInst>(CS.getInstruction())) { 547 if (SI->getType()->isIntegerTy() && willNotOverflow(SI, LVI)) { 548 processSaturatingInst(SI, LVI); 549 return true; 550 } 551 } 552 553 // Deopt bundle operands are intended to capture state with minimal 554 // perturbance of the code otherwise. If we can find a constant value for 555 // any such operand and remove a use of the original value, that's 556 // desireable since it may allow further optimization of that value (e.g. via 557 // single use rules in instcombine). Since deopt uses tend to, 558 // idiomatically, appear along rare conditional paths, it's reasonable likely 559 // we may have a conditional fact with which LVI can fold. 560 if (auto DeoptBundle = CS.getOperandBundle(LLVMContext::OB_deopt)) { 561 bool Progress = false; 562 for (const Use &ConstU : DeoptBundle->Inputs) { 563 Use &U = const_cast<Use&>(ConstU); 564 Value *V = U.get(); 565 if (V->getType()->isVectorTy()) continue; 566 if (isa<Constant>(V)) continue; 567 568 Constant *C = LVI->getConstant(V, CS.getParent(), CS.getInstruction()); 569 if (!C) continue; 570 U.set(C); 571 Progress = true; 572 } 573 if (Progress) 574 return true; 575 } 576 577 for (Value *V : CS.args()) { 578 PointerType *Type = dyn_cast<PointerType>(V->getType()); 579 // Try to mark pointer typed parameters as non-null. We skip the 580 // relatively expensive analysis for constants which are obviously either 581 // null or non-null to start with. 582 if (Type && !CS.paramHasAttr(ArgNo, Attribute::NonNull) && 583 !isa<Constant>(V) && 584 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V, 585 ConstantPointerNull::get(Type), 586 CS.getInstruction()) == LazyValueInfo::False) 587 ArgNos.push_back(ArgNo); 588 ArgNo++; 589 } 590 591 assert(ArgNo == CS.arg_size() && "sanity check"); 592 593 if (ArgNos.empty()) 594 return false; 595 596 AttributeList AS = CS.getAttributes(); 597 LLVMContext &Ctx = CS.getInstruction()->getContext(); 598 AS = AS.addParamAttribute(Ctx, ArgNos, 599 Attribute::get(Ctx, Attribute::NonNull)); 600 CS.setAttributes(AS); 601 602 return true; 603 } 604 605 static bool hasPositiveOperands(BinaryOperator *SDI, LazyValueInfo *LVI) { 606 Constant *Zero = ConstantInt::get(SDI->getType(), 0); 607 for (Value *O : SDI->operands()) { 608 auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI); 609 if (Result != LazyValueInfo::True) 610 return false; 611 } 612 return true; 613 } 614 615 /// Try to shrink a udiv/urem's width down to the smallest power of two that's 616 /// sufficient to contain its operands. 617 static bool processUDivOrURem(BinaryOperator *Instr, LazyValueInfo *LVI) { 618 assert(Instr->getOpcode() == Instruction::UDiv || 619 Instr->getOpcode() == Instruction::URem); 620 if (Instr->getType()->isVectorTy()) 621 return false; 622 623 // Find the smallest power of two bitwidth that's sufficient to hold Instr's 624 // operands. 625 auto OrigWidth = Instr->getType()->getIntegerBitWidth(); 626 ConstantRange OperandRange(OrigWidth, /*isFullSet=*/false); 627 for (Value *Operand : Instr->operands()) { 628 OperandRange = OperandRange.unionWith( 629 LVI->getConstantRange(Operand, Instr->getParent())); 630 } 631 // Don't shrink below 8 bits wide. 632 unsigned NewWidth = std::max<unsigned>( 633 PowerOf2Ceil(OperandRange.getUnsignedMax().getActiveBits()), 8); 634 // NewWidth might be greater than OrigWidth if OrigWidth is not a power of 635 // two. 636 if (NewWidth >= OrigWidth) 637 return false; 638 639 ++NumUDivs; 640 IRBuilder<> B{Instr}; 641 auto *TruncTy = Type::getIntNTy(Instr->getContext(), NewWidth); 642 auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy, 643 Instr->getName() + ".lhs.trunc"); 644 auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy, 645 Instr->getName() + ".rhs.trunc"); 646 auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName()); 647 auto *Zext = B.CreateZExt(BO, Instr->getType(), Instr->getName() + ".zext"); 648 if (auto *BinOp = dyn_cast<BinaryOperator>(BO)) 649 if (BinOp->getOpcode() == Instruction::UDiv) 650 BinOp->setIsExact(Instr->isExact()); 651 652 Instr->replaceAllUsesWith(Zext); 653 Instr->eraseFromParent(); 654 return true; 655 } 656 657 static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) { 658 if (SDI->getType()->isVectorTy() || !hasPositiveOperands(SDI, LVI)) 659 return false; 660 661 ++NumSRems; 662 auto *BO = BinaryOperator::CreateURem(SDI->getOperand(0), SDI->getOperand(1), 663 SDI->getName(), SDI); 664 BO->setDebugLoc(SDI->getDebugLoc()); 665 SDI->replaceAllUsesWith(BO); 666 SDI->eraseFromParent(); 667 668 // Try to process our new urem. 669 processUDivOrURem(BO, LVI); 670 671 return true; 672 } 673 674 /// See if LazyValueInfo's ability to exploit edge conditions or range 675 /// information is sufficient to prove the both operands of this SDiv are 676 /// positive. If this is the case, replace the SDiv with a UDiv. Even for local 677 /// conditions, this can sometimes prove conditions instcombine can't by 678 /// exploiting range information. 679 static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) { 680 if (SDI->getType()->isVectorTy() || !hasPositiveOperands(SDI, LVI)) 681 return false; 682 683 ++NumSDivs; 684 auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1), 685 SDI->getName(), SDI); 686 BO->setDebugLoc(SDI->getDebugLoc()); 687 BO->setIsExact(SDI->isExact()); 688 SDI->replaceAllUsesWith(BO); 689 SDI->eraseFromParent(); 690 691 // Try to simplify our new udiv. 692 processUDivOrURem(BO, LVI); 693 694 return true; 695 } 696 697 static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) { 698 if (SDI->getType()->isVectorTy()) 699 return false; 700 701 Constant *Zero = ConstantInt::get(SDI->getType(), 0); 702 if (LVI->getPredicateAt(ICmpInst::ICMP_SGE, SDI->getOperand(0), Zero, SDI) != 703 LazyValueInfo::True) 704 return false; 705 706 ++NumAShrs; 707 auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1), 708 SDI->getName(), SDI); 709 BO->setDebugLoc(SDI->getDebugLoc()); 710 BO->setIsExact(SDI->isExact()); 711 SDI->replaceAllUsesWith(BO); 712 SDI->eraseFromParent(); 713 714 return true; 715 } 716 717 static bool processSExt(SExtInst *SDI, LazyValueInfo *LVI) { 718 if (SDI->getType()->isVectorTy()) 719 return false; 720 721 Value *Base = SDI->getOperand(0); 722 723 Constant *Zero = ConstantInt::get(Base->getType(), 0); 724 if (LVI->getPredicateAt(ICmpInst::ICMP_SGE, Base, Zero, SDI) != 725 LazyValueInfo::True) 726 return false; 727 728 ++NumSExt; 729 auto *ZExt = 730 CastInst::CreateZExtOrBitCast(Base, SDI->getType(), SDI->getName(), SDI); 731 ZExt->setDebugLoc(SDI->getDebugLoc()); 732 SDI->replaceAllUsesWith(ZExt); 733 SDI->eraseFromParent(); 734 735 return true; 736 } 737 738 static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI) { 739 using OBO = OverflowingBinaryOperator; 740 741 if (DontAddNoWrapFlags) 742 return false; 743 744 if (BinOp->getType()->isVectorTy()) 745 return false; 746 747 bool NSW = BinOp->hasNoSignedWrap(); 748 bool NUW = BinOp->hasNoUnsignedWrap(); 749 if (NSW && NUW) 750 return false; 751 752 BasicBlock *BB = BinOp->getParent(); 753 754 Instruction::BinaryOps Opcode = BinOp->getOpcode(); 755 Value *LHS = BinOp->getOperand(0); 756 Value *RHS = BinOp->getOperand(1); 757 758 ConstantRange LRange = LVI->getConstantRange(LHS, BB, BinOp); 759 ConstantRange RRange = LVI->getConstantRange(RHS, BB, BinOp); 760 761 bool Changed = false; 762 bool NewNUW = false, NewNSW = false; 763 if (!NUW) { 764 ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion( 765 Opcode, RRange, OBO::NoUnsignedWrap); 766 NewNUW = NUWRange.contains(LRange); 767 Changed |= NewNUW; 768 } 769 if (!NSW) { 770 ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion( 771 Opcode, RRange, OBO::NoSignedWrap); 772 NewNSW = NSWRange.contains(LRange); 773 Changed |= NewNSW; 774 } 775 776 setDeducedOverflowingFlags(BinOp, Opcode, NewNSW, NewNUW); 777 778 return Changed; 779 } 780 781 static bool processAnd(BinaryOperator *BinOp, LazyValueInfo *LVI) { 782 if (BinOp->getType()->isVectorTy()) 783 return false; 784 785 // Pattern match (and lhs, C) where C includes a superset of bits which might 786 // be set in lhs. This is a common truncation idiom created by instcombine. 787 BasicBlock *BB = BinOp->getParent(); 788 Value *LHS = BinOp->getOperand(0); 789 ConstantInt *RHS = dyn_cast<ConstantInt>(BinOp->getOperand(1)); 790 if (!RHS || !RHS->getValue().isMask()) 791 return false; 792 793 // We can only replace the AND with LHS based on range info if the range does 794 // not include undef. 795 ConstantRange LRange = 796 LVI->getConstantRange(LHS, BB, BinOp, /*UndefAllowed=*/false); 797 if (!LRange.getUnsignedMax().ule(RHS->getValue())) 798 return false; 799 800 BinOp->replaceAllUsesWith(LHS); 801 BinOp->eraseFromParent(); 802 NumAnd++; 803 return true; 804 } 805 806 807 static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) { 808 if (Constant *C = LVI->getConstant(V, At->getParent(), At)) 809 return C; 810 811 // TODO: The following really should be sunk inside LVI's core algorithm, or 812 // at least the outer shims around such. 813 auto *C = dyn_cast<CmpInst>(V); 814 if (!C) return nullptr; 815 816 Value *Op0 = C->getOperand(0); 817 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); 818 if (!Op1) return nullptr; 819 820 LazyValueInfo::Tristate Result = 821 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At); 822 if (Result == LazyValueInfo::Unknown) 823 return nullptr; 824 825 return (Result == LazyValueInfo::True) ? 826 ConstantInt::getTrue(C->getContext()) : 827 ConstantInt::getFalse(C->getContext()); 828 } 829 830 static bool runImpl(Function &F, LazyValueInfo *LVI, DominatorTree *DT, 831 const SimplifyQuery &SQ) { 832 bool FnChanged = false; 833 // Visiting in a pre-order depth-first traversal causes us to simplify early 834 // blocks before querying later blocks (which require us to analyze early 835 // blocks). Eagerly simplifying shallow blocks means there is strictly less 836 // work to do for deep blocks. This also means we don't visit unreachable 837 // blocks. 838 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) { 839 bool BBChanged = false; 840 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { 841 Instruction *II = &*BI++; 842 switch (II->getOpcode()) { 843 case Instruction::Select: 844 BBChanged |= processSelect(cast<SelectInst>(II), LVI); 845 break; 846 case Instruction::PHI: 847 BBChanged |= processPHI(cast<PHINode>(II), LVI, DT, SQ); 848 break; 849 case Instruction::ICmp: 850 case Instruction::FCmp: 851 BBChanged |= processCmp(cast<CmpInst>(II), LVI); 852 break; 853 case Instruction::Load: 854 case Instruction::Store: 855 BBChanged |= processMemAccess(II, LVI); 856 break; 857 case Instruction::Call: 858 case Instruction::Invoke: 859 BBChanged |= processCallSite(CallSite(II), LVI); 860 break; 861 case Instruction::SRem: 862 BBChanged |= processSRem(cast<BinaryOperator>(II), LVI); 863 break; 864 case Instruction::SDiv: 865 BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI); 866 break; 867 case Instruction::UDiv: 868 case Instruction::URem: 869 BBChanged |= processUDivOrURem(cast<BinaryOperator>(II), LVI); 870 break; 871 case Instruction::AShr: 872 BBChanged |= processAShr(cast<BinaryOperator>(II), LVI); 873 break; 874 case Instruction::SExt: 875 BBChanged |= processSExt(cast<SExtInst>(II), LVI); 876 break; 877 case Instruction::Add: 878 case Instruction::Sub: 879 case Instruction::Mul: 880 case Instruction::Shl: 881 BBChanged |= processBinOp(cast<BinaryOperator>(II), LVI); 882 break; 883 case Instruction::And: 884 BBChanged |= processAnd(cast<BinaryOperator>(II), LVI); 885 break; 886 } 887 } 888 889 Instruction *Term = BB->getTerminator(); 890 switch (Term->getOpcode()) { 891 case Instruction::Switch: 892 BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI, DT); 893 break; 894 case Instruction::Ret: { 895 auto *RI = cast<ReturnInst>(Term); 896 // Try to determine the return value if we can. This is mainly here to 897 // simplify the writing of unit tests, but also helps to enable IPO by 898 // constant folding the return values of callees. 899 auto *RetVal = RI->getReturnValue(); 900 if (!RetVal) break; // handle "ret void" 901 if (isa<Constant>(RetVal)) break; // nothing to do 902 if (auto *C = getConstantAt(RetVal, RI, LVI)) { 903 ++NumReturns; 904 RI->replaceUsesOfWith(RetVal, C); 905 BBChanged = true; 906 } 907 } 908 } 909 910 FnChanged |= BBChanged; 911 } 912 913 return FnChanged; 914 } 915 916 bool CorrelatedValuePropagation::runOnFunction(Function &F) { 917 if (skipFunction(F)) 918 return false; 919 920 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI(); 921 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 922 923 return runImpl(F, LVI, DT, getBestSimplifyQuery(*this, F)); 924 } 925 926 PreservedAnalyses 927 CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) { 928 LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F); 929 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F); 930 931 bool Changed = runImpl(F, LVI, DT, getBestSimplifyQuery(AM, F)); 932 933 if (!Changed) 934 return PreservedAnalyses::all(); 935 PreservedAnalyses PA; 936 PA.preserve<GlobalsAA>(); 937 PA.preserve<DominatorTreeAnalysis>(); 938 PA.preserve<LazyValueAnalysis>(); 939 return PA; 940 } 941