xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Transforms/Scalar/SCCP.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
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/SetVector.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/ConstantFolding.h"
31 #include "llvm/Analysis/DomTreeUpdater.h"
32 #include "llvm/Analysis/GlobalsModRef.h"
33 #include "llvm/Analysis/InstructionSimplify.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueLattice.h"
36 #include "llvm/Analysis/ValueLatticeUtils.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/InstVisitor.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/PassManager.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/User.h"
53 #include "llvm/IR/Value.h"
54 #include "llvm/InitializePasses.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Scalar.h"
61 #include "llvm/Transforms/Utils/Local.h"
62 #include "llvm/Transforms/Utils/PredicateInfo.h"
63 #include <cassert>
64 #include <utility>
65 #include <vector>
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "sccp"
70 
71 STATISTIC(NumInstRemoved, "Number of instructions removed");
72 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
73 STATISTIC(NumInstReplaced,
74           "Number of instructions replaced with (simpler) instruction");
75 
76 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
77 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
78 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
79 STATISTIC(
80     IPNumInstReplaced,
81     "Number of instructions replaced with (simpler) instruction by IPSCCP");
82 
83 // Helper to check if \p LV is either a constant or a constant
84 // range with a single element. This should cover exactly the same cases as the
85 // old ValueLatticeElement::isConstant() and is intended to be used in the
86 // transition to ValueLatticeElement.
isConstant(const ValueLatticeElement & LV)87 static bool isConstant(const ValueLatticeElement &LV) {
88   return LV.isConstant() ||
89          (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
90 }
91 
92 // Helper to check if \p LV is either overdefined or a constant range with more
93 // than a single element. This should cover exactly the same cases as the old
94 // ValueLatticeElement::isOverdefined() and is intended to be used in the
95 // transition to ValueLatticeElement.
isOverdefined(const ValueLatticeElement & LV)96 static bool isOverdefined(const ValueLatticeElement &LV) {
97   return !LV.isUnknownOrUndef() && !isConstant(LV);
98 }
99 
100 
101 
102 
tryToReplaceWithConstant(SCCPSolver & Solver,Value * V)103 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
104   Constant *Const = nullptr;
105   if (V->getType()->isStructTy()) {
106     std::vector<ValueLatticeElement> IVs = Solver.getStructLatticeValueFor(V);
107     if (any_of(IVs,
108                [](const ValueLatticeElement &LV) { return isOverdefined(LV); }))
109       return false;
110     std::vector<Constant *> ConstVals;
111     auto *ST = cast<StructType>(V->getType());
112     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
113       ValueLatticeElement V = IVs[i];
114       ConstVals.push_back(isConstant(V)
115                               ? Solver.getConstant(V)
116                               : UndefValue::get(ST->getElementType(i)));
117     }
118     Const = ConstantStruct::get(ST, ConstVals);
119   } else {
120     const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
121     if (isOverdefined(IV))
122       return false;
123 
124     Const =
125         isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType());
126   }
127   assert(Const && "Constant is nullptr here!");
128 
129   // Replacing `musttail` instructions with constant breaks `musttail` invariant
130   // unless the call itself can be removed.
131   // Calls with "clang.arc.attachedcall" implicitly use the return value and
132   // those uses cannot be updated with a constant.
133   CallBase *CB = dyn_cast<CallBase>(V);
134   if (CB && ((CB->isMustTailCall() && !CB->isSafeToRemove()) ||
135              CB->getOperandBundle(LLVMContext::OB_clang_arc_attachedcall))) {
136     Function *F = CB->getCalledFunction();
137 
138     // Don't zap returns of the callee
139     if (F)
140       Solver.addToMustPreserveReturnsInFunctions(F);
141 
142     LLVM_DEBUG(dbgs() << "  Can\'t treat the result of call " << *CB
143                       << " as a constant\n");
144     return false;
145   }
146 
147   LLVM_DEBUG(dbgs() << "  Constant: " << *Const << " = " << *V << '\n');
148 
149   // Replaces all of the uses of a variable with uses of the constant.
150   V->replaceAllUsesWith(Const);
151   return true;
152 }
153 
simplifyInstsInBlock(SCCPSolver & Solver,BasicBlock & BB,SmallPtrSetImpl<Value * > & InsertedValues,Statistic & InstRemovedStat,Statistic & InstReplacedStat)154 static bool simplifyInstsInBlock(SCCPSolver &Solver, BasicBlock &BB,
155                                  SmallPtrSetImpl<Value *> &InsertedValues,
156                                  Statistic &InstRemovedStat,
157                                  Statistic &InstReplacedStat) {
158   bool MadeChanges = false;
159   for (Instruction &Inst : make_early_inc_range(BB)) {
160     if (Inst.getType()->isVoidTy())
161       continue;
162     if (tryToReplaceWithConstant(Solver, &Inst)) {
163       if (Inst.isSafeToRemove())
164         Inst.eraseFromParent();
165       // Hey, we just changed something!
166       MadeChanges = true;
167       ++InstRemovedStat;
168     } else if (isa<SExtInst>(&Inst)) {
169       Value *ExtOp = Inst.getOperand(0);
170       if (isa<Constant>(ExtOp) || InsertedValues.count(ExtOp))
171         continue;
172       const ValueLatticeElement &IV = Solver.getLatticeValueFor(ExtOp);
173       if (!IV.isConstantRange(/*UndefAllowed=*/false))
174         continue;
175       if (IV.getConstantRange().isAllNonNegative()) {
176         auto *ZExt = new ZExtInst(ExtOp, Inst.getType(), "", &Inst);
177         InsertedValues.insert(ZExt);
178         Inst.replaceAllUsesWith(ZExt);
179         Solver.removeLatticeValueFor(&Inst);
180         Inst.eraseFromParent();
181         InstReplacedStat++;
182         MadeChanges = true;
183       }
184     }
185   }
186   return MadeChanges;
187 }
188 
189 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
190 // and return true if the function was modified.
runSCCP(Function & F,const DataLayout & DL,const TargetLibraryInfo * TLI)191 static bool runSCCP(Function &F, const DataLayout &DL,
192                     const TargetLibraryInfo *TLI) {
193   LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
194   SCCPSolver Solver(
195       DL, [TLI](Function &F) -> const TargetLibraryInfo & { return *TLI; },
196       F.getContext());
197 
198   // Mark the first block of the function as being executable.
199   Solver.markBlockExecutable(&F.front());
200 
201   // Mark all arguments to the function as being overdefined.
202   for (Argument &AI : F.args())
203     Solver.markOverdefined(&AI);
204 
205   // Solve for constants.
206   bool ResolvedUndefs = true;
207   while (ResolvedUndefs) {
208     Solver.solve();
209     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
210     ResolvedUndefs = Solver.resolvedUndefsIn(F);
211   }
212 
213   bool MadeChanges = false;
214 
215   // If we decided that there are basic blocks that are dead in this function,
216   // delete their contents now.  Note that we cannot actually delete the blocks,
217   // as we cannot modify the CFG of the function.
218 
219   SmallPtrSet<Value *, 32> InsertedValues;
220   for (BasicBlock &BB : F) {
221     if (!Solver.isBlockExecutable(&BB)) {
222       LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
223 
224       ++NumDeadBlocks;
225       NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB).first;
226 
227       MadeChanges = true;
228       continue;
229     }
230 
231     MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues,
232                                         NumInstRemoved, NumInstReplaced);
233   }
234 
235   return MadeChanges;
236 }
237 
run(Function & F,FunctionAnalysisManager & AM)238 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
239   const DataLayout &DL = F.getParent()->getDataLayout();
240   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
241   if (!runSCCP(F, DL, &TLI))
242     return PreservedAnalyses::all();
243 
244   auto PA = PreservedAnalyses();
245   PA.preserveSet<CFGAnalyses>();
246   return PA;
247 }
248 
249 namespace {
250 
251 //===--------------------------------------------------------------------===//
252 //
253 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
254 /// Sparse Conditional Constant Propagator.
255 ///
256 class SCCPLegacyPass : public FunctionPass {
257 public:
258   // Pass identification, replacement for typeid
259   static char ID;
260 
SCCPLegacyPass()261   SCCPLegacyPass() : FunctionPass(ID) {
262     initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
263   }
264 
getAnalysisUsage(AnalysisUsage & AU) const265   void getAnalysisUsage(AnalysisUsage &AU) const override {
266     AU.addRequired<TargetLibraryInfoWrapperPass>();
267     AU.addPreserved<GlobalsAAWrapperPass>();
268     AU.setPreservesCFG();
269   }
270 
271   // runOnFunction - Run the Sparse Conditional Constant Propagation
272   // algorithm, and return true if the function was modified.
runOnFunction(Function & F)273   bool runOnFunction(Function &F) override {
274     if (skipFunction(F))
275       return false;
276     const DataLayout &DL = F.getParent()->getDataLayout();
277     const TargetLibraryInfo *TLI =
278         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
279     return runSCCP(F, DL, TLI);
280   }
281 };
282 
283 } // end anonymous namespace
284 
285 char SCCPLegacyPass::ID = 0;
286 
287 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
288                       "Sparse Conditional Constant Propagation", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)289 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
290 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
291                     "Sparse Conditional Constant Propagation", false, false)
292 
293 // createSCCPPass - This is the public interface to this file.
294 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
295 
findReturnsToZap(Function & F,SmallVector<ReturnInst *,8> & ReturnsToZap,SCCPSolver & Solver)296 static void findReturnsToZap(Function &F,
297                              SmallVector<ReturnInst *, 8> &ReturnsToZap,
298                              SCCPSolver &Solver) {
299   // We can only do this if we know that nothing else can call the function.
300   if (!Solver.isArgumentTrackedFunction(&F))
301     return;
302 
303   if (Solver.mustPreserveReturn(&F)) {
304     LLVM_DEBUG(
305         dbgs()
306         << "Can't zap returns of the function : " << F.getName()
307         << " due to present musttail or \"clang.arc.attachedcall\" call of "
308            "it\n");
309     return;
310   }
311 
312   assert(
313       all_of(F.users(),
314              [&Solver](User *U) {
315                if (isa<Instruction>(U) &&
316                    !Solver.isBlockExecutable(cast<Instruction>(U)->getParent()))
317                  return true;
318                // Non-callsite uses are not impacted by zapping. Also, constant
319                // uses (like blockaddresses) could stuck around, without being
320                // used in the underlying IR, meaning we do not have lattice
321                // values for them.
322                if (!isa<CallBase>(U))
323                  return true;
324                if (U->getType()->isStructTy()) {
325                  return all_of(Solver.getStructLatticeValueFor(U),
326                                [](const ValueLatticeElement &LV) {
327                                  return !isOverdefined(LV);
328                                });
329                }
330                return !isOverdefined(Solver.getLatticeValueFor(U));
331              }) &&
332       "We can only zap functions where all live users have a concrete value");
333 
334   for (BasicBlock &BB : F) {
335     if (CallInst *CI = BB.getTerminatingMustTailCall()) {
336       LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "
337                         << "musttail call : " << *CI << "\n");
338       (void)CI;
339       return;
340     }
341 
342     if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
343       if (!isa<UndefValue>(RI->getOperand(0)))
344         ReturnsToZap.push_back(RI);
345   }
346 }
347 
removeNonFeasibleEdges(const SCCPSolver & Solver,BasicBlock * BB,DomTreeUpdater & DTU)348 static bool removeNonFeasibleEdges(const SCCPSolver &Solver, BasicBlock *BB,
349                                    DomTreeUpdater &DTU) {
350   SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
351   bool HasNonFeasibleEdges = false;
352   for (BasicBlock *Succ : successors(BB)) {
353     if (Solver.isEdgeFeasible(BB, Succ))
354       FeasibleSuccessors.insert(Succ);
355     else
356       HasNonFeasibleEdges = true;
357   }
358 
359   // All edges feasible, nothing to do.
360   if (!HasNonFeasibleEdges)
361     return false;
362 
363   // SCCP can only determine non-feasible edges for br, switch and indirectbr.
364   Instruction *TI = BB->getTerminator();
365   assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
366           isa<IndirectBrInst>(TI)) &&
367          "Terminator must be a br, switch or indirectbr");
368 
369   if (FeasibleSuccessors.size() == 1) {
370     // Replace with an unconditional branch to the only feasible successor.
371     BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
372     SmallVector<DominatorTree::UpdateType, 8> Updates;
373     bool HaveSeenOnlyFeasibleSuccessor = false;
374     for (BasicBlock *Succ : successors(BB)) {
375       if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
376         // Don't remove the edge to the only feasible successor the first time
377         // we see it. We still do need to remove any multi-edges to it though.
378         HaveSeenOnlyFeasibleSuccessor = true;
379         continue;
380       }
381 
382       Succ->removePredecessor(BB);
383       Updates.push_back({DominatorTree::Delete, BB, Succ});
384     }
385 
386     BranchInst::Create(OnlyFeasibleSuccessor, BB);
387     TI->eraseFromParent();
388     DTU.applyUpdatesPermissive(Updates);
389   } else if (FeasibleSuccessors.size() > 1) {
390     SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(TI));
391     SmallVector<DominatorTree::UpdateType, 8> Updates;
392     for (auto CI = SI->case_begin(); CI != SI->case_end();) {
393       if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
394         ++CI;
395         continue;
396       }
397 
398       BasicBlock *Succ = CI->getCaseSuccessor();
399       Succ->removePredecessor(BB);
400       Updates.push_back({DominatorTree::Delete, BB, Succ});
401       SI.removeCase(CI);
402       // Don't increment CI, as we removed a case.
403     }
404 
405     DTU.applyUpdatesPermissive(Updates);
406   } else {
407     llvm_unreachable("Must have at least one feasible successor");
408   }
409   return true;
410 }
411 
runIPSCCP(Module & M,const DataLayout & DL,std::function<const TargetLibraryInfo & (Function &)> GetTLI,function_ref<AnalysisResultsForFn (Function &)> getAnalysis)412 bool llvm::runIPSCCP(
413     Module &M, const DataLayout &DL,
414     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
415     function_ref<AnalysisResultsForFn(Function &)> getAnalysis) {
416   SCCPSolver Solver(DL, GetTLI, M.getContext());
417 
418   // Loop over all functions, marking arguments to those with their addresses
419   // taken or that are external as overdefined.
420   for (Function &F : M) {
421     if (F.isDeclaration())
422       continue;
423 
424     Solver.addAnalysis(F, getAnalysis(F));
425 
426     // Determine if we can track the function's return values. If so, add the
427     // function to the solver's set of return-tracked functions.
428     if (canTrackReturnsInterprocedurally(&F))
429       Solver.addTrackedFunction(&F);
430 
431     // Determine if we can track the function's arguments. If so, add the
432     // function to the solver's set of argument-tracked functions.
433     if (canTrackArgumentsInterprocedurally(&F)) {
434       Solver.addArgumentTrackedFunction(&F);
435       continue;
436     }
437 
438     // Assume the function is called.
439     Solver.markBlockExecutable(&F.front());
440 
441     // Assume nothing about the incoming arguments.
442     for (Argument &AI : F.args())
443       Solver.markOverdefined(&AI);
444   }
445 
446   // Determine if we can track any of the module's global variables. If so, add
447   // the global variables we can track to the solver's set of tracked global
448   // variables.
449   for (GlobalVariable &G : M.globals()) {
450     G.removeDeadConstantUsers();
451     if (canTrackGlobalVariableInterprocedurally(&G))
452       Solver.trackValueOfGlobalVariable(&G);
453   }
454 
455   // Solve for constants.
456   bool ResolvedUndefs = true;
457   Solver.solve();
458   while (ResolvedUndefs) {
459     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
460     ResolvedUndefs = false;
461     for (Function &F : M) {
462       if (Solver.resolvedUndefsIn(F))
463         ResolvedUndefs = true;
464     }
465     if (ResolvedUndefs)
466       Solver.solve();
467   }
468 
469   bool MadeChanges = false;
470 
471   // Iterate over all of the instructions in the module, replacing them with
472   // constants if we have found them to be of constant values.
473 
474   for (Function &F : M) {
475     if (F.isDeclaration())
476       continue;
477 
478     SmallVector<BasicBlock *, 512> BlocksToErase;
479 
480     if (Solver.isBlockExecutable(&F.front())) {
481       bool ReplacedPointerArg = false;
482       for (Argument &Arg : F.args()) {
483         if (!Arg.use_empty() && tryToReplaceWithConstant(Solver, &Arg)) {
484           ReplacedPointerArg |= Arg.getType()->isPointerTy();
485           ++IPNumArgsElimed;
486         }
487       }
488 
489       // If we replaced an argument, the argmemonly and
490       // inaccessiblemem_or_argmemonly attributes do not hold any longer. Remove
491       // them from both the function and callsites.
492       if (ReplacedPointerArg) {
493         AttrBuilder AttributesToRemove;
494         AttributesToRemove.addAttribute(Attribute::ArgMemOnly);
495         AttributesToRemove.addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
496         F.removeAttributes(AttributeList::FunctionIndex, AttributesToRemove);
497 
498         for (User *U : F.users()) {
499           auto *CB = dyn_cast<CallBase>(U);
500           if (!CB || CB->getCalledFunction() != &F)
501             continue;
502 
503           CB->removeAttributes(AttributeList::FunctionIndex,
504                                AttributesToRemove);
505         }
506       }
507     }
508 
509     SmallPtrSet<Value *, 32> InsertedValues;
510     for (BasicBlock &BB : F) {
511       if (!Solver.isBlockExecutable(&BB)) {
512         LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
513         ++NumDeadBlocks;
514 
515         MadeChanges = true;
516 
517         if (&BB != &F.front())
518           BlocksToErase.push_back(&BB);
519         continue;
520       }
521 
522       MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues,
523                                           IPNumInstRemoved, IPNumInstReplaced);
524     }
525 
526     DomTreeUpdater DTU = Solver.getDTU(F);
527     // Change dead blocks to unreachable. We do it after replacing constants
528     // in all executable blocks, because changeToUnreachable may remove PHI
529     // nodes in executable blocks we found values for. The function's entry
530     // block is not part of BlocksToErase, so we have to handle it separately.
531     for (BasicBlock *BB : BlocksToErase) {
532       NumInstRemoved +=
533           changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false,
534                               /*PreserveLCSSA=*/false, &DTU);
535     }
536     if (!Solver.isBlockExecutable(&F.front()))
537       NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
538                                             /*UseLLVMTrap=*/false,
539                                             /*PreserveLCSSA=*/false, &DTU);
540 
541     for (BasicBlock &BB : F)
542       MadeChanges |= removeNonFeasibleEdges(Solver, &BB, DTU);
543 
544     for (BasicBlock *DeadBB : BlocksToErase)
545       DTU.deleteBB(DeadBB);
546 
547     for (BasicBlock &BB : F) {
548       for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
549         Instruction *Inst = &*BI++;
550         if (Solver.getPredicateInfoFor(Inst)) {
551           if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
552             if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
553               Value *Op = II->getOperand(0);
554               Inst->replaceAllUsesWith(Op);
555               Inst->eraseFromParent();
556             }
557           }
558         }
559       }
560     }
561   }
562 
563   // If we inferred constant or undef return values for a function, we replaced
564   // all call uses with the inferred value.  This means we don't need to bother
565   // actually returning anything from the function.  Replace all return
566   // instructions with return undef.
567   //
568   // Do this in two stages: first identify the functions we should process, then
569   // actually zap their returns.  This is important because we can only do this
570   // if the address of the function isn't taken.  In cases where a return is the
571   // last use of a function, the order of processing functions would affect
572   // whether other functions are optimizable.
573   SmallVector<ReturnInst*, 8> ReturnsToZap;
574 
575   for (const auto &I : Solver.getTrackedRetVals()) {
576     Function *F = I.first;
577     const ValueLatticeElement &ReturnValue = I.second;
578 
579     // If there is a known constant range for the return value, add !range
580     // metadata to the function's call sites.
581     if (ReturnValue.isConstantRange() &&
582         !ReturnValue.getConstantRange().isSingleElement()) {
583       // Do not add range metadata if the return value may include undef.
584       if (ReturnValue.isConstantRangeIncludingUndef())
585         continue;
586 
587       auto &CR = ReturnValue.getConstantRange();
588       for (User *User : F->users()) {
589         auto *CB = dyn_cast<CallBase>(User);
590         if (!CB || CB->getCalledFunction() != F)
591           continue;
592 
593         // Limit to cases where the return value is guaranteed to be neither
594         // poison nor undef. Poison will be outside any range and currently
595         // values outside of the specified range cause immediate undefined
596         // behavior.
597         if (!isGuaranteedNotToBeUndefOrPoison(CB, nullptr, CB))
598           continue;
599 
600         // Do not touch existing metadata for now.
601         // TODO: We should be able to take the intersection of the existing
602         // metadata and the inferred range.
603         if (CB->getMetadata(LLVMContext::MD_range))
604           continue;
605 
606         LLVMContext &Context = CB->getParent()->getContext();
607         Metadata *RangeMD[] = {
608             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getLower())),
609             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getUpper()))};
610         CB->setMetadata(LLVMContext::MD_range, MDNode::get(Context, RangeMD));
611       }
612       continue;
613     }
614     if (F->getReturnType()->isVoidTy())
615       continue;
616     if (isConstant(ReturnValue) || ReturnValue.isUnknownOrUndef())
617       findReturnsToZap(*F, ReturnsToZap, Solver);
618   }
619 
620   for (auto F : Solver.getMRVFunctionsTracked()) {
621     assert(F->getReturnType()->isStructTy() &&
622            "The return type should be a struct");
623     StructType *STy = cast<StructType>(F->getReturnType());
624     if (Solver.isStructLatticeConstant(F, STy))
625       findReturnsToZap(*F, ReturnsToZap, Solver);
626   }
627 
628   // Zap all returns which we've identified as zap to change.
629   SmallSetVector<Function *, 8> FuncZappedReturn;
630   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
631     Function *F = ReturnsToZap[i]->getParent()->getParent();
632     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
633     // Record all functions that are zapped.
634     FuncZappedReturn.insert(F);
635   }
636 
637   // Remove the returned attribute for zapped functions and the
638   // corresponding call sites.
639   for (Function *F : FuncZappedReturn) {
640     for (Argument &A : F->args())
641       F->removeParamAttr(A.getArgNo(), Attribute::Returned);
642     for (Use &U : F->uses()) {
643       // Skip over blockaddr users.
644       if (isa<BlockAddress>(U.getUser()))
645         continue;
646       CallBase *CB = cast<CallBase>(U.getUser());
647       for (Use &Arg : CB->args())
648         CB->removeParamAttr(CB->getArgOperandNo(&Arg), Attribute::Returned);
649     }
650   }
651 
652   // If we inferred constant or undef values for globals variables, we can
653   // delete the global and any stores that remain to it.
654   for (auto &I : make_early_inc_range(Solver.getTrackedGlobals())) {
655     GlobalVariable *GV = I.first;
656     if (isOverdefined(I.second))
657       continue;
658     LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
659                       << "' is constant!\n");
660     while (!GV->use_empty()) {
661       StoreInst *SI = cast<StoreInst>(GV->user_back());
662       SI->eraseFromParent();
663       MadeChanges = true;
664     }
665     M.getGlobalList().erase(GV);
666     ++IPNumGlobalConst;
667   }
668 
669   return MadeChanges;
670 }
671