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