xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/StackSafetyAnalysis.cpp (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
1 //===- StackSafetyAnalysis.cpp - Stack memory safety analysis -------------===//
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 //===----------------------------------------------------------------------===//
10 
11 #include "llvm/Analysis/StackSafetyAnalysis.h"
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
17 #include "llvm/Analysis/ScalarEvolution.h"
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Analysis/StackLifetime.h"
20 #include "llvm/IR/ConstantRange.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/ModuleSummaryIndex.h"
28 #include "llvm/InitializePasses.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/FormatVariadic.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <memory>
35 #include <tuple>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "stack-safety"
40 
41 STATISTIC(NumAllocaStackSafe, "Number of safe allocas");
42 STATISTIC(NumAllocaTotal, "Number of total allocas");
43 
44 STATISTIC(NumCombinedCalleeLookupTotal,
45           "Number of total callee lookups on combined index.");
46 STATISTIC(NumCombinedCalleeLookupFailed,
47           "Number of failed callee lookups on combined index.");
48 STATISTIC(NumModuleCalleeLookupTotal,
49           "Number of total callee lookups on module index.");
50 STATISTIC(NumModuleCalleeLookupFailed,
51           "Number of failed callee lookups on module index.");
52 STATISTIC(NumCombinedParamAccessesBefore,
53           "Number of total param accesses before generateParamAccessSummary.");
54 STATISTIC(NumCombinedParamAccessesAfter,
55           "Number of total param accesses after generateParamAccessSummary.");
56 STATISTIC(NumCombinedDataFlowNodes,
57           "Number of total nodes in combined index for dataflow processing.");
58 STATISTIC(NumIndexCalleeUnhandled, "Number of index callee which are unhandled.");
59 STATISTIC(NumIndexCalleeMultipleWeak, "Number of index callee non-unique weak.");
60 STATISTIC(NumIndexCalleeMultipleExternal, "Number of index callee non-unique external.");
61 
62 
63 static cl::opt<int> StackSafetyMaxIterations("stack-safety-max-iterations",
64                                              cl::init(20), cl::Hidden);
65 
66 static cl::opt<bool> StackSafetyPrint("stack-safety-print", cl::init(false),
67                                       cl::Hidden);
68 
69 static cl::opt<bool> StackSafetyRun("stack-safety-run", cl::init(false),
70                                     cl::Hidden);
71 
72 namespace {
73 
74 // Check if we should bailout for such ranges.
75 bool isUnsafe(const ConstantRange &R) {
76   return R.isEmptySet() || R.isFullSet() || R.isUpperSignWrapped();
77 }
78 
79 ConstantRange addOverflowNever(const ConstantRange &L, const ConstantRange &R) {
80   assert(!L.isSignWrappedSet());
81   assert(!R.isSignWrappedSet());
82   if (L.signedAddMayOverflow(R) !=
83       ConstantRange::OverflowResult::NeverOverflows)
84     return ConstantRange::getFull(L.getBitWidth());
85   ConstantRange Result = L.add(R);
86   assert(!Result.isSignWrappedSet());
87   return Result;
88 }
89 
90 ConstantRange unionNoWrap(const ConstantRange &L, const ConstantRange &R) {
91   assert(!L.isSignWrappedSet());
92   assert(!R.isSignWrappedSet());
93   auto Result = L.unionWith(R);
94   // Two non-wrapped sets can produce wrapped.
95   if (Result.isSignWrappedSet())
96     Result = ConstantRange::getFull(Result.getBitWidth());
97   return Result;
98 }
99 
100 /// Describes use of address in as a function call argument.
101 template <typename CalleeTy> struct CallInfo {
102   /// Function being called.
103   const CalleeTy *Callee = nullptr;
104   /// Index of argument which pass address.
105   size_t ParamNo = 0;
106 
107   CallInfo(const CalleeTy *Callee, size_t ParamNo)
108       : Callee(Callee), ParamNo(ParamNo) {}
109 
110   struct Less {
111     bool operator()(const CallInfo &L, const CallInfo &R) const {
112       return std::tie(L.ParamNo, L.Callee) < std::tie(R.ParamNo, R.Callee);
113     }
114   };
115 };
116 
117 /// Describe uses of address (alloca or parameter) inside of the function.
118 template <typename CalleeTy> struct UseInfo {
119   // Access range if the address (alloca or parameters).
120   // It is allowed to be empty-set when there are no known accesses.
121   ConstantRange Range;
122   std::set<const Instruction *> UnsafeAccesses;
123 
124   // List of calls which pass address as an argument.
125   // Value is offset range of address from base address (alloca or calling
126   // function argument). Range should never set to empty-set, that is an invalid
127   // access range that can cause empty-set to be propagated with
128   // ConstantRange::add
129   using CallsTy = std::map<CallInfo<CalleeTy>, ConstantRange,
130                            typename CallInfo<CalleeTy>::Less>;
131   CallsTy Calls;
132 
133   UseInfo(unsigned PointerSize) : Range{PointerSize, false} {}
134 
135   void updateRange(const ConstantRange &R) { Range = unionNoWrap(Range, R); }
136   void addRange(const Instruction *I, const ConstantRange &R, bool IsSafe) {
137     if (!IsSafe)
138       UnsafeAccesses.insert(I);
139     updateRange(R);
140   }
141 };
142 
143 template <typename CalleeTy>
144 raw_ostream &operator<<(raw_ostream &OS, const UseInfo<CalleeTy> &U) {
145   OS << U.Range;
146   for (auto &Call : U.Calls)
147     OS << ", "
148        << "@" << Call.first.Callee->getName() << "(arg" << Call.first.ParamNo
149        << ", " << Call.second << ")";
150   return OS;
151 }
152 
153 /// Calculate the allocation size of a given alloca. Returns empty range
154 // in case of confution.
155 ConstantRange getStaticAllocaSizeRange(const AllocaInst &AI) {
156   const DataLayout &DL = AI.getModule()->getDataLayout();
157   TypeSize TS = DL.getTypeAllocSize(AI.getAllocatedType());
158   unsigned PointerSize = DL.getPointerTypeSizeInBits(AI.getType());
159   // Fallback to empty range for alloca size.
160   ConstantRange R = ConstantRange::getEmpty(PointerSize);
161   if (TS.isScalable())
162     return R;
163   APInt APSize(PointerSize, TS.getFixedSize(), true);
164   if (APSize.isNonPositive())
165     return R;
166   if (AI.isArrayAllocation()) {
167     const auto *C = dyn_cast<ConstantInt>(AI.getArraySize());
168     if (!C)
169       return R;
170     bool Overflow = false;
171     APInt Mul = C->getValue();
172     if (Mul.isNonPositive())
173       return R;
174     Mul = Mul.sextOrTrunc(PointerSize);
175     APSize = APSize.smul_ov(Mul, Overflow);
176     if (Overflow)
177       return R;
178   }
179   R = ConstantRange(APInt::getZero(PointerSize), APSize);
180   assert(!isUnsafe(R));
181   return R;
182 }
183 
184 template <typename CalleeTy> struct FunctionInfo {
185   std::map<const AllocaInst *, UseInfo<CalleeTy>> Allocas;
186   std::map<uint32_t, UseInfo<CalleeTy>> Params;
187   // TODO: describe return value as depending on one or more of its arguments.
188 
189   // StackSafetyDataFlowAnalysis counter stored here for faster access.
190   int UpdateCount = 0;
191 
192   void print(raw_ostream &O, StringRef Name, const Function *F) const {
193     // TODO: Consider different printout format after
194     // StackSafetyDataFlowAnalysis. Calls and parameters are irrelevant then.
195     O << "  @" << Name << ((F && F->isDSOLocal()) ? "" : " dso_preemptable")
196       << ((F && F->isInterposable()) ? " interposable" : "") << "\n";
197 
198     O << "    args uses:\n";
199     for (auto &KV : Params) {
200       O << "      ";
201       if (F)
202         O << F->getArg(KV.first)->getName();
203       else
204         O << formatv("arg{0}", KV.first);
205       O << "[]: " << KV.second << "\n";
206     }
207 
208     O << "    allocas uses:\n";
209     if (F) {
210       for (auto &I : instructions(F)) {
211         if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
212           auto &AS = Allocas.find(AI)->second;
213           O << "      " << AI->getName() << "["
214             << getStaticAllocaSizeRange(*AI).getUpper() << "]: " << AS << "\n";
215         }
216       }
217     } else {
218       assert(Allocas.empty());
219     }
220   }
221 };
222 
223 using GVToSSI = std::map<const GlobalValue *, FunctionInfo<GlobalValue>>;
224 
225 } // namespace
226 
227 struct StackSafetyInfo::InfoTy {
228   FunctionInfo<GlobalValue> Info;
229 };
230 
231 struct StackSafetyGlobalInfo::InfoTy {
232   GVToSSI Info;
233   SmallPtrSet<const AllocaInst *, 8> SafeAllocas;
234   std::set<const Instruction *> UnsafeAccesses;
235 };
236 
237 namespace {
238 
239 class StackSafetyLocalAnalysis {
240   Function &F;
241   const DataLayout &DL;
242   ScalarEvolution &SE;
243   unsigned PointerSize = 0;
244 
245   const ConstantRange UnknownRange;
246 
247   ConstantRange offsetFrom(Value *Addr, Value *Base);
248   ConstantRange getAccessRange(Value *Addr, Value *Base,
249                                const ConstantRange &SizeRange);
250   ConstantRange getAccessRange(Value *Addr, Value *Base, TypeSize Size);
251   ConstantRange getMemIntrinsicAccessRange(const MemIntrinsic *MI, const Use &U,
252                                            Value *Base);
253 
254   void analyzeAllUses(Value *Ptr, UseInfo<GlobalValue> &AS,
255                       const StackLifetime &SL);
256 
257 
258   bool isSafeAccess(const Use &U, AllocaInst *AI, const SCEV *AccessSize);
259   bool isSafeAccess(const Use &U, AllocaInst *AI, Value *V);
260   bool isSafeAccess(const Use &U, AllocaInst *AI, TypeSize AccessSize);
261 
262 public:
263   StackSafetyLocalAnalysis(Function &F, ScalarEvolution &SE)
264       : F(F), DL(F.getParent()->getDataLayout()), SE(SE),
265         PointerSize(DL.getPointerSizeInBits()),
266         UnknownRange(PointerSize, true) {}
267 
268   // Run the transformation on the associated function.
269   FunctionInfo<GlobalValue> run();
270 };
271 
272 ConstantRange StackSafetyLocalAnalysis::offsetFrom(Value *Addr, Value *Base) {
273   if (!SE.isSCEVable(Addr->getType()) || !SE.isSCEVable(Base->getType()))
274     return UnknownRange;
275 
276   auto *PtrTy = IntegerType::getInt8PtrTy(SE.getContext());
277   const SCEV *AddrExp = SE.getTruncateOrZeroExtend(SE.getSCEV(Addr), PtrTy);
278   const SCEV *BaseExp = SE.getTruncateOrZeroExtend(SE.getSCEV(Base), PtrTy);
279   const SCEV *Diff = SE.getMinusSCEV(AddrExp, BaseExp);
280   if (isa<SCEVCouldNotCompute>(Diff))
281     return UnknownRange;
282 
283   ConstantRange Offset = SE.getSignedRange(Diff);
284   if (isUnsafe(Offset))
285     return UnknownRange;
286   return Offset.sextOrTrunc(PointerSize);
287 }
288 
289 ConstantRange
290 StackSafetyLocalAnalysis::getAccessRange(Value *Addr, Value *Base,
291                                          const ConstantRange &SizeRange) {
292   // Zero-size loads and stores do not access memory.
293   if (SizeRange.isEmptySet())
294     return ConstantRange::getEmpty(PointerSize);
295   assert(!isUnsafe(SizeRange));
296 
297   ConstantRange Offsets = offsetFrom(Addr, Base);
298   if (isUnsafe(Offsets))
299     return UnknownRange;
300 
301   Offsets = addOverflowNever(Offsets, SizeRange);
302   if (isUnsafe(Offsets))
303     return UnknownRange;
304   return Offsets;
305 }
306 
307 ConstantRange StackSafetyLocalAnalysis::getAccessRange(Value *Addr, Value *Base,
308                                                        TypeSize Size) {
309   if (Size.isScalable())
310     return UnknownRange;
311   APInt APSize(PointerSize, Size.getFixedSize(), true);
312   if (APSize.isNegative())
313     return UnknownRange;
314   return getAccessRange(Addr, Base,
315                         ConstantRange(APInt::getZero(PointerSize), APSize));
316 }
317 
318 ConstantRange StackSafetyLocalAnalysis::getMemIntrinsicAccessRange(
319     const MemIntrinsic *MI, const Use &U, Value *Base) {
320   if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
321     if (MTI->getRawSource() != U && MTI->getRawDest() != U)
322       return ConstantRange::getEmpty(PointerSize);
323   } else {
324     if (MI->getRawDest() != U)
325       return ConstantRange::getEmpty(PointerSize);
326   }
327 
328   auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
329   if (!SE.isSCEVable(MI->getLength()->getType()))
330     return UnknownRange;
331 
332   const SCEV *Expr =
333       SE.getTruncateOrZeroExtend(SE.getSCEV(MI->getLength()), CalculationTy);
334   ConstantRange Sizes = SE.getSignedRange(Expr);
335   if (Sizes.getUpper().isNegative() || isUnsafe(Sizes))
336     return UnknownRange;
337   Sizes = Sizes.sextOrTrunc(PointerSize);
338   ConstantRange SizeRange(APInt::getZero(PointerSize), Sizes.getUpper() - 1);
339   return getAccessRange(U, Base, SizeRange);
340 }
341 
342 bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
343                                             Value *V) {
344   return isSafeAccess(U, AI, SE.getSCEV(V));
345 }
346 
347 bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
348                                             TypeSize TS) {
349   if (TS.isScalable())
350     return false;
351   auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
352   const SCEV *SV = SE.getConstant(CalculationTy, TS.getFixedSize());
353   return isSafeAccess(U, AI, SV);
354 }
355 
356 bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
357                                             const SCEV *AccessSize) {
358 
359   if (!AI)
360     return true;
361   if (isa<SCEVCouldNotCompute>(AccessSize))
362     return false;
363 
364   const auto *I = cast<Instruction>(U.getUser());
365 
366   auto ToCharPtr = [&](const SCEV *V) {
367     auto *PtrTy = IntegerType::getInt8PtrTy(SE.getContext());
368     return SE.getTruncateOrZeroExtend(V, PtrTy);
369   };
370 
371   const SCEV *AddrExp = ToCharPtr(SE.getSCEV(U.get()));
372   const SCEV *BaseExp = ToCharPtr(SE.getSCEV(AI));
373   const SCEV *Diff = SE.getMinusSCEV(AddrExp, BaseExp);
374   if (isa<SCEVCouldNotCompute>(Diff))
375     return false;
376 
377   auto Size = getStaticAllocaSizeRange(*AI);
378 
379   auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
380   auto ToDiffTy = [&](const SCEV *V) {
381     return SE.getTruncateOrZeroExtend(V, CalculationTy);
382   };
383   const SCEV *Min = ToDiffTy(SE.getConstant(Size.getLower()));
384   const SCEV *Max = SE.getMinusSCEV(ToDiffTy(SE.getConstant(Size.getUpper())),
385                                     ToDiffTy(AccessSize));
386   return SE.evaluatePredicateAt(ICmpInst::Predicate::ICMP_SGE, Diff, Min, I)
387              .getValueOr(false) &&
388          SE.evaluatePredicateAt(ICmpInst::Predicate::ICMP_SLE, Diff, Max, I)
389              .getValueOr(false);
390 }
391 
392 /// The function analyzes all local uses of Ptr (alloca or argument) and
393 /// calculates local access range and all function calls where it was used.
394 void StackSafetyLocalAnalysis::analyzeAllUses(Value *Ptr,
395                                               UseInfo<GlobalValue> &US,
396                                               const StackLifetime &SL) {
397   SmallPtrSet<const Value *, 16> Visited;
398   SmallVector<const Value *, 8> WorkList;
399   WorkList.push_back(Ptr);
400   AllocaInst *AI = dyn_cast<AllocaInst>(Ptr);
401 
402   // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
403   while (!WorkList.empty()) {
404     const Value *V = WorkList.pop_back_val();
405     for (const Use &UI : V->uses()) {
406       const auto *I = cast<Instruction>(UI.getUser());
407       if (!SL.isReachable(I))
408         continue;
409 
410       assert(V == UI.get());
411 
412       switch (I->getOpcode()) {
413       case Instruction::Load: {
414         if (AI && !SL.isAliveAfter(AI, I)) {
415           US.addRange(I, UnknownRange, /*IsSafe=*/false);
416           break;
417         }
418         auto TypeSize = DL.getTypeStoreSize(I->getType());
419         auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
420         bool Safe = isSafeAccess(UI, AI, TypeSize);
421         US.addRange(I, AccessRange, Safe);
422         break;
423       }
424 
425       case Instruction::VAArg:
426         // "va-arg" from a pointer is safe.
427         break;
428       case Instruction::Store: {
429         if (V == I->getOperand(0)) {
430           // Stored the pointer - conservatively assume it may be unsafe.
431           US.addRange(I, UnknownRange, /*IsSafe=*/false);
432           break;
433         }
434         if (AI && !SL.isAliveAfter(AI, I)) {
435           US.addRange(I, UnknownRange, /*IsSafe=*/false);
436           break;
437         }
438         auto TypeSize = DL.getTypeStoreSize(I->getOperand(0)->getType());
439         auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
440         bool Safe = isSafeAccess(UI, AI, TypeSize);
441         US.addRange(I, AccessRange, Safe);
442         break;
443       }
444 
445       case Instruction::Ret:
446         // Information leak.
447         // FIXME: Process parameters correctly. This is a leak only if we return
448         // alloca.
449         US.addRange(I, UnknownRange, /*IsSafe=*/false);
450         break;
451 
452       case Instruction::Call:
453       case Instruction::Invoke: {
454         if (I->isLifetimeStartOrEnd())
455           break;
456 
457         if (AI && !SL.isAliveAfter(AI, I)) {
458           US.addRange(I, UnknownRange, /*IsSafe=*/false);
459           break;
460         }
461         if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
462           auto AccessRange = getMemIntrinsicAccessRange(MI, UI, Ptr);
463           bool Safe = false;
464           if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
465             if (MTI->getRawSource() != UI && MTI->getRawDest() != UI)
466               Safe = true;
467           } else if (MI->getRawDest() != UI) {
468             Safe = true;
469           }
470           Safe = Safe || isSafeAccess(UI, AI, MI->getLength());
471           US.addRange(I, AccessRange, Safe);
472           break;
473         }
474 
475         const auto &CB = cast<CallBase>(*I);
476         if (CB.getReturnedArgOperand() == V) {
477           if (Visited.insert(I).second)
478             WorkList.push_back(cast<const Instruction>(I));
479         }
480 
481         if (!CB.isArgOperand(&UI)) {
482           US.addRange(I, UnknownRange, /*IsSafe=*/false);
483           break;
484         }
485 
486         unsigned ArgNo = CB.getArgOperandNo(&UI);
487         if (CB.isByValArgument(ArgNo)) {
488           auto TypeSize = DL.getTypeStoreSize(CB.getParamByValType(ArgNo));
489           auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
490           bool Safe = isSafeAccess(UI, AI, TypeSize);
491           US.addRange(I, AccessRange, Safe);
492           break;
493         }
494 
495         // FIXME: consult devirt?
496         // Do not follow aliases, otherwise we could inadvertently follow
497         // dso_preemptable aliases or aliases with interposable linkage.
498         const GlobalValue *Callee =
499             dyn_cast<GlobalValue>(CB.getCalledOperand()->stripPointerCasts());
500         if (!Callee) {
501           US.addRange(I, UnknownRange, /*IsSafe=*/false);
502           break;
503         }
504 
505         assert(isa<Function>(Callee) || isa<GlobalAlias>(Callee));
506         ConstantRange Offsets = offsetFrom(UI, Ptr);
507         auto Insert =
508             US.Calls.emplace(CallInfo<GlobalValue>(Callee, ArgNo), Offsets);
509         if (!Insert.second)
510           Insert.first->second = Insert.first->second.unionWith(Offsets);
511         break;
512       }
513 
514       default:
515         if (Visited.insert(I).second)
516           WorkList.push_back(cast<const Instruction>(I));
517       }
518     }
519   }
520 }
521 
522 FunctionInfo<GlobalValue> StackSafetyLocalAnalysis::run() {
523   FunctionInfo<GlobalValue> Info;
524   assert(!F.isDeclaration() &&
525          "Can't run StackSafety on a function declaration");
526 
527   LLVM_DEBUG(dbgs() << "[StackSafety] " << F.getName() << "\n");
528 
529   SmallVector<AllocaInst *, 64> Allocas;
530   for (auto &I : instructions(F))
531     if (auto *AI = dyn_cast<AllocaInst>(&I))
532       Allocas.push_back(AI);
533   StackLifetime SL(F, Allocas, StackLifetime::LivenessType::Must);
534   SL.run();
535 
536   for (auto *AI : Allocas) {
537     auto &UI = Info.Allocas.emplace(AI, PointerSize).first->second;
538     analyzeAllUses(AI, UI, SL);
539   }
540 
541   for (Argument &A : F.args()) {
542     // Non pointers and bypass arguments are not going to be used in any global
543     // processing.
544     if (A.getType()->isPointerTy() && !A.hasByValAttr()) {
545       auto &UI = Info.Params.emplace(A.getArgNo(), PointerSize).first->second;
546       analyzeAllUses(&A, UI, SL);
547     }
548   }
549 
550   LLVM_DEBUG(Info.print(dbgs(), F.getName(), &F));
551   LLVM_DEBUG(dbgs() << "\n[StackSafety] done\n");
552   return Info;
553 }
554 
555 template <typename CalleeTy> class StackSafetyDataFlowAnalysis {
556   using FunctionMap = std::map<const CalleeTy *, FunctionInfo<CalleeTy>>;
557 
558   FunctionMap Functions;
559   const ConstantRange UnknownRange;
560 
561   // Callee-to-Caller multimap.
562   DenseMap<const CalleeTy *, SmallVector<const CalleeTy *, 4>> Callers;
563   SetVector<const CalleeTy *> WorkList;
564 
565   bool updateOneUse(UseInfo<CalleeTy> &US, bool UpdateToFullSet);
566   void updateOneNode(const CalleeTy *Callee, FunctionInfo<CalleeTy> &FS);
567   void updateOneNode(const CalleeTy *Callee) {
568     updateOneNode(Callee, Functions.find(Callee)->second);
569   }
570   void updateAllNodes() {
571     for (auto &F : Functions)
572       updateOneNode(F.first, F.second);
573   }
574   void runDataFlow();
575 #ifndef NDEBUG
576   void verifyFixedPoint();
577 #endif
578 
579 public:
580   StackSafetyDataFlowAnalysis(uint32_t PointerBitWidth, FunctionMap Functions)
581       : Functions(std::move(Functions)),
582         UnknownRange(ConstantRange::getFull(PointerBitWidth)) {}
583 
584   const FunctionMap &run();
585 
586   ConstantRange getArgumentAccessRange(const CalleeTy *Callee, unsigned ParamNo,
587                                        const ConstantRange &Offsets) const;
588 };
589 
590 template <typename CalleeTy>
591 ConstantRange StackSafetyDataFlowAnalysis<CalleeTy>::getArgumentAccessRange(
592     const CalleeTy *Callee, unsigned ParamNo,
593     const ConstantRange &Offsets) const {
594   auto FnIt = Functions.find(Callee);
595   // Unknown callee (outside of LTO domain or an indirect call).
596   if (FnIt == Functions.end())
597     return UnknownRange;
598   auto &FS = FnIt->second;
599   auto ParamIt = FS.Params.find(ParamNo);
600   if (ParamIt == FS.Params.end())
601     return UnknownRange;
602   auto &Access = ParamIt->second.Range;
603   if (Access.isEmptySet())
604     return Access;
605   if (Access.isFullSet())
606     return UnknownRange;
607   return addOverflowNever(Access, Offsets);
608 }
609 
610 template <typename CalleeTy>
611 bool StackSafetyDataFlowAnalysis<CalleeTy>::updateOneUse(UseInfo<CalleeTy> &US,
612                                                          bool UpdateToFullSet) {
613   bool Changed = false;
614   for (auto &KV : US.Calls) {
615     assert(!KV.second.isEmptySet() &&
616            "Param range can't be empty-set, invalid offset range");
617 
618     ConstantRange CalleeRange =
619         getArgumentAccessRange(KV.first.Callee, KV.first.ParamNo, KV.second);
620     if (!US.Range.contains(CalleeRange)) {
621       Changed = true;
622       if (UpdateToFullSet)
623         US.Range = UnknownRange;
624       else
625         US.updateRange(CalleeRange);
626     }
627   }
628   return Changed;
629 }
630 
631 template <typename CalleeTy>
632 void StackSafetyDataFlowAnalysis<CalleeTy>::updateOneNode(
633     const CalleeTy *Callee, FunctionInfo<CalleeTy> &FS) {
634   bool UpdateToFullSet = FS.UpdateCount > StackSafetyMaxIterations;
635   bool Changed = false;
636   for (auto &KV : FS.Params)
637     Changed |= updateOneUse(KV.second, UpdateToFullSet);
638 
639   if (Changed) {
640     LLVM_DEBUG(dbgs() << "=== update [" << FS.UpdateCount
641                       << (UpdateToFullSet ? ", full-set" : "") << "] " << &FS
642                       << "\n");
643     // Callers of this function may need updating.
644     for (auto &CallerID : Callers[Callee])
645       WorkList.insert(CallerID);
646 
647     ++FS.UpdateCount;
648   }
649 }
650 
651 template <typename CalleeTy>
652 void StackSafetyDataFlowAnalysis<CalleeTy>::runDataFlow() {
653   SmallVector<const CalleeTy *, 16> Callees;
654   for (auto &F : Functions) {
655     Callees.clear();
656     auto &FS = F.second;
657     for (auto &KV : FS.Params)
658       for (auto &CS : KV.second.Calls)
659         Callees.push_back(CS.first.Callee);
660 
661     llvm::sort(Callees);
662     Callees.erase(std::unique(Callees.begin(), Callees.end()), Callees.end());
663 
664     for (auto &Callee : Callees)
665       Callers[Callee].push_back(F.first);
666   }
667 
668   updateAllNodes();
669 
670   while (!WorkList.empty()) {
671     const CalleeTy *Callee = WorkList.pop_back_val();
672     updateOneNode(Callee);
673   }
674 }
675 
676 #ifndef NDEBUG
677 template <typename CalleeTy>
678 void StackSafetyDataFlowAnalysis<CalleeTy>::verifyFixedPoint() {
679   WorkList.clear();
680   updateAllNodes();
681   assert(WorkList.empty());
682 }
683 #endif
684 
685 template <typename CalleeTy>
686 const typename StackSafetyDataFlowAnalysis<CalleeTy>::FunctionMap &
687 StackSafetyDataFlowAnalysis<CalleeTy>::run() {
688   runDataFlow();
689   LLVM_DEBUG(verifyFixedPoint());
690   return Functions;
691 }
692 
693 FunctionSummary *findCalleeFunctionSummary(ValueInfo VI, StringRef ModuleId) {
694   if (!VI)
695     return nullptr;
696   auto SummaryList = VI.getSummaryList();
697   GlobalValueSummary* S = nullptr;
698   for (const auto& GVS : SummaryList) {
699     if (!GVS->isLive())
700       continue;
701     if (const AliasSummary *AS = dyn_cast<AliasSummary>(GVS.get()))
702       if (!AS->hasAliasee())
703         continue;
704     if (!isa<FunctionSummary>(GVS->getBaseObject()))
705       continue;
706     if (GlobalValue::isLocalLinkage(GVS->linkage())) {
707       if (GVS->modulePath() == ModuleId) {
708         S = GVS.get();
709         break;
710       }
711     } else if (GlobalValue::isExternalLinkage(GVS->linkage())) {
712       if (S) {
713         ++NumIndexCalleeMultipleExternal;
714         return nullptr;
715       }
716       S = GVS.get();
717     } else if (GlobalValue::isWeakLinkage(GVS->linkage())) {
718       if (S) {
719         ++NumIndexCalleeMultipleWeak;
720         return nullptr;
721       }
722       S = GVS.get();
723     } else if (GlobalValue::isAvailableExternallyLinkage(GVS->linkage()) ||
724                GlobalValue::isLinkOnceLinkage(GVS->linkage())) {
725       if (SummaryList.size() == 1)
726         S = GVS.get();
727       // According thinLTOResolvePrevailingGUID these are unlikely prevailing.
728     } else {
729       ++NumIndexCalleeUnhandled;
730     }
731   };
732   while (S) {
733     if (!S->isLive() || !S->isDSOLocal())
734       return nullptr;
735     if (FunctionSummary *FS = dyn_cast<FunctionSummary>(S))
736       return FS;
737     AliasSummary *AS = dyn_cast<AliasSummary>(S);
738     if (!AS || !AS->hasAliasee())
739       return nullptr;
740     S = AS->getBaseObject();
741     if (S == AS)
742       return nullptr;
743   }
744   return nullptr;
745 }
746 
747 const Function *findCalleeInModule(const GlobalValue *GV) {
748   while (GV) {
749     if (GV->isDeclaration() || GV->isInterposable() || !GV->isDSOLocal())
750       return nullptr;
751     if (const Function *F = dyn_cast<Function>(GV))
752       return F;
753     const GlobalAlias *A = dyn_cast<GlobalAlias>(GV);
754     if (!A)
755       return nullptr;
756     GV = A->getAliaseeObject();
757     if (GV == A)
758       return nullptr;
759   }
760   return nullptr;
761 }
762 
763 const ConstantRange *findParamAccess(const FunctionSummary &FS,
764                                      uint32_t ParamNo) {
765   assert(FS.isLive());
766   assert(FS.isDSOLocal());
767   for (auto &PS : FS.paramAccesses())
768     if (ParamNo == PS.ParamNo)
769       return &PS.Use;
770   return nullptr;
771 }
772 
773 void resolveAllCalls(UseInfo<GlobalValue> &Use,
774                      const ModuleSummaryIndex *Index) {
775   ConstantRange FullSet(Use.Range.getBitWidth(), true);
776   // Move Use.Calls to a temp storage and repopulate - don't use std::move as it
777   // leaves Use.Calls in an undefined state.
778   UseInfo<GlobalValue>::CallsTy TmpCalls;
779   std::swap(TmpCalls, Use.Calls);
780   for (const auto &C : TmpCalls) {
781     const Function *F = findCalleeInModule(C.first.Callee);
782     if (F) {
783       Use.Calls.emplace(CallInfo<GlobalValue>(F, C.first.ParamNo), C.second);
784       continue;
785     }
786 
787     if (!Index)
788       return Use.updateRange(FullSet);
789     FunctionSummary *FS =
790         findCalleeFunctionSummary(Index->getValueInfo(C.first.Callee->getGUID()),
791                                   C.first.Callee->getParent()->getModuleIdentifier());
792     ++NumModuleCalleeLookupTotal;
793     if (!FS) {
794       ++NumModuleCalleeLookupFailed;
795       return Use.updateRange(FullSet);
796     }
797     const ConstantRange *Found = findParamAccess(*FS, C.first.ParamNo);
798     if (!Found || Found->isFullSet())
799       return Use.updateRange(FullSet);
800     ConstantRange Access = Found->sextOrTrunc(Use.Range.getBitWidth());
801     if (!Access.isEmptySet())
802       Use.updateRange(addOverflowNever(Access, C.second));
803   }
804 }
805 
806 GVToSSI createGlobalStackSafetyInfo(
807     std::map<const GlobalValue *, FunctionInfo<GlobalValue>> Functions,
808     const ModuleSummaryIndex *Index) {
809   GVToSSI SSI;
810   if (Functions.empty())
811     return SSI;
812 
813   // FIXME: Simplify printing and remove copying here.
814   auto Copy = Functions;
815 
816   for (auto &FnKV : Copy)
817     for (auto &KV : FnKV.second.Params) {
818       resolveAllCalls(KV.second, Index);
819       if (KV.second.Range.isFullSet())
820         KV.second.Calls.clear();
821     }
822 
823   uint32_t PointerSize =
824       Copy.begin()->first->getParent()->getDataLayout().getPointerSizeInBits();
825   StackSafetyDataFlowAnalysis<GlobalValue> SSDFA(PointerSize, std::move(Copy));
826 
827   for (auto &F : SSDFA.run()) {
828     auto FI = F.second;
829     auto &SrcF = Functions[F.first];
830     for (auto &KV : FI.Allocas) {
831       auto &A = KV.second;
832       resolveAllCalls(A, Index);
833       for (auto &C : A.Calls) {
834         A.updateRange(SSDFA.getArgumentAccessRange(C.first.Callee,
835                                                    C.first.ParamNo, C.second));
836       }
837       // FIXME: This is needed only to preserve calls in print() results.
838       A.Calls = SrcF.Allocas.find(KV.first)->second.Calls;
839     }
840     for (auto &KV : FI.Params) {
841       auto &P = KV.second;
842       P.Calls = SrcF.Params.find(KV.first)->second.Calls;
843     }
844     SSI[F.first] = std::move(FI);
845   }
846 
847   return SSI;
848 }
849 
850 } // end anonymous namespace
851 
852 StackSafetyInfo::StackSafetyInfo() = default;
853 
854 StackSafetyInfo::StackSafetyInfo(Function *F,
855                                  std::function<ScalarEvolution &()> GetSE)
856     : F(F), GetSE(GetSE) {}
857 
858 StackSafetyInfo::StackSafetyInfo(StackSafetyInfo &&) = default;
859 
860 StackSafetyInfo &StackSafetyInfo::operator=(StackSafetyInfo &&) = default;
861 
862 StackSafetyInfo::~StackSafetyInfo() = default;
863 
864 const StackSafetyInfo::InfoTy &StackSafetyInfo::getInfo() const {
865   if (!Info) {
866     StackSafetyLocalAnalysis SSLA(*F, GetSE());
867     Info.reset(new InfoTy{SSLA.run()});
868   }
869   return *Info;
870 }
871 
872 void StackSafetyInfo::print(raw_ostream &O) const {
873   getInfo().Info.print(O, F->getName(), dyn_cast<Function>(F));
874   O << "\n";
875 }
876 
877 const StackSafetyGlobalInfo::InfoTy &StackSafetyGlobalInfo::getInfo() const {
878   if (!Info) {
879     std::map<const GlobalValue *, FunctionInfo<GlobalValue>> Functions;
880     for (auto &F : M->functions()) {
881       if (!F.isDeclaration()) {
882         auto FI = GetSSI(F).getInfo().Info;
883         Functions.emplace(&F, std::move(FI));
884       }
885     }
886     Info.reset(new InfoTy{
887         createGlobalStackSafetyInfo(std::move(Functions), Index), {}, {}});
888 
889     for (auto &FnKV : Info->Info) {
890       for (auto &KV : FnKV.second.Allocas) {
891         ++NumAllocaTotal;
892         const AllocaInst *AI = KV.first;
893         auto AIRange = getStaticAllocaSizeRange(*AI);
894         if (AIRange.contains(KV.second.Range)) {
895           Info->SafeAllocas.insert(AI);
896           ++NumAllocaStackSafe;
897         }
898         Info->UnsafeAccesses.insert(KV.second.UnsafeAccesses.begin(),
899                                     KV.second.UnsafeAccesses.end());
900       }
901     }
902 
903     if (StackSafetyPrint)
904       print(errs());
905   }
906   return *Info;
907 }
908 
909 std::vector<FunctionSummary::ParamAccess>
910 StackSafetyInfo::getParamAccesses(ModuleSummaryIndex &Index) const {
911   // Implementation transforms internal representation of parameter information
912   // into FunctionSummary format.
913   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
914   for (const auto &KV : getInfo().Info.Params) {
915     auto &PS = KV.second;
916     // Parameter accessed by any or unknown offset, represented as FullSet by
917     // StackSafety, is handled as the parameter for which we have no
918     // StackSafety info at all. So drop it to reduce summary size.
919     if (PS.Range.isFullSet())
920       continue;
921 
922     ParamAccesses.emplace_back(KV.first, PS.Range);
923     FunctionSummary::ParamAccess &Param = ParamAccesses.back();
924 
925     Param.Calls.reserve(PS.Calls.size());
926     for (auto &C : PS.Calls) {
927       // Parameter forwarded into another function by any or unknown offset
928       // will make ParamAccess::Range as FullSet anyway. So we can drop the
929       // entire parameter like we did above.
930       // TODO(vitalybuka): Return already filtered parameters from getInfo().
931       if (C.second.isFullSet()) {
932         ParamAccesses.pop_back();
933         break;
934       }
935       Param.Calls.emplace_back(C.first.ParamNo,
936                                Index.getOrInsertValueInfo(C.first.Callee),
937                                C.second);
938     }
939   }
940   for (FunctionSummary::ParamAccess &Param : ParamAccesses) {
941     sort(Param.Calls, [](const FunctionSummary::ParamAccess::Call &L,
942                          const FunctionSummary::ParamAccess::Call &R) {
943       return std::tie(L.ParamNo, L.Callee) < std::tie(R.ParamNo, R.Callee);
944     });
945   }
946   return ParamAccesses;
947 }
948 
949 StackSafetyGlobalInfo::StackSafetyGlobalInfo() = default;
950 
951 StackSafetyGlobalInfo::StackSafetyGlobalInfo(
952     Module *M, std::function<const StackSafetyInfo &(Function &F)> GetSSI,
953     const ModuleSummaryIndex *Index)
954     : M(M), GetSSI(GetSSI), Index(Index) {
955   if (StackSafetyRun)
956     getInfo();
957 }
958 
959 StackSafetyGlobalInfo::StackSafetyGlobalInfo(StackSafetyGlobalInfo &&) =
960     default;
961 
962 StackSafetyGlobalInfo &
963 StackSafetyGlobalInfo::operator=(StackSafetyGlobalInfo &&) = default;
964 
965 StackSafetyGlobalInfo::~StackSafetyGlobalInfo() = default;
966 
967 bool StackSafetyGlobalInfo::isSafe(const AllocaInst &AI) const {
968   const auto &Info = getInfo();
969   return Info.SafeAllocas.count(&AI);
970 }
971 
972 bool StackSafetyGlobalInfo::stackAccessIsSafe(const Instruction &I) const {
973   const auto &Info = getInfo();
974   return Info.UnsafeAccesses.find(&I) == Info.UnsafeAccesses.end();
975 }
976 
977 void StackSafetyGlobalInfo::print(raw_ostream &O) const {
978   auto &SSI = getInfo().Info;
979   if (SSI.empty())
980     return;
981   const Module &M = *SSI.begin()->first->getParent();
982   for (auto &F : M.functions()) {
983     if (!F.isDeclaration()) {
984       SSI.find(&F)->second.print(O, F.getName(), &F);
985       O << "    safe accesses:"
986         << "\n";
987       for (const auto &I : instructions(F)) {
988         const CallInst *Call = dyn_cast<CallInst>(&I);
989         if ((isa<StoreInst>(I) || isa<LoadInst>(I) || isa<MemIntrinsic>(I) ||
990              (Call && Call->hasByValArgument())) &&
991             stackAccessIsSafe(I)) {
992           O << "     " << I << "\n";
993         }
994       }
995       O << "\n";
996     }
997   }
998 }
999 
1000 LLVM_DUMP_METHOD void StackSafetyGlobalInfo::dump() const { print(dbgs()); }
1001 
1002 AnalysisKey StackSafetyAnalysis::Key;
1003 
1004 StackSafetyInfo StackSafetyAnalysis::run(Function &F,
1005                                          FunctionAnalysisManager &AM) {
1006   return StackSafetyInfo(&F, [&AM, &F]() -> ScalarEvolution & {
1007     return AM.getResult<ScalarEvolutionAnalysis>(F);
1008   });
1009 }
1010 
1011 PreservedAnalyses StackSafetyPrinterPass::run(Function &F,
1012                                               FunctionAnalysisManager &AM) {
1013   OS << "'Stack Safety Local Analysis' for function '" << F.getName() << "'\n";
1014   AM.getResult<StackSafetyAnalysis>(F).print(OS);
1015   return PreservedAnalyses::all();
1016 }
1017 
1018 char StackSafetyInfoWrapperPass::ID = 0;
1019 
1020 StackSafetyInfoWrapperPass::StackSafetyInfoWrapperPass() : FunctionPass(ID) {
1021   initializeStackSafetyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
1022 }
1023 
1024 void StackSafetyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1025   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
1026   AU.setPreservesAll();
1027 }
1028 
1029 void StackSafetyInfoWrapperPass::print(raw_ostream &O, const Module *M) const {
1030   SSI.print(O);
1031 }
1032 
1033 bool StackSafetyInfoWrapperPass::runOnFunction(Function &F) {
1034   auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1035   SSI = {&F, [SE]() -> ScalarEvolution & { return *SE; }};
1036   return false;
1037 }
1038 
1039 AnalysisKey StackSafetyGlobalAnalysis::Key;
1040 
1041 StackSafetyGlobalInfo
1042 StackSafetyGlobalAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
1043   // FIXME: Lookup Module Summary.
1044   FunctionAnalysisManager &FAM =
1045       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1046   return {&M,
1047           [&FAM](Function &F) -> const StackSafetyInfo & {
1048             return FAM.getResult<StackSafetyAnalysis>(F);
1049           },
1050           nullptr};
1051 }
1052 
1053 PreservedAnalyses StackSafetyGlobalPrinterPass::run(Module &M,
1054                                                     ModuleAnalysisManager &AM) {
1055   OS << "'Stack Safety Analysis' for module '" << M.getName() << "'\n";
1056   AM.getResult<StackSafetyGlobalAnalysis>(M).print(OS);
1057   return PreservedAnalyses::all();
1058 }
1059 
1060 char StackSafetyGlobalInfoWrapperPass::ID = 0;
1061 
1062 StackSafetyGlobalInfoWrapperPass::StackSafetyGlobalInfoWrapperPass()
1063     : ModulePass(ID) {
1064   initializeStackSafetyGlobalInfoWrapperPassPass(
1065       *PassRegistry::getPassRegistry());
1066 }
1067 
1068 StackSafetyGlobalInfoWrapperPass::~StackSafetyGlobalInfoWrapperPass() = default;
1069 
1070 void StackSafetyGlobalInfoWrapperPass::print(raw_ostream &O,
1071                                              const Module *M) const {
1072   SSGI.print(O);
1073 }
1074 
1075 void StackSafetyGlobalInfoWrapperPass::getAnalysisUsage(
1076     AnalysisUsage &AU) const {
1077   AU.setPreservesAll();
1078   AU.addRequired<StackSafetyInfoWrapperPass>();
1079 }
1080 
1081 bool StackSafetyGlobalInfoWrapperPass::runOnModule(Module &M) {
1082   const ModuleSummaryIndex *ImportSummary = nullptr;
1083   if (auto *IndexWrapperPass =
1084           getAnalysisIfAvailable<ImmutableModuleSummaryIndexWrapperPass>())
1085     ImportSummary = IndexWrapperPass->getIndex();
1086 
1087   SSGI = {&M,
1088           [this](Function &F) -> const StackSafetyInfo & {
1089             return getAnalysis<StackSafetyInfoWrapperPass>(F).getResult();
1090           },
1091           ImportSummary};
1092   return false;
1093 }
1094 
1095 bool llvm::needsParamAccessSummary(const Module &M) {
1096   if (StackSafetyRun)
1097     return true;
1098   for (auto &F : M.functions())
1099     if (F.hasFnAttribute(Attribute::SanitizeMemTag))
1100       return true;
1101   return false;
1102 }
1103 
1104 void llvm::generateParamAccessSummary(ModuleSummaryIndex &Index) {
1105   if (!Index.hasParamAccess())
1106     return;
1107   const ConstantRange FullSet(FunctionSummary::ParamAccess::RangeWidth, true);
1108 
1109   auto CountParamAccesses = [&](auto &Stat) {
1110     if (!AreStatisticsEnabled())
1111       return;
1112     for (auto &GVS : Index)
1113       for (auto &GV : GVS.second.SummaryList)
1114         if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GV.get()))
1115           Stat += FS->paramAccesses().size();
1116   };
1117 
1118   CountParamAccesses(NumCombinedParamAccessesBefore);
1119 
1120   std::map<const FunctionSummary *, FunctionInfo<FunctionSummary>> Functions;
1121 
1122   // Convert the ModuleSummaryIndex to a FunctionMap
1123   for (auto &GVS : Index) {
1124     for (auto &GV : GVS.second.SummaryList) {
1125       FunctionSummary *FS = dyn_cast<FunctionSummary>(GV.get());
1126       if (!FS || FS->paramAccesses().empty())
1127         continue;
1128       if (FS->isLive() && FS->isDSOLocal()) {
1129         FunctionInfo<FunctionSummary> FI;
1130         for (auto &PS : FS->paramAccesses()) {
1131           auto &US =
1132               FI.Params
1133                   .emplace(PS.ParamNo, FunctionSummary::ParamAccess::RangeWidth)
1134                   .first->second;
1135           US.Range = PS.Use;
1136           for (auto &Call : PS.Calls) {
1137             assert(!Call.Offsets.isFullSet());
1138             FunctionSummary *S =
1139                 findCalleeFunctionSummary(Call.Callee, FS->modulePath());
1140             ++NumCombinedCalleeLookupTotal;
1141             if (!S) {
1142               ++NumCombinedCalleeLookupFailed;
1143               US.Range = FullSet;
1144               US.Calls.clear();
1145               break;
1146             }
1147             US.Calls.emplace(CallInfo<FunctionSummary>(S, Call.ParamNo),
1148                              Call.Offsets);
1149           }
1150         }
1151         Functions.emplace(FS, std::move(FI));
1152       }
1153       // Reset data for all summaries. Alive and DSO local will be set back from
1154       // of data flow results below. Anything else will not be accessed
1155       // by ThinLTO backend, so we can save on bitcode size.
1156       FS->setParamAccesses({});
1157     }
1158   }
1159   NumCombinedDataFlowNodes += Functions.size();
1160   StackSafetyDataFlowAnalysis<FunctionSummary> SSDFA(
1161       FunctionSummary::ParamAccess::RangeWidth, std::move(Functions));
1162   for (auto &KV : SSDFA.run()) {
1163     std::vector<FunctionSummary::ParamAccess> NewParams;
1164     NewParams.reserve(KV.second.Params.size());
1165     for (auto &Param : KV.second.Params) {
1166       // It's not needed as FullSet is processed the same as a missing value.
1167       if (Param.second.Range.isFullSet())
1168         continue;
1169       NewParams.emplace_back();
1170       FunctionSummary::ParamAccess &New = NewParams.back();
1171       New.ParamNo = Param.first;
1172       New.Use = Param.second.Range; // Only range is needed.
1173     }
1174     const_cast<FunctionSummary *>(KV.first)->setParamAccesses(
1175         std::move(NewParams));
1176   }
1177 
1178   CountParamAccesses(NumCombinedParamAccessesAfter);
1179 }
1180 
1181 static const char LocalPassArg[] = "stack-safety-local";
1182 static const char LocalPassName[] = "Stack Safety Local Analysis";
1183 INITIALIZE_PASS_BEGIN(StackSafetyInfoWrapperPass, LocalPassArg, LocalPassName,
1184                       false, true)
1185 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1186 INITIALIZE_PASS_END(StackSafetyInfoWrapperPass, LocalPassArg, LocalPassName,
1187                     false, true)
1188 
1189 static const char GlobalPassName[] = "Stack Safety Analysis";
1190 INITIALIZE_PASS_BEGIN(StackSafetyGlobalInfoWrapperPass, DEBUG_TYPE,
1191                       GlobalPassName, false, true)
1192 INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass)
1193 INITIALIZE_PASS_DEPENDENCY(ImmutableModuleSummaryIndexWrapperPass)
1194 INITIALIZE_PASS_END(StackSafetyGlobalInfoWrapperPass, DEBUG_TYPE,
1195                     GlobalPassName, false, true)
1196