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