1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 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 sparse conditional constant propagation and merging: 11 // 12 // Specifically, this: 13 // * Assumes values are constant unless proven otherwise 14 // * Assumes BasicBlocks are dead unless proven otherwise 15 // * Proves values to be constant, and replaces them with constants 16 // * Proves conditional branches to be unconditional 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Transforms/Scalar/SCCP.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/DenseSet.h" 24 #include "llvm/ADT/PointerIntPair.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallPtrSet.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/GlobalsModRef.h" 31 #include "llvm/Analysis/TargetLibraryInfo.h" 32 #include "llvm/Transforms/Utils/Local.h" 33 #include "llvm/Analysis/ValueLattice.h" 34 #include "llvm/Analysis/ValueLatticeUtils.h" 35 #include "llvm/IR/BasicBlock.h" 36 #include "llvm/IR/CallSite.h" 37 #include "llvm/IR/Constant.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/DataLayout.h" 40 #include "llvm/IR/DerivedTypes.h" 41 #include "llvm/IR/Function.h" 42 #include "llvm/IR/GlobalVariable.h" 43 #include "llvm/IR/InstVisitor.h" 44 #include "llvm/IR/InstrTypes.h" 45 #include "llvm/IR/Instruction.h" 46 #include "llvm/IR/Instructions.h" 47 #include "llvm/IR/Module.h" 48 #include "llvm/IR/PassManager.h" 49 #include "llvm/IR/Type.h" 50 #include "llvm/IR/User.h" 51 #include "llvm/IR/Value.h" 52 #include "llvm/Pass.h" 53 #include "llvm/Support/Casting.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include "llvm/Transforms/Scalar.h" 58 #include <cassert> 59 #include <utility> 60 #include <vector> 61 62 using namespace llvm; 63 64 #define DEBUG_TYPE "sccp" 65 66 STATISTIC(NumInstRemoved, "Number of instructions removed"); 67 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable"); 68 69 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP"); 70 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP"); 71 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP"); 72 STATISTIC(IPNumRangeInfoUsed, "Number of times constant range info was used by" 73 "IPSCCP"); 74 75 namespace { 76 77 /// LatticeVal class - This class represents the different lattice values that 78 /// an LLVM value may occupy. It is a simple class with value semantics. 79 /// 80 class LatticeVal { 81 enum LatticeValueTy { 82 /// unknown - This LLVM Value has no known value yet. 83 unknown, 84 85 /// constant - This LLVM Value has a specific constant value. 86 constant, 87 88 /// forcedconstant - This LLVM Value was thought to be undef until 89 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged 90 /// with another (different) constant, it goes to overdefined, instead of 91 /// asserting. 92 forcedconstant, 93 94 /// overdefined - This instruction is not known to be constant, and we know 95 /// it has a value. 96 overdefined 97 }; 98 99 /// Val: This stores the current lattice value along with the Constant* for 100 /// the constant if this is a 'constant' or 'forcedconstant' value. 101 PointerIntPair<Constant *, 2, LatticeValueTy> Val; 102 103 LatticeValueTy getLatticeValue() const { 104 return Val.getInt(); 105 } 106 107 public: 108 LatticeVal() : Val(nullptr, unknown) {} 109 110 bool isUnknown() const { return getLatticeValue() == unknown; } 111 112 bool isConstant() const { 113 return getLatticeValue() == constant || getLatticeValue() == forcedconstant; 114 } 115 116 bool isOverdefined() const { return getLatticeValue() == overdefined; } 117 118 Constant *getConstant() const { 119 assert(isConstant() && "Cannot get the constant of a non-constant!"); 120 return Val.getPointer(); 121 } 122 123 /// markOverdefined - Return true if this is a change in status. 124 bool markOverdefined() { 125 if (isOverdefined()) 126 return false; 127 128 Val.setInt(overdefined); 129 return true; 130 } 131 132 /// markConstant - Return true if this is a change in status. 133 bool markConstant(Constant *V) { 134 if (getLatticeValue() == constant) { // Constant but not forcedconstant. 135 assert(getConstant() == V && "Marking constant with different value"); 136 return false; 137 } 138 139 if (isUnknown()) { 140 Val.setInt(constant); 141 assert(V && "Marking constant with NULL"); 142 Val.setPointer(V); 143 } else { 144 assert(getLatticeValue() == forcedconstant && 145 "Cannot move from overdefined to constant!"); 146 // Stay at forcedconstant if the constant is the same. 147 if (V == getConstant()) return false; 148 149 // Otherwise, we go to overdefined. Assumptions made based on the 150 // forced value are possibly wrong. Assuming this is another constant 151 // could expose a contradiction. 152 Val.setInt(overdefined); 153 } 154 return true; 155 } 156 157 /// getConstantInt - If this is a constant with a ConstantInt value, return it 158 /// otherwise return null. 159 ConstantInt *getConstantInt() const { 160 if (isConstant()) 161 return dyn_cast<ConstantInt>(getConstant()); 162 return nullptr; 163 } 164 165 /// getBlockAddress - If this is a constant with a BlockAddress value, return 166 /// it, otherwise return null. 167 BlockAddress *getBlockAddress() const { 168 if (isConstant()) 169 return dyn_cast<BlockAddress>(getConstant()); 170 return nullptr; 171 } 172 173 void markForcedConstant(Constant *V) { 174 assert(isUnknown() && "Can't force a defined value!"); 175 Val.setInt(forcedconstant); 176 Val.setPointer(V); 177 } 178 179 ValueLatticeElement toValueLattice() const { 180 if (isOverdefined()) 181 return ValueLatticeElement::getOverdefined(); 182 if (isConstant()) 183 return ValueLatticeElement::get(getConstant()); 184 return ValueLatticeElement(); 185 } 186 }; 187 188 //===----------------------------------------------------------------------===// 189 // 190 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional 191 /// Constant Propagation. 192 /// 193 class SCCPSolver : public InstVisitor<SCCPSolver> { 194 const DataLayout &DL; 195 const TargetLibraryInfo *TLI; 196 SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable. 197 DenseMap<Value *, LatticeVal> ValueState; // The state each value is in. 198 // The state each parameter is in. 199 DenseMap<Value *, ValueLatticeElement> ParamState; 200 201 /// StructValueState - This maintains ValueState for values that have 202 /// StructType, for example for formal arguments, calls, insertelement, etc. 203 DenseMap<std::pair<Value *, unsigned>, LatticeVal> StructValueState; 204 205 /// GlobalValue - If we are tracking any values for the contents of a global 206 /// variable, we keep a mapping from the constant accessor to the element of 207 /// the global, to the currently known value. If the value becomes 208 /// overdefined, it's entry is simply removed from this map. 209 DenseMap<GlobalVariable *, LatticeVal> TrackedGlobals; 210 211 /// TrackedRetVals - If we are tracking arguments into and the return 212 /// value out of a function, it will have an entry in this map, indicating 213 /// what the known return value for the function is. 214 DenseMap<Function *, LatticeVal> TrackedRetVals; 215 216 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions 217 /// that return multiple values. 218 DenseMap<std::pair<Function *, unsigned>, LatticeVal> TrackedMultipleRetVals; 219 220 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is 221 /// represented here for efficient lookup. 222 SmallPtrSet<Function *, 16> MRVFunctionsTracked; 223 224 /// MustTailFunctions - Each function here is a callee of non-removable 225 /// musttail call site. 226 SmallPtrSet<Function *, 16> MustTailCallees; 227 228 /// TrackingIncomingArguments - This is the set of functions for whose 229 /// arguments we make optimistic assumptions about and try to prove as 230 /// constants. 231 SmallPtrSet<Function *, 16> TrackingIncomingArguments; 232 233 /// The reason for two worklists is that overdefined is the lowest state 234 /// on the lattice, and moving things to overdefined as fast as possible 235 /// makes SCCP converge much faster. 236 /// 237 /// By having a separate worklist, we accomplish this because everything 238 /// possibly overdefined will become overdefined at the soonest possible 239 /// point. 240 SmallVector<Value *, 64> OverdefinedInstWorkList; 241 SmallVector<Value *, 64> InstWorkList; 242 243 // The BasicBlock work list 244 SmallVector<BasicBlock *, 64> BBWorkList; 245 246 /// KnownFeasibleEdges - Entries in this set are edges which have already had 247 /// PHI nodes retriggered. 248 using Edge = std::pair<BasicBlock *, BasicBlock *>; 249 DenseSet<Edge> KnownFeasibleEdges; 250 251 public: 252 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli) 253 : DL(DL), TLI(tli) {} 254 255 /// MarkBlockExecutable - This method can be used by clients to mark all of 256 /// the blocks that are known to be intrinsically live in the processed unit. 257 /// 258 /// This returns true if the block was not considered live before. 259 bool MarkBlockExecutable(BasicBlock *BB) { 260 if (!BBExecutable.insert(BB).second) 261 return false; 262 LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n'); 263 BBWorkList.push_back(BB); // Add the block to the work list! 264 return true; 265 } 266 267 /// TrackValueOfGlobalVariable - Clients can use this method to 268 /// inform the SCCPSolver that it should track loads and stores to the 269 /// specified global variable if it can. This is only legal to call if 270 /// performing Interprocedural SCCP. 271 void TrackValueOfGlobalVariable(GlobalVariable *GV) { 272 // We only track the contents of scalar globals. 273 if (GV->getValueType()->isSingleValueType()) { 274 LatticeVal &IV = TrackedGlobals[GV]; 275 if (!isa<UndefValue>(GV->getInitializer())) 276 IV.markConstant(GV->getInitializer()); 277 } 278 } 279 280 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into 281 /// and out of the specified function (which cannot have its address taken), 282 /// this method must be called. 283 void AddTrackedFunction(Function *F) { 284 // Add an entry, F -> undef. 285 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) { 286 MRVFunctionsTracked.insert(F); 287 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 288 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i), 289 LatticeVal())); 290 } else 291 TrackedRetVals.insert(std::make_pair(F, LatticeVal())); 292 } 293 294 /// AddMustTailCallee - If the SCCP solver finds that this function is called 295 /// from non-removable musttail call site. 296 void AddMustTailCallee(Function *F) { 297 MustTailCallees.insert(F); 298 } 299 300 /// Returns true if the given function is called from non-removable musttail 301 /// call site. 302 bool isMustTailCallee(Function *F) { 303 return MustTailCallees.count(F); 304 } 305 306 void AddArgumentTrackedFunction(Function *F) { 307 TrackingIncomingArguments.insert(F); 308 } 309 310 /// Returns true if the given function is in the solver's set of 311 /// argument-tracked functions. 312 bool isArgumentTrackedFunction(Function *F) { 313 return TrackingIncomingArguments.count(F); 314 } 315 316 /// Solve - Solve for constants and executable blocks. 317 void Solve(); 318 319 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 320 /// that branches on undef values cannot reach any of their successors. 321 /// However, this is not a safe assumption. After we solve dataflow, this 322 /// method should be use to handle this. If this returns true, the solver 323 /// should be rerun. 324 bool ResolvedUndefsIn(Function &F); 325 326 bool isBlockExecutable(BasicBlock *BB) const { 327 return BBExecutable.count(BB); 328 } 329 330 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const { 331 std::vector<LatticeVal> StructValues; 332 auto *STy = dyn_cast<StructType>(V->getType()); 333 assert(STy && "getStructLatticeValueFor() can be called only on structs"); 334 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 335 auto I = StructValueState.find(std::make_pair(V, i)); 336 assert(I != StructValueState.end() && "Value not in valuemap!"); 337 StructValues.push_back(I->second); 338 } 339 return StructValues; 340 } 341 342 ValueLatticeElement getLatticeValueFor(Value *V) { 343 assert(!V->getType()->isStructTy() && 344 "Should use getStructLatticeValueFor"); 345 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool> 346 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement())); 347 ValueLatticeElement &LV = PI.first->second; 348 if (PI.second) { 349 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V); 350 assert(I != ValueState.end() && 351 "V not found in ValueState nor Paramstate map!"); 352 LV = I->second.toValueLattice(); 353 } 354 355 return LV; 356 } 357 358 /// getTrackedRetVals - Get the inferred return value map. 359 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() { 360 return TrackedRetVals; 361 } 362 363 /// getTrackedGlobals - Get and return the set of inferred initializers for 364 /// global variables. 365 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() { 366 return TrackedGlobals; 367 } 368 369 /// getMRVFunctionsTracked - Get the set of functions which return multiple 370 /// values tracked by the pass. 371 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() { 372 return MRVFunctionsTracked; 373 } 374 375 /// getMustTailCallees - Get the set of functions which are called 376 /// from non-removable musttail call sites. 377 const SmallPtrSet<Function *, 16> getMustTailCallees() { 378 return MustTailCallees; 379 } 380 381 /// markOverdefined - Mark the specified value overdefined. This 382 /// works with both scalars and structs. 383 void markOverdefined(Value *V) { 384 if (auto *STy = dyn_cast<StructType>(V->getType())) 385 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 386 markOverdefined(getStructValueState(V, i), V); 387 else 388 markOverdefined(ValueState[V], V); 389 } 390 391 // isStructLatticeConstant - Return true if all the lattice values 392 // corresponding to elements of the structure are not overdefined, 393 // false otherwise. 394 bool isStructLatticeConstant(Function *F, StructType *STy) { 395 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 396 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i)); 397 assert(It != TrackedMultipleRetVals.end()); 398 LatticeVal LV = It->second; 399 if (LV.isOverdefined()) 400 return false; 401 } 402 return true; 403 } 404 405 private: 406 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined 407 void pushToWorkList(LatticeVal &IV, Value *V) { 408 if (IV.isOverdefined()) 409 return OverdefinedInstWorkList.push_back(V); 410 InstWorkList.push_back(V); 411 } 412 413 // markConstant - Make a value be marked as "constant". If the value 414 // is not already a constant, add it to the instruction work list so that 415 // the users of the instruction are updated later. 416 void markConstant(LatticeVal &IV, Value *V, Constant *C) { 417 if (!IV.markConstant(C)) return; 418 LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n'); 419 pushToWorkList(IV, V); 420 } 421 422 void markConstant(Value *V, Constant *C) { 423 assert(!V->getType()->isStructTy() && "structs should use mergeInValue"); 424 markConstant(ValueState[V], V, C); 425 } 426 427 void markForcedConstant(Value *V, Constant *C) { 428 assert(!V->getType()->isStructTy() && "structs should use mergeInValue"); 429 LatticeVal &IV = ValueState[V]; 430 IV.markForcedConstant(C); 431 LLVM_DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n'); 432 pushToWorkList(IV, V); 433 } 434 435 // markOverdefined - Make a value be marked as "overdefined". If the 436 // value is not already overdefined, add it to the overdefined instruction 437 // work list so that the users of the instruction are updated later. 438 void markOverdefined(LatticeVal &IV, Value *V) { 439 if (!IV.markOverdefined()) return; 440 441 LLVM_DEBUG(dbgs() << "markOverdefined: "; 442 if (auto *F = dyn_cast<Function>(V)) dbgs() 443 << "Function '" << F->getName() << "'\n"; 444 else dbgs() << *V << '\n'); 445 // Only instructions go on the work list 446 pushToWorkList(IV, V); 447 } 448 449 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) { 450 if (IV.isOverdefined() || MergeWithV.isUnknown()) 451 return; // Noop. 452 if (MergeWithV.isOverdefined()) 453 return markOverdefined(IV, V); 454 if (IV.isUnknown()) 455 return markConstant(IV, V, MergeWithV.getConstant()); 456 if (IV.getConstant() != MergeWithV.getConstant()) 457 return markOverdefined(IV, V); 458 } 459 460 void mergeInValue(Value *V, LatticeVal MergeWithV) { 461 assert(!V->getType()->isStructTy() && 462 "non-structs should use markConstant"); 463 mergeInValue(ValueState[V], V, MergeWithV); 464 } 465 466 /// getValueState - Return the LatticeVal object that corresponds to the 467 /// value. This function handles the case when the value hasn't been seen yet 468 /// by properly seeding constants etc. 469 LatticeVal &getValueState(Value *V) { 470 assert(!V->getType()->isStructTy() && "Should use getStructValueState"); 471 472 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I = 473 ValueState.insert(std::make_pair(V, LatticeVal())); 474 LatticeVal &LV = I.first->second; 475 476 if (!I.second) 477 return LV; // Common case, already in the map. 478 479 if (auto *C = dyn_cast<Constant>(V)) { 480 // Undef values remain unknown. 481 if (!isa<UndefValue>(V)) 482 LV.markConstant(C); // Constants are constant 483 } 484 485 // All others are underdefined by default. 486 return LV; 487 } 488 489 ValueLatticeElement &getParamState(Value *V) { 490 assert(!V->getType()->isStructTy() && "Should use getStructValueState"); 491 492 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool> 493 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement())); 494 ValueLatticeElement &LV = PI.first->second; 495 if (PI.second) 496 LV = getValueState(V).toValueLattice(); 497 498 return LV; 499 } 500 501 /// getStructValueState - Return the LatticeVal object that corresponds to the 502 /// value/field pair. This function handles the case when the value hasn't 503 /// been seen yet by properly seeding constants etc. 504 LatticeVal &getStructValueState(Value *V, unsigned i) { 505 assert(V->getType()->isStructTy() && "Should use getValueState"); 506 assert(i < cast<StructType>(V->getType())->getNumElements() && 507 "Invalid element #"); 508 509 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator, 510 bool> I = StructValueState.insert( 511 std::make_pair(std::make_pair(V, i), LatticeVal())); 512 LatticeVal &LV = I.first->second; 513 514 if (!I.second) 515 return LV; // Common case, already in the map. 516 517 if (auto *C = dyn_cast<Constant>(V)) { 518 Constant *Elt = C->getAggregateElement(i); 519 520 if (!Elt) 521 LV.markOverdefined(); // Unknown sort of constant. 522 else if (isa<UndefValue>(Elt)) 523 ; // Undef values remain unknown. 524 else 525 LV.markConstant(Elt); // Constants are constant. 526 } 527 528 // All others are underdefined by default. 529 return LV; 530 } 531 532 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB 533 /// work list if it is not already executable. 534 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { 535 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) 536 return; // This edge is already known to be executable! 537 538 if (!MarkBlockExecutable(Dest)) { 539 // If the destination is already executable, we just made an *edge* 540 // feasible that wasn't before. Revisit the PHI nodes in the block 541 // because they have potentially new operands. 542 LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName() 543 << " -> " << Dest->getName() << '\n'); 544 545 for (PHINode &PN : Dest->phis()) 546 visitPHINode(PN); 547 } 548 } 549 550 // getFeasibleSuccessors - Return a vector of booleans to indicate which 551 // successors are reachable from a given terminator instruction. 552 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs); 553 554 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 555 // block to the 'To' basic block is currently feasible. 556 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To); 557 558 // OperandChangedState - This method is invoked on all of the users of an 559 // instruction that was just changed state somehow. Based on this 560 // information, we need to update the specified user of this instruction. 561 void OperandChangedState(Instruction *I) { 562 if (BBExecutable.count(I->getParent())) // Inst is executable? 563 visit(*I); 564 } 565 566 private: 567 friend class InstVisitor<SCCPSolver>; 568 569 // visit implementations - Something changed in this instruction. Either an 570 // operand made a transition, or the instruction is newly executable. Change 571 // the value type of I to reflect these changes if appropriate. 572 void visitPHINode(PHINode &I); 573 574 // Terminators 575 576 void visitReturnInst(ReturnInst &I); 577 void visitTerminatorInst(TerminatorInst &TI); 578 579 void visitCastInst(CastInst &I); 580 void visitSelectInst(SelectInst &I); 581 void visitBinaryOperator(Instruction &I); 582 void visitCmpInst(CmpInst &I); 583 void visitExtractValueInst(ExtractValueInst &EVI); 584 void visitInsertValueInst(InsertValueInst &IVI); 585 586 void visitCatchSwitchInst(CatchSwitchInst &CPI) { 587 markOverdefined(&CPI); 588 visitTerminatorInst(CPI); 589 } 590 591 // Instructions that cannot be folded away. 592 593 void visitStoreInst (StoreInst &I); 594 void visitLoadInst (LoadInst &I); 595 void visitGetElementPtrInst(GetElementPtrInst &I); 596 597 void visitCallInst (CallInst &I) { 598 visitCallSite(&I); 599 } 600 601 void visitInvokeInst (InvokeInst &II) { 602 visitCallSite(&II); 603 visitTerminatorInst(II); 604 } 605 606 void visitCallSite (CallSite CS); 607 void visitResumeInst (TerminatorInst &I) { /*returns void*/ } 608 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ } 609 void visitFenceInst (FenceInst &I) { /*returns void*/ } 610 611 void visitInstruction(Instruction &I) { 612 // All the instructions we don't do any special handling for just 613 // go to overdefined. 614 LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n'); 615 markOverdefined(&I); 616 } 617 }; 618 619 } // end anonymous namespace 620 621 // getFeasibleSuccessors - Return a vector of booleans to indicate which 622 // successors are reachable from a given terminator instruction. 623 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI, 624 SmallVectorImpl<bool> &Succs) { 625 Succs.resize(TI.getNumSuccessors()); 626 if (auto *BI = dyn_cast<BranchInst>(&TI)) { 627 if (BI->isUnconditional()) { 628 Succs[0] = true; 629 return; 630 } 631 632 LatticeVal BCValue = getValueState(BI->getCondition()); 633 ConstantInt *CI = BCValue.getConstantInt(); 634 if (!CI) { 635 // Overdefined condition variables, and branches on unfoldable constant 636 // conditions, mean the branch could go either way. 637 if (!BCValue.isUnknown()) 638 Succs[0] = Succs[1] = true; 639 return; 640 } 641 642 // Constant condition variables mean the branch can only go a single way. 643 Succs[CI->isZero()] = true; 644 return; 645 } 646 647 // Unwinding instructions successors are always executable. 648 if (TI.isExceptional()) { 649 Succs.assign(TI.getNumSuccessors(), true); 650 return; 651 } 652 653 if (auto *SI = dyn_cast<SwitchInst>(&TI)) { 654 if (!SI->getNumCases()) { 655 Succs[0] = true; 656 return; 657 } 658 LatticeVal SCValue = getValueState(SI->getCondition()); 659 ConstantInt *CI = SCValue.getConstantInt(); 660 661 if (!CI) { // Overdefined or unknown condition? 662 // All destinations are executable! 663 if (!SCValue.isUnknown()) 664 Succs.assign(TI.getNumSuccessors(), true); 665 return; 666 } 667 668 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true; 669 return; 670 } 671 672 // In case of indirect branch and its address is a blockaddress, we mark 673 // the target as executable. 674 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) { 675 // Casts are folded by visitCastInst. 676 LatticeVal IBRValue = getValueState(IBR->getAddress()); 677 BlockAddress *Addr = IBRValue.getBlockAddress(); 678 if (!Addr) { // Overdefined or unknown condition? 679 // All destinations are executable! 680 if (!IBRValue.isUnknown()) 681 Succs.assign(TI.getNumSuccessors(), true); 682 return; 683 } 684 685 BasicBlock* T = Addr->getBasicBlock(); 686 assert(Addr->getFunction() == T->getParent() && 687 "Block address of a different function ?"); 688 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) { 689 // This is the target. 690 if (IBR->getDestination(i) == T) { 691 Succs[i] = true; 692 return; 693 } 694 } 695 696 // If we didn't find our destination in the IBR successor list, then we 697 // have undefined behavior. Its ok to assume no successor is executable. 698 return; 699 } 700 701 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n'); 702 llvm_unreachable("SCCP: Don't know how to handle this terminator!"); 703 } 704 705 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 706 // block to the 'To' basic block is currently feasible. 707 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) { 708 assert(BBExecutable.count(To) && "Dest should always be alive!"); 709 710 // Make sure the source basic block is executable!! 711 if (!BBExecutable.count(From)) return false; 712 713 // Check to make sure this edge itself is actually feasible now. 714 TerminatorInst *TI = From->getTerminator(); 715 if (auto *BI = dyn_cast<BranchInst>(TI)) { 716 if (BI->isUnconditional()) 717 return true; 718 719 LatticeVal BCValue = getValueState(BI->getCondition()); 720 721 // Overdefined condition variables mean the branch could go either way, 722 // undef conditions mean that neither edge is feasible yet. 723 ConstantInt *CI = BCValue.getConstantInt(); 724 if (!CI) 725 return !BCValue.isUnknown(); 726 727 // Constant condition variables mean the branch can only go a single way. 728 return BI->getSuccessor(CI->isZero()) == To; 729 } 730 731 // Unwinding instructions successors are always executable. 732 if (TI->isExceptional()) 733 return true; 734 735 if (auto *SI = dyn_cast<SwitchInst>(TI)) { 736 if (SI->getNumCases() < 1) 737 return true; 738 739 LatticeVal SCValue = getValueState(SI->getCondition()); 740 ConstantInt *CI = SCValue.getConstantInt(); 741 742 if (!CI) 743 return !SCValue.isUnknown(); 744 745 return SI->findCaseValue(CI)->getCaseSuccessor() == To; 746 } 747 748 // In case of indirect branch and its address is a blockaddress, we mark 749 // the target as executable. 750 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) { 751 LatticeVal IBRValue = getValueState(IBR->getAddress()); 752 BlockAddress *Addr = IBRValue.getBlockAddress(); 753 754 if (!Addr) 755 return !IBRValue.isUnknown(); 756 757 // At this point, the indirectbr is branching on a blockaddress. 758 return Addr->getBasicBlock() == To; 759 } 760 761 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n'); 762 llvm_unreachable("SCCP: Don't know how to handle this terminator!"); 763 } 764 765 // visit Implementations - Something changed in this instruction, either an 766 // operand made a transition, or the instruction is newly executable. Change 767 // the value type of I to reflect these changes if appropriate. This method 768 // makes sure to do the following actions: 769 // 770 // 1. If a phi node merges two constants in, and has conflicting value coming 771 // from different branches, or if the PHI node merges in an overdefined 772 // value, then the PHI node becomes overdefined. 773 // 2. If a phi node merges only constants in, and they all agree on value, the 774 // PHI node becomes a constant value equal to that. 775 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 776 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 777 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 778 // 6. If a conditional branch has a value that is constant, make the selected 779 // destination executable 780 // 7. If a conditional branch has a value that is overdefined, make all 781 // successors executable. 782 void SCCPSolver::visitPHINode(PHINode &PN) { 783 // If this PN returns a struct, just mark the result overdefined. 784 // TODO: We could do a lot better than this if code actually uses this. 785 if (PN.getType()->isStructTy()) 786 return markOverdefined(&PN); 787 788 if (getValueState(&PN).isOverdefined()) 789 return; // Quick exit 790 791 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, 792 // and slow us down a lot. Just mark them overdefined. 793 if (PN.getNumIncomingValues() > 64) 794 return markOverdefined(&PN); 795 796 // Look at all of the executable operands of the PHI node. If any of them 797 // are overdefined, the PHI becomes overdefined as well. If they are all 798 // constant, and they agree with each other, the PHI becomes the identical 799 // constant. If they are constant and don't agree, the PHI is overdefined. 800 // If there are no executable operands, the PHI remains unknown. 801 Constant *OperandVal = nullptr; 802 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 803 LatticeVal IV = getValueState(PN.getIncomingValue(i)); 804 if (IV.isUnknown()) continue; // Doesn't influence PHI node. 805 806 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) 807 continue; 808 809 if (IV.isOverdefined()) // PHI node becomes overdefined! 810 return markOverdefined(&PN); 811 812 if (!OperandVal) { // Grab the first value. 813 OperandVal = IV.getConstant(); 814 continue; 815 } 816 817 // There is already a reachable operand. If we conflict with it, 818 // then the PHI node becomes overdefined. If we agree with it, we 819 // can continue on. 820 821 // Check to see if there are two different constants merging, if so, the PHI 822 // node is overdefined. 823 if (IV.getConstant() != OperandVal) 824 return markOverdefined(&PN); 825 } 826 827 // If we exited the loop, this means that the PHI node only has constant 828 // arguments that agree with each other(and OperandVal is the constant) or 829 // OperandVal is null because there are no defined incoming arguments. If 830 // this is the case, the PHI remains unknown. 831 if (OperandVal) 832 markConstant(&PN, OperandVal); // Acquire operand value 833 } 834 835 void SCCPSolver::visitReturnInst(ReturnInst &I) { 836 if (I.getNumOperands() == 0) return; // ret void 837 838 Function *F = I.getParent()->getParent(); 839 Value *ResultOp = I.getOperand(0); 840 841 // If we are tracking the return value of this function, merge it in. 842 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) { 843 DenseMap<Function*, LatticeVal>::iterator TFRVI = 844 TrackedRetVals.find(F); 845 if (TFRVI != TrackedRetVals.end()) { 846 mergeInValue(TFRVI->second, F, getValueState(ResultOp)); 847 return; 848 } 849 } 850 851 // Handle functions that return multiple values. 852 if (!TrackedMultipleRetVals.empty()) { 853 if (auto *STy = dyn_cast<StructType>(ResultOp->getType())) 854 if (MRVFunctionsTracked.count(F)) 855 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 856 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F, 857 getStructValueState(ResultOp, i)); 858 } 859 } 860 861 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) { 862 SmallVector<bool, 16> SuccFeasible; 863 getFeasibleSuccessors(TI, SuccFeasible); 864 865 BasicBlock *BB = TI.getParent(); 866 867 // Mark all feasible successors executable. 868 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) 869 if (SuccFeasible[i]) 870 markEdgeExecutable(BB, TI.getSuccessor(i)); 871 } 872 873 void SCCPSolver::visitCastInst(CastInst &I) { 874 LatticeVal OpSt = getValueState(I.getOperand(0)); 875 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand 876 markOverdefined(&I); 877 else if (OpSt.isConstant()) { 878 // Fold the constant as we build. 879 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(), 880 I.getType(), DL); 881 if (isa<UndefValue>(C)) 882 return; 883 // Propagate constant value 884 markConstant(&I, C); 885 } 886 } 887 888 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) { 889 // If this returns a struct, mark all elements over defined, we don't track 890 // structs in structs. 891 if (EVI.getType()->isStructTy()) 892 return markOverdefined(&EVI); 893 894 // If this is extracting from more than one level of struct, we don't know. 895 if (EVI.getNumIndices() != 1) 896 return markOverdefined(&EVI); 897 898 Value *AggVal = EVI.getAggregateOperand(); 899 if (AggVal->getType()->isStructTy()) { 900 unsigned i = *EVI.idx_begin(); 901 LatticeVal EltVal = getStructValueState(AggVal, i); 902 mergeInValue(getValueState(&EVI), &EVI, EltVal); 903 } else { 904 // Otherwise, must be extracting from an array. 905 return markOverdefined(&EVI); 906 } 907 } 908 909 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) { 910 auto *STy = dyn_cast<StructType>(IVI.getType()); 911 if (!STy) 912 return markOverdefined(&IVI); 913 914 // If this has more than one index, we can't handle it, drive all results to 915 // undef. 916 if (IVI.getNumIndices() != 1) 917 return markOverdefined(&IVI); 918 919 Value *Aggr = IVI.getAggregateOperand(); 920 unsigned Idx = *IVI.idx_begin(); 921 922 // Compute the result based on what we're inserting. 923 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 924 // This passes through all values that aren't the inserted element. 925 if (i != Idx) { 926 LatticeVal EltVal = getStructValueState(Aggr, i); 927 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal); 928 continue; 929 } 930 931 Value *Val = IVI.getInsertedValueOperand(); 932 if (Val->getType()->isStructTy()) 933 // We don't track structs in structs. 934 markOverdefined(getStructValueState(&IVI, i), &IVI); 935 else { 936 LatticeVal InVal = getValueState(Val); 937 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal); 938 } 939 } 940 } 941 942 void SCCPSolver::visitSelectInst(SelectInst &I) { 943 // If this select returns a struct, just mark the result overdefined. 944 // TODO: We could do a lot better than this if code actually uses this. 945 if (I.getType()->isStructTy()) 946 return markOverdefined(&I); 947 948 LatticeVal CondValue = getValueState(I.getCondition()); 949 if (CondValue.isUnknown()) 950 return; 951 952 if (ConstantInt *CondCB = CondValue.getConstantInt()) { 953 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue(); 954 mergeInValue(&I, getValueState(OpVal)); 955 return; 956 } 957 958 // Otherwise, the condition is overdefined or a constant we can't evaluate. 959 // See if we can produce something better than overdefined based on the T/F 960 // value. 961 LatticeVal TVal = getValueState(I.getTrueValue()); 962 LatticeVal FVal = getValueState(I.getFalseValue()); 963 964 // select ?, C, C -> C. 965 if (TVal.isConstant() && FVal.isConstant() && 966 TVal.getConstant() == FVal.getConstant()) 967 return markConstant(&I, FVal.getConstant()); 968 969 if (TVal.isUnknown()) // select ?, undef, X -> X. 970 return mergeInValue(&I, FVal); 971 if (FVal.isUnknown()) // select ?, X, undef -> X. 972 return mergeInValue(&I, TVal); 973 markOverdefined(&I); 974 } 975 976 // Handle Binary Operators. 977 void SCCPSolver::visitBinaryOperator(Instruction &I) { 978 LatticeVal V1State = getValueState(I.getOperand(0)); 979 LatticeVal V2State = getValueState(I.getOperand(1)); 980 981 LatticeVal &IV = ValueState[&I]; 982 if (IV.isOverdefined()) return; 983 984 if (V1State.isConstant() && V2State.isConstant()) { 985 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(), 986 V2State.getConstant()); 987 // X op Y -> undef. 988 if (isa<UndefValue>(C)) 989 return; 990 return markConstant(IV, &I, C); 991 } 992 993 // If something is undef, wait for it to resolve. 994 if (!V1State.isOverdefined() && !V2State.isOverdefined()) 995 return; 996 997 // Otherwise, one of our operands is overdefined. Try to produce something 998 // better than overdefined with some tricks. 999 // If this is 0 / Y, it doesn't matter that the second operand is 1000 // overdefined, and we can replace it with zero. 1001 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv) 1002 if (V1State.isConstant() && V1State.getConstant()->isNullValue()) 1003 return markConstant(IV, &I, V1State.getConstant()); 1004 1005 // If this is: 1006 // -> AND/MUL with 0 1007 // -> OR with -1 1008 // it doesn't matter that the other operand is overdefined. 1009 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul || 1010 I.getOpcode() == Instruction::Or) { 1011 LatticeVal *NonOverdefVal = nullptr; 1012 if (!V1State.isOverdefined()) 1013 NonOverdefVal = &V1State; 1014 else if (!V2State.isOverdefined()) 1015 NonOverdefVal = &V2State; 1016 1017 if (NonOverdefVal) { 1018 if (NonOverdefVal->isUnknown()) 1019 return; 1020 1021 if (I.getOpcode() == Instruction::And || 1022 I.getOpcode() == Instruction::Mul) { 1023 // X and 0 = 0 1024 // X * 0 = 0 1025 if (NonOverdefVal->getConstant()->isNullValue()) 1026 return markConstant(IV, &I, NonOverdefVal->getConstant()); 1027 } else { 1028 // X or -1 = -1 1029 if (ConstantInt *CI = NonOverdefVal->getConstantInt()) 1030 if (CI->isMinusOne()) 1031 return markConstant(IV, &I, NonOverdefVal->getConstant()); 1032 } 1033 } 1034 } 1035 1036 markOverdefined(&I); 1037 } 1038 1039 // Handle ICmpInst instruction. 1040 void SCCPSolver::visitCmpInst(CmpInst &I) { 1041 LatticeVal V1State = getValueState(I.getOperand(0)); 1042 LatticeVal V2State = getValueState(I.getOperand(1)); 1043 1044 LatticeVal &IV = ValueState[&I]; 1045 if (IV.isOverdefined()) return; 1046 1047 if (V1State.isConstant() && V2State.isConstant()) { 1048 Constant *C = ConstantExpr::getCompare( 1049 I.getPredicate(), V1State.getConstant(), V2State.getConstant()); 1050 if (isa<UndefValue>(C)) 1051 return; 1052 return markConstant(IV, &I, C); 1053 } 1054 1055 // If operands are still unknown, wait for it to resolve. 1056 if (!V1State.isOverdefined() && !V2State.isOverdefined()) 1057 return; 1058 1059 markOverdefined(&I); 1060 } 1061 1062 // Handle getelementptr instructions. If all operands are constants then we 1063 // can turn this into a getelementptr ConstantExpr. 1064 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) { 1065 if (ValueState[&I].isOverdefined()) return; 1066 1067 SmallVector<Constant*, 8> Operands; 1068 Operands.reserve(I.getNumOperands()); 1069 1070 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 1071 LatticeVal State = getValueState(I.getOperand(i)); 1072 if (State.isUnknown()) 1073 return; // Operands are not resolved yet. 1074 1075 if (State.isOverdefined()) 1076 return markOverdefined(&I); 1077 1078 assert(State.isConstant() && "Unknown state!"); 1079 Operands.push_back(State.getConstant()); 1080 } 1081 1082 Constant *Ptr = Operands[0]; 1083 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end()); 1084 Constant *C = 1085 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices); 1086 if (isa<UndefValue>(C)) 1087 return; 1088 markConstant(&I, C); 1089 } 1090 1091 void SCCPSolver::visitStoreInst(StoreInst &SI) { 1092 // If this store is of a struct, ignore it. 1093 if (SI.getOperand(0)->getType()->isStructTy()) 1094 return; 1095 1096 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1))) 1097 return; 1098 1099 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1)); 1100 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV); 1101 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return; 1102 1103 // Get the value we are storing into the global, then merge it. 1104 mergeInValue(I->second, GV, getValueState(SI.getOperand(0))); 1105 if (I->second.isOverdefined()) 1106 TrackedGlobals.erase(I); // No need to keep tracking this! 1107 } 1108 1109 // Handle load instructions. If the operand is a constant pointer to a constant 1110 // global, we can replace the load with the loaded constant value! 1111 void SCCPSolver::visitLoadInst(LoadInst &I) { 1112 // If this load is of a struct, just mark the result overdefined. 1113 if (I.getType()->isStructTy()) 1114 return markOverdefined(&I); 1115 1116 LatticeVal PtrVal = getValueState(I.getOperand(0)); 1117 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet! 1118 1119 LatticeVal &IV = ValueState[&I]; 1120 if (IV.isOverdefined()) return; 1121 1122 if (!PtrVal.isConstant() || I.isVolatile()) 1123 return markOverdefined(IV, &I); 1124 1125 Constant *Ptr = PtrVal.getConstant(); 1126 1127 // load null is undefined. 1128 if (isa<ConstantPointerNull>(Ptr)) { 1129 if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace())) 1130 return (void)markOverdefined(IV, &I); 1131 else 1132 return; 1133 } 1134 1135 // Transform load (constant global) into the value loaded. 1136 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) { 1137 if (!TrackedGlobals.empty()) { 1138 // If we are tracking this global, merge in the known value for it. 1139 DenseMap<GlobalVariable*, LatticeVal>::iterator It = 1140 TrackedGlobals.find(GV); 1141 if (It != TrackedGlobals.end()) { 1142 mergeInValue(IV, &I, It->second); 1143 return; 1144 } 1145 } 1146 } 1147 1148 // Transform load from a constant into a constant if possible. 1149 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) { 1150 if (isa<UndefValue>(C)) 1151 return; 1152 return markConstant(IV, &I, C); 1153 } 1154 1155 // Otherwise we cannot say for certain what value this load will produce. 1156 // Bail out. 1157 markOverdefined(IV, &I); 1158 } 1159 1160 void SCCPSolver::visitCallSite(CallSite CS) { 1161 Function *F = CS.getCalledFunction(); 1162 Instruction *I = CS.getInstruction(); 1163 1164 // The common case is that we aren't tracking the callee, either because we 1165 // are not doing interprocedural analysis or the callee is indirect, or is 1166 // external. Handle these cases first. 1167 if (!F || F->isDeclaration()) { 1168 CallOverdefined: 1169 // Void return and not tracking callee, just bail. 1170 if (I->getType()->isVoidTy()) return; 1171 1172 // Otherwise, if we have a single return value case, and if the function is 1173 // a declaration, maybe we can constant fold it. 1174 if (F && F->isDeclaration() && !I->getType()->isStructTy() && 1175 canConstantFoldCallTo(CS, F)) { 1176 SmallVector<Constant*, 8> Operands; 1177 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); 1178 AI != E; ++AI) { 1179 LatticeVal State = getValueState(*AI); 1180 1181 if (State.isUnknown()) 1182 return; // Operands are not resolved yet. 1183 if (State.isOverdefined()) 1184 return markOverdefined(I); 1185 assert(State.isConstant() && "Unknown state!"); 1186 Operands.push_back(State.getConstant()); 1187 } 1188 1189 if (getValueState(I).isOverdefined()) 1190 return; 1191 1192 // If we can constant fold this, mark the result of the call as a 1193 // constant. 1194 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) { 1195 // call -> undef. 1196 if (isa<UndefValue>(C)) 1197 return; 1198 return markConstant(I, C); 1199 } 1200 } 1201 1202 // Otherwise, we don't know anything about this call, mark it overdefined. 1203 return markOverdefined(I); 1204 } 1205 1206 // If this is a local function that doesn't have its address taken, mark its 1207 // entry block executable and merge in the actual arguments to the call into 1208 // the formal arguments of the function. 1209 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){ 1210 MarkBlockExecutable(&F->front()); 1211 1212 // Propagate information from this call site into the callee. 1213 CallSite::arg_iterator CAI = CS.arg_begin(); 1214 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1215 AI != E; ++AI, ++CAI) { 1216 // If this argument is byval, and if the function is not readonly, there 1217 // will be an implicit copy formed of the input aggregate. 1218 if (AI->hasByValAttr() && !F->onlyReadsMemory()) { 1219 markOverdefined(&*AI); 1220 continue; 1221 } 1222 1223 if (auto *STy = dyn_cast<StructType>(AI->getType())) { 1224 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1225 LatticeVal CallArg = getStructValueState(*CAI, i); 1226 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg); 1227 } 1228 } else { 1229 // Most other parts of the Solver still only use the simpler value 1230 // lattice, so we propagate changes for parameters to both lattices. 1231 getParamState(&*AI).mergeIn(getValueState(*CAI).toValueLattice(), DL); 1232 mergeInValue(&*AI, getValueState(*CAI)); 1233 } 1234 } 1235 } 1236 1237 // If this is a single/zero retval case, see if we're tracking the function. 1238 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) { 1239 if (!MRVFunctionsTracked.count(F)) 1240 goto CallOverdefined; // Not tracking this callee. 1241 1242 // If we are tracking this callee, propagate the result of the function 1243 // into this call site. 1244 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1245 mergeInValue(getStructValueState(I, i), I, 1246 TrackedMultipleRetVals[std::make_pair(F, i)]); 1247 } else { 1248 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F); 1249 if (TFRVI == TrackedRetVals.end()) 1250 goto CallOverdefined; // Not tracking this callee. 1251 1252 // If so, propagate the return value of the callee into this call result. 1253 mergeInValue(I, TFRVI->second); 1254 } 1255 } 1256 1257 void SCCPSolver::Solve() { 1258 // Process the work lists until they are empty! 1259 while (!BBWorkList.empty() || !InstWorkList.empty() || 1260 !OverdefinedInstWorkList.empty()) { 1261 // Process the overdefined instruction's work list first, which drives other 1262 // things to overdefined more quickly. 1263 while (!OverdefinedInstWorkList.empty()) { 1264 Value *I = OverdefinedInstWorkList.pop_back_val(); 1265 1266 LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n'); 1267 1268 // "I" got into the work list because it either made the transition from 1269 // bottom to constant, or to overdefined. 1270 // 1271 // Anything on this worklist that is overdefined need not be visited 1272 // since all of its users will have already been marked as overdefined 1273 // Update all of the users of this instruction's value. 1274 // 1275 for (User *U : I->users()) 1276 if (auto *UI = dyn_cast<Instruction>(U)) 1277 OperandChangedState(UI); 1278 } 1279 1280 // Process the instruction work list. 1281 while (!InstWorkList.empty()) { 1282 Value *I = InstWorkList.pop_back_val(); 1283 1284 LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n'); 1285 1286 // "I" got into the work list because it made the transition from undef to 1287 // constant. 1288 // 1289 // Anything on this worklist that is overdefined need not be visited 1290 // since all of its users will have already been marked as overdefined. 1291 // Update all of the users of this instruction's value. 1292 // 1293 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined()) 1294 for (User *U : I->users()) 1295 if (auto *UI = dyn_cast<Instruction>(U)) 1296 OperandChangedState(UI); 1297 } 1298 1299 // Process the basic block work list. 1300 while (!BBWorkList.empty()) { 1301 BasicBlock *BB = BBWorkList.back(); 1302 BBWorkList.pop_back(); 1303 1304 LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n'); 1305 1306 // Notify all instructions in this basic block that they are newly 1307 // executable. 1308 visit(BB); 1309 } 1310 } 1311 } 1312 1313 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 1314 /// that branches on undef values cannot reach any of their successors. 1315 /// However, this is not a safe assumption. After we solve dataflow, this 1316 /// method should be use to handle this. If this returns true, the solver 1317 /// should be rerun. 1318 /// 1319 /// This method handles this by finding an unresolved branch and marking it one 1320 /// of the edges from the block as being feasible, even though the condition 1321 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the 1322 /// CFG and only slightly pessimizes the analysis results (by marking one, 1323 /// potentially infeasible, edge feasible). This cannot usefully modify the 1324 /// constraints on the condition of the branch, as that would impact other users 1325 /// of the value. 1326 /// 1327 /// This scan also checks for values that use undefs, whose results are actually 1328 /// defined. For example, 'zext i8 undef to i32' should produce all zeros 1329 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero, 1330 /// even if X isn't defined. 1331 bool SCCPSolver::ResolvedUndefsIn(Function &F) { 1332 for (BasicBlock &BB : F) { 1333 if (!BBExecutable.count(&BB)) 1334 continue; 1335 1336 for (Instruction &I : BB) { 1337 // Look for instructions which produce undef values. 1338 if (I.getType()->isVoidTy()) continue; 1339 1340 if (auto *STy = dyn_cast<StructType>(I.getType())) { 1341 // Only a few things that can be structs matter for undef. 1342 1343 // Tracked calls must never be marked overdefined in ResolvedUndefsIn. 1344 if (CallSite CS = CallSite(&I)) 1345 if (Function *F = CS.getCalledFunction()) 1346 if (MRVFunctionsTracked.count(F)) 1347 continue; 1348 1349 // extractvalue and insertvalue don't need to be marked; they are 1350 // tracked as precisely as their operands. 1351 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I)) 1352 continue; 1353 1354 // Send the results of everything else to overdefined. We could be 1355 // more precise than this but it isn't worth bothering. 1356 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1357 LatticeVal &LV = getStructValueState(&I, i); 1358 if (LV.isUnknown()) 1359 markOverdefined(LV, &I); 1360 } 1361 continue; 1362 } 1363 1364 LatticeVal &LV = getValueState(&I); 1365 if (!LV.isUnknown()) continue; 1366 1367 // extractvalue is safe; check here because the argument is a struct. 1368 if (isa<ExtractValueInst>(I)) 1369 continue; 1370 1371 // Compute the operand LatticeVals, for convenience below. 1372 // Anything taking a struct is conservatively assumed to require 1373 // overdefined markings. 1374 if (I.getOperand(0)->getType()->isStructTy()) { 1375 markOverdefined(&I); 1376 return true; 1377 } 1378 LatticeVal Op0LV = getValueState(I.getOperand(0)); 1379 LatticeVal Op1LV; 1380 if (I.getNumOperands() == 2) { 1381 if (I.getOperand(1)->getType()->isStructTy()) { 1382 markOverdefined(&I); 1383 return true; 1384 } 1385 1386 Op1LV = getValueState(I.getOperand(1)); 1387 } 1388 // If this is an instructions whose result is defined even if the input is 1389 // not fully defined, propagate the information. 1390 Type *ITy = I.getType(); 1391 switch (I.getOpcode()) { 1392 case Instruction::Add: 1393 case Instruction::Sub: 1394 case Instruction::Trunc: 1395 case Instruction::FPTrunc: 1396 case Instruction::BitCast: 1397 break; // Any undef -> undef 1398 case Instruction::FSub: 1399 case Instruction::FAdd: 1400 case Instruction::FMul: 1401 case Instruction::FDiv: 1402 case Instruction::FRem: 1403 // Floating-point binary operation: be conservative. 1404 if (Op0LV.isUnknown() && Op1LV.isUnknown()) 1405 markForcedConstant(&I, Constant::getNullValue(ITy)); 1406 else 1407 markOverdefined(&I); 1408 return true; 1409 case Instruction::ZExt: 1410 case Instruction::SExt: 1411 case Instruction::FPToUI: 1412 case Instruction::FPToSI: 1413 case Instruction::FPExt: 1414 case Instruction::PtrToInt: 1415 case Instruction::IntToPtr: 1416 case Instruction::SIToFP: 1417 case Instruction::UIToFP: 1418 // undef -> 0; some outputs are impossible 1419 markForcedConstant(&I, Constant::getNullValue(ITy)); 1420 return true; 1421 case Instruction::Mul: 1422 case Instruction::And: 1423 // Both operands undef -> undef 1424 if (Op0LV.isUnknown() && Op1LV.isUnknown()) 1425 break; 1426 // undef * X -> 0. X could be zero. 1427 // undef & X -> 0. X could be zero. 1428 markForcedConstant(&I, Constant::getNullValue(ITy)); 1429 return true; 1430 case Instruction::Or: 1431 // Both operands undef -> undef 1432 if (Op0LV.isUnknown() && Op1LV.isUnknown()) 1433 break; 1434 // undef | X -> -1. X could be -1. 1435 markForcedConstant(&I, Constant::getAllOnesValue(ITy)); 1436 return true; 1437 case Instruction::Xor: 1438 // undef ^ undef -> 0; strictly speaking, this is not strictly 1439 // necessary, but we try to be nice to people who expect this 1440 // behavior in simple cases 1441 if (Op0LV.isUnknown() && Op1LV.isUnknown()) { 1442 markForcedConstant(&I, Constant::getNullValue(ITy)); 1443 return true; 1444 } 1445 // undef ^ X -> undef 1446 break; 1447 case Instruction::SDiv: 1448 case Instruction::UDiv: 1449 case Instruction::SRem: 1450 case Instruction::URem: 1451 // X / undef -> undef. No change. 1452 // X % undef -> undef. No change. 1453 if (Op1LV.isUnknown()) break; 1454 1455 // X / 0 -> undef. No change. 1456 // X % 0 -> undef. No change. 1457 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue()) 1458 break; 1459 1460 // undef / X -> 0. X could be maxint. 1461 // undef % X -> 0. X could be 1. 1462 markForcedConstant(&I, Constant::getNullValue(ITy)); 1463 return true; 1464 case Instruction::AShr: 1465 // X >>a undef -> undef. 1466 if (Op1LV.isUnknown()) break; 1467 1468 // Shifting by the bitwidth or more is undefined. 1469 if (Op1LV.isConstant()) { 1470 if (auto *ShiftAmt = Op1LV.getConstantInt()) 1471 if (ShiftAmt->getLimitedValue() >= 1472 ShiftAmt->getType()->getScalarSizeInBits()) 1473 break; 1474 } 1475 1476 // undef >>a X -> 0 1477 markForcedConstant(&I, Constant::getNullValue(ITy)); 1478 return true; 1479 case Instruction::LShr: 1480 case Instruction::Shl: 1481 // X << undef -> undef. 1482 // X >> undef -> undef. 1483 if (Op1LV.isUnknown()) break; 1484 1485 // Shifting by the bitwidth or more is undefined. 1486 if (Op1LV.isConstant()) { 1487 if (auto *ShiftAmt = Op1LV.getConstantInt()) 1488 if (ShiftAmt->getLimitedValue() >= 1489 ShiftAmt->getType()->getScalarSizeInBits()) 1490 break; 1491 } 1492 1493 // undef << X -> 0 1494 // undef >> X -> 0 1495 markForcedConstant(&I, Constant::getNullValue(ITy)); 1496 return true; 1497 case Instruction::Select: 1498 Op1LV = getValueState(I.getOperand(1)); 1499 // undef ? X : Y -> X or Y. There could be commonality between X/Y. 1500 if (Op0LV.isUnknown()) { 1501 if (!Op1LV.isConstant()) // Pick the constant one if there is any. 1502 Op1LV = getValueState(I.getOperand(2)); 1503 } else if (Op1LV.isUnknown()) { 1504 // c ? undef : undef -> undef. No change. 1505 Op1LV = getValueState(I.getOperand(2)); 1506 if (Op1LV.isUnknown()) 1507 break; 1508 // Otherwise, c ? undef : x -> x. 1509 } else { 1510 // Leave Op1LV as Operand(1)'s LatticeValue. 1511 } 1512 1513 if (Op1LV.isConstant()) 1514 markForcedConstant(&I, Op1LV.getConstant()); 1515 else 1516 markOverdefined(&I); 1517 return true; 1518 case Instruction::Load: 1519 // A load here means one of two things: a load of undef from a global, 1520 // a load from an unknown pointer. Either way, having it return undef 1521 // is okay. 1522 break; 1523 case Instruction::ICmp: 1524 // X == undef -> undef. Other comparisons get more complicated. 1525 if (cast<ICmpInst>(&I)->isEquality()) 1526 break; 1527 markOverdefined(&I); 1528 return true; 1529 case Instruction::Call: 1530 case Instruction::Invoke: 1531 // There are two reasons a call can have an undef result 1532 // 1. It could be tracked. 1533 // 2. It could be constant-foldable. 1534 // Because of the way we solve return values, tracked calls must 1535 // never be marked overdefined in ResolvedUndefsIn. 1536 if (Function *F = CallSite(&I).getCalledFunction()) 1537 if (TrackedRetVals.count(F)) 1538 break; 1539 1540 // If the call is constant-foldable, we mark it overdefined because 1541 // we do not know what return values are valid. 1542 markOverdefined(&I); 1543 return true; 1544 default: 1545 // If we don't know what should happen here, conservatively mark it 1546 // overdefined. 1547 markOverdefined(&I); 1548 return true; 1549 } 1550 } 1551 1552 // Check to see if we have a branch or switch on an undefined value. If so 1553 // we force the branch to go one way or the other to make the successor 1554 // values live. It doesn't really matter which way we force it. 1555 TerminatorInst *TI = BB.getTerminator(); 1556 if (auto *BI = dyn_cast<BranchInst>(TI)) { 1557 if (!BI->isConditional()) continue; 1558 if (!getValueState(BI->getCondition()).isUnknown()) 1559 continue; 1560 1561 // If the input to SCCP is actually branch on undef, fix the undef to 1562 // false. 1563 if (isa<UndefValue>(BI->getCondition())) { 1564 BI->setCondition(ConstantInt::getFalse(BI->getContext())); 1565 markEdgeExecutable(&BB, TI->getSuccessor(1)); 1566 return true; 1567 } 1568 1569 // Otherwise, it is a branch on a symbolic value which is currently 1570 // considered to be undef. Handle this by forcing the input value to the 1571 // branch to false. 1572 markForcedConstant(BI->getCondition(), 1573 ConstantInt::getFalse(TI->getContext())); 1574 return true; 1575 } 1576 1577 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) { 1578 // Indirect branch with no successor ?. Its ok to assume it branches 1579 // to no target. 1580 if (IBR->getNumSuccessors() < 1) 1581 continue; 1582 1583 if (!getValueState(IBR->getAddress()).isUnknown()) 1584 continue; 1585 1586 // If the input to SCCP is actually branch on undef, fix the undef to 1587 // the first successor of the indirect branch. 1588 if (isa<UndefValue>(IBR->getAddress())) { 1589 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0))); 1590 markEdgeExecutable(&BB, IBR->getSuccessor(0)); 1591 return true; 1592 } 1593 1594 // Otherwise, it is a branch on a symbolic value which is currently 1595 // considered to be undef. Handle this by forcing the input value to the 1596 // branch to the first successor. 1597 markForcedConstant(IBR->getAddress(), 1598 BlockAddress::get(IBR->getSuccessor(0))); 1599 return true; 1600 } 1601 1602 if (auto *SI = dyn_cast<SwitchInst>(TI)) { 1603 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown()) 1604 continue; 1605 1606 // If the input to SCCP is actually switch on undef, fix the undef to 1607 // the first constant. 1608 if (isa<UndefValue>(SI->getCondition())) { 1609 SI->setCondition(SI->case_begin()->getCaseValue()); 1610 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor()); 1611 return true; 1612 } 1613 1614 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue()); 1615 return true; 1616 } 1617 } 1618 1619 return false; 1620 } 1621 1622 static bool tryToReplaceWithConstantRange(SCCPSolver &Solver, Value *V) { 1623 bool Changed = false; 1624 1625 // Currently we only use range information for integer values. 1626 if (!V->getType()->isIntegerTy()) 1627 return false; 1628 1629 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V); 1630 if (!IV.isConstantRange()) 1631 return false; 1632 1633 for (auto UI = V->uses().begin(), E = V->uses().end(); UI != E;) { 1634 const Use &U = *UI++; 1635 auto *Icmp = dyn_cast<ICmpInst>(U.getUser()); 1636 if (!Icmp || !Solver.isBlockExecutable(Icmp->getParent())) 1637 continue; 1638 1639 auto getIcmpLatticeValue = [&](Value *Op) { 1640 if (auto *C = dyn_cast<Constant>(Op)) 1641 return ValueLatticeElement::get(C); 1642 return Solver.getLatticeValueFor(Op); 1643 }; 1644 1645 ValueLatticeElement A = getIcmpLatticeValue(Icmp->getOperand(0)); 1646 ValueLatticeElement B = getIcmpLatticeValue(Icmp->getOperand(1)); 1647 1648 Constant *C = A.getCompare(Icmp->getPredicate(), Icmp->getType(), B); 1649 if (C) { 1650 Icmp->replaceAllUsesWith(C); 1651 LLVM_DEBUG(dbgs() << "Replacing " << *Icmp << " with " << *C 1652 << ", because of range information " << A << " " << B 1653 << "\n"); 1654 Icmp->eraseFromParent(); 1655 Changed = true; 1656 } 1657 } 1658 return Changed; 1659 } 1660 1661 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) { 1662 Constant *Const = nullptr; 1663 if (V->getType()->isStructTy()) { 1664 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V); 1665 if (llvm::any_of(IVs, 1666 [](const LatticeVal &LV) { return LV.isOverdefined(); })) 1667 return false; 1668 std::vector<Constant *> ConstVals; 1669 auto *ST = dyn_cast<StructType>(V->getType()); 1670 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) { 1671 LatticeVal V = IVs[i]; 1672 ConstVals.push_back(V.isConstant() 1673 ? V.getConstant() 1674 : UndefValue::get(ST->getElementType(i))); 1675 } 1676 Const = ConstantStruct::get(ST, ConstVals); 1677 } else { 1678 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V); 1679 if (IV.isOverdefined()) 1680 return false; 1681 1682 if (IV.isConstantRange()) { 1683 if (IV.getConstantRange().isSingleElement()) 1684 Const = 1685 ConstantInt::get(V->getType(), IV.asConstantInteger().getValue()); 1686 else 1687 return false; 1688 } else 1689 Const = 1690 IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType()); 1691 } 1692 assert(Const && "Constant is nullptr here!"); 1693 1694 // Replacing `musttail` instructions with constant breaks `musttail` invariant 1695 // unless the call itself can be removed 1696 CallInst *CI = dyn_cast<CallInst>(V); 1697 if (CI && CI->isMustTailCall() && !CI->isSafeToRemove()) { 1698 CallSite CS(CI); 1699 Function *F = CS.getCalledFunction(); 1700 1701 // Don't zap returns of the callee 1702 if (F) 1703 Solver.AddMustTailCallee(F); 1704 1705 LLVM_DEBUG(dbgs() << " Can\'t treat the result of musttail call : " << *CI 1706 << " as a constant\n"); 1707 return false; 1708 } 1709 1710 LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n'); 1711 1712 // Replaces all of the uses of a variable with uses of the constant. 1713 V->replaceAllUsesWith(Const); 1714 return true; 1715 } 1716 1717 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm, 1718 // and return true if the function was modified. 1719 static bool runSCCP(Function &F, const DataLayout &DL, 1720 const TargetLibraryInfo *TLI) { 1721 LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n"); 1722 SCCPSolver Solver(DL, TLI); 1723 1724 // Mark the first block of the function as being executable. 1725 Solver.MarkBlockExecutable(&F.front()); 1726 1727 // Mark all arguments to the function as being overdefined. 1728 for (Argument &AI : F.args()) 1729 Solver.markOverdefined(&AI); 1730 1731 // Solve for constants. 1732 bool ResolvedUndefs = true; 1733 while (ResolvedUndefs) { 1734 Solver.Solve(); 1735 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n"); 1736 ResolvedUndefs = Solver.ResolvedUndefsIn(F); 1737 } 1738 1739 bool MadeChanges = false; 1740 1741 // If we decided that there are basic blocks that are dead in this function, 1742 // delete their contents now. Note that we cannot actually delete the blocks, 1743 // as we cannot modify the CFG of the function. 1744 1745 for (BasicBlock &BB : F) { 1746 if (!Solver.isBlockExecutable(&BB)) { 1747 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << BB); 1748 1749 ++NumDeadBlocks; 1750 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB); 1751 1752 MadeChanges = true; 1753 continue; 1754 } 1755 1756 // Iterate over all of the instructions in a function, replacing them with 1757 // constants if we have found them to be of constant values. 1758 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) { 1759 Instruction *Inst = &*BI++; 1760 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst)) 1761 continue; 1762 1763 if (tryToReplaceWithConstant(Solver, Inst)) { 1764 if (isInstructionTriviallyDead(Inst)) 1765 Inst->eraseFromParent(); 1766 // Hey, we just changed something! 1767 MadeChanges = true; 1768 ++NumInstRemoved; 1769 } 1770 } 1771 } 1772 1773 return MadeChanges; 1774 } 1775 1776 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) { 1777 const DataLayout &DL = F.getParent()->getDataLayout(); 1778 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1779 if (!runSCCP(F, DL, &TLI)) 1780 return PreservedAnalyses::all(); 1781 1782 auto PA = PreservedAnalyses(); 1783 PA.preserve<GlobalsAA>(); 1784 PA.preserveSet<CFGAnalyses>(); 1785 return PA; 1786 } 1787 1788 namespace { 1789 1790 //===--------------------------------------------------------------------===// 1791 // 1792 /// SCCP Class - This class uses the SCCPSolver to implement a per-function 1793 /// Sparse Conditional Constant Propagator. 1794 /// 1795 class SCCPLegacyPass : public FunctionPass { 1796 public: 1797 // Pass identification, replacement for typeid 1798 static char ID; 1799 1800 SCCPLegacyPass() : FunctionPass(ID) { 1801 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry()); 1802 } 1803 1804 void getAnalysisUsage(AnalysisUsage &AU) const override { 1805 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1806 AU.addPreserved<GlobalsAAWrapperPass>(); 1807 AU.setPreservesCFG(); 1808 } 1809 1810 // runOnFunction - Run the Sparse Conditional Constant Propagation 1811 // algorithm, and return true if the function was modified. 1812 bool runOnFunction(Function &F) override { 1813 if (skipFunction(F)) 1814 return false; 1815 const DataLayout &DL = F.getParent()->getDataLayout(); 1816 const TargetLibraryInfo *TLI = 1817 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1818 return runSCCP(F, DL, TLI); 1819 } 1820 }; 1821 1822 } // end anonymous namespace 1823 1824 char SCCPLegacyPass::ID = 0; 1825 1826 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp", 1827 "Sparse Conditional Constant Propagation", false, false) 1828 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1829 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp", 1830 "Sparse Conditional Constant Propagation", false, false) 1831 1832 // createSCCPPass - This is the public interface to this file. 1833 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); } 1834 1835 static void findReturnsToZap(Function &F, 1836 SmallVector<ReturnInst *, 8> &ReturnsToZap, 1837 SCCPSolver &Solver) { 1838 // We can only do this if we know that nothing else can call the function. 1839 if (!Solver.isArgumentTrackedFunction(&F)) 1840 return; 1841 1842 // There is a non-removable musttail call site of this function. Zapping 1843 // returns is not allowed. 1844 if (Solver.isMustTailCallee(&F)) { 1845 LLVM_DEBUG(dbgs() << "Can't zap returns of the function : " << F.getName() 1846 << " due to present musttail call of it\n"); 1847 return; 1848 } 1849 1850 for (BasicBlock &BB : F) { 1851 if (CallInst *CI = BB.getTerminatingMustTailCall()) { 1852 LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present " 1853 << "musttail call : " << *CI << "\n"); 1854 (void)CI; 1855 return; 1856 } 1857 1858 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) 1859 if (!isa<UndefValue>(RI->getOperand(0))) 1860 ReturnsToZap.push_back(RI); 1861 } 1862 } 1863 1864 bool llvm::runIPSCCP(Module &M, const DataLayout &DL, 1865 const TargetLibraryInfo *TLI) { 1866 SCCPSolver Solver(DL, TLI); 1867 1868 // Loop over all functions, marking arguments to those with their addresses 1869 // taken or that are external as overdefined. 1870 for (Function &F : M) { 1871 if (F.isDeclaration()) 1872 continue; 1873 1874 // Determine if we can track the function's return values. If so, add the 1875 // function to the solver's set of return-tracked functions. 1876 if (canTrackReturnsInterprocedurally(&F)) 1877 Solver.AddTrackedFunction(&F); 1878 1879 // Determine if we can track the function's arguments. If so, add the 1880 // function to the solver's set of argument-tracked functions. 1881 if (canTrackArgumentsInterprocedurally(&F)) { 1882 Solver.AddArgumentTrackedFunction(&F); 1883 continue; 1884 } 1885 1886 // Assume the function is called. 1887 Solver.MarkBlockExecutable(&F.front()); 1888 1889 // Assume nothing about the incoming arguments. 1890 for (Argument &AI : F.args()) 1891 Solver.markOverdefined(&AI); 1892 } 1893 1894 // Determine if we can track any of the module's global variables. If so, add 1895 // the global variables we can track to the solver's set of tracked global 1896 // variables. 1897 for (GlobalVariable &G : M.globals()) { 1898 G.removeDeadConstantUsers(); 1899 if (canTrackGlobalVariableInterprocedurally(&G)) 1900 Solver.TrackValueOfGlobalVariable(&G); 1901 } 1902 1903 // Solve for constants. 1904 bool ResolvedUndefs = true; 1905 Solver.Solve(); 1906 while (ResolvedUndefs) { 1907 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n"); 1908 ResolvedUndefs = false; 1909 for (Function &F : M) 1910 if (Solver.ResolvedUndefsIn(F)) { 1911 // We run Solve() after we resolved an undef in a function, because 1912 // we might deduce a fact that eliminates an undef in another function. 1913 Solver.Solve(); 1914 ResolvedUndefs = true; 1915 } 1916 } 1917 1918 bool MadeChanges = false; 1919 1920 // Iterate over all of the instructions in the module, replacing them with 1921 // constants if we have found them to be of constant values. 1922 SmallVector<BasicBlock*, 512> BlocksToErase; 1923 1924 for (Function &F : M) { 1925 if (F.isDeclaration()) 1926 continue; 1927 1928 if (Solver.isBlockExecutable(&F.front())) 1929 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; 1930 ++AI) { 1931 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) { 1932 ++IPNumArgsElimed; 1933 continue; 1934 } 1935 1936 if (!AI->use_empty() && tryToReplaceWithConstantRange(Solver, &*AI)) 1937 ++IPNumRangeInfoUsed; 1938 } 1939 1940 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 1941 if (!Solver.isBlockExecutable(&*BB)) { 1942 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB); 1943 ++NumDeadBlocks; 1944 1945 MadeChanges = true; 1946 1947 if (&*BB != &F.front()) 1948 BlocksToErase.push_back(&*BB); 1949 continue; 1950 } 1951 1952 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1953 Instruction *Inst = &*BI++; 1954 if (Inst->getType()->isVoidTy()) 1955 continue; 1956 if (tryToReplaceWithConstant(Solver, Inst)) { 1957 if (Inst->isSafeToRemove()) 1958 Inst->eraseFromParent(); 1959 // Hey, we just changed something! 1960 MadeChanges = true; 1961 ++IPNumInstRemoved; 1962 } 1963 } 1964 } 1965 1966 // Change dead blocks to unreachable. We do it after replacing constants in 1967 // all executable blocks, because changeToUnreachable may remove PHI nodes 1968 // in executable blocks we found values for. The function's entry block is 1969 // not part of BlocksToErase, so we have to handle it separately. 1970 for (BasicBlock *BB : BlocksToErase) 1971 NumInstRemoved += 1972 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false); 1973 if (!Solver.isBlockExecutable(&F.front())) 1974 NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(), 1975 /*UseLLVMTrap=*/false); 1976 1977 // Now that all instructions in the function are constant folded, erase dead 1978 // blocks, because we can now use ConstantFoldTerminator to get rid of 1979 // in-edges. 1980 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) { 1981 // If there are any PHI nodes in this successor, drop entries for BB now. 1982 BasicBlock *DeadBB = BlocksToErase[i]; 1983 for (Value::user_iterator UI = DeadBB->user_begin(), 1984 UE = DeadBB->user_end(); 1985 UI != UE;) { 1986 // Grab the user and then increment the iterator early, as the user 1987 // will be deleted. Step past all adjacent uses from the same user. 1988 auto *I = dyn_cast<Instruction>(*UI); 1989 do { ++UI; } while (UI != UE && *UI == I); 1990 1991 // Ignore blockaddress users; BasicBlock's dtor will handle them. 1992 if (!I) continue; 1993 1994 bool Folded = ConstantFoldTerminator(I->getParent()); 1995 assert(Folded && 1996 "Expect TermInst on constantint or blockaddress to be folded"); 1997 (void) Folded; 1998 } 1999 2000 // Finally, delete the basic block. 2001 F.getBasicBlockList().erase(DeadBB); 2002 } 2003 BlocksToErase.clear(); 2004 } 2005 2006 // If we inferred constant or undef return values for a function, we replaced 2007 // all call uses with the inferred value. This means we don't need to bother 2008 // actually returning anything from the function. Replace all return 2009 // instructions with return undef. 2010 // 2011 // Do this in two stages: first identify the functions we should process, then 2012 // actually zap their returns. This is important because we can only do this 2013 // if the address of the function isn't taken. In cases where a return is the 2014 // last use of a function, the order of processing functions would affect 2015 // whether other functions are optimizable. 2016 SmallVector<ReturnInst*, 8> ReturnsToZap; 2017 2018 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals(); 2019 for (const auto &I : RV) { 2020 Function *F = I.first; 2021 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy()) 2022 continue; 2023 findReturnsToZap(*F, ReturnsToZap, Solver); 2024 } 2025 2026 for (const auto &F : Solver.getMRVFunctionsTracked()) { 2027 assert(F->getReturnType()->isStructTy() && 2028 "The return type should be a struct"); 2029 StructType *STy = cast<StructType>(F->getReturnType()); 2030 if (Solver.isStructLatticeConstant(F, STy)) 2031 findReturnsToZap(*F, ReturnsToZap, Solver); 2032 } 2033 2034 // Zap all returns which we've identified as zap to change. 2035 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) { 2036 Function *F = ReturnsToZap[i]->getParent()->getParent(); 2037 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType())); 2038 } 2039 2040 // If we inferred constant or undef values for globals variables, we can 2041 // delete the global and any stores that remain to it. 2042 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals(); 2043 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(), 2044 E = TG.end(); I != E; ++I) { 2045 GlobalVariable *GV = I->first; 2046 assert(!I->second.isOverdefined() && 2047 "Overdefined values should have been taken out of the map!"); 2048 LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName() 2049 << "' is constant!\n"); 2050 while (!GV->use_empty()) { 2051 StoreInst *SI = cast<StoreInst>(GV->user_back()); 2052 SI->eraseFromParent(); 2053 } 2054 M.getGlobalList().erase(GV); 2055 ++IPNumGlobalConst; 2056 } 2057 2058 return MadeChanges; 2059 } 2060