LLVM 24.0.0git
StackSafetyAnalysis.cpp
Go to the documentation of this file.
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
12#include "AnalysisOptions.h"
13#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/Statistic.h"
22#include "llvm/IR/GlobalValue.h"
24#include "llvm/IR/Instruction.h"
33#include <algorithm>
34#include <tuple>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "stack-safety"
39
40STATISTIC(NumAllocaStackSafe, "Number of safe allocas");
41STATISTIC(NumAllocaTotal, "Number of total allocas");
42
43STATISTIC(NumCombinedCalleeLookupTotal,
44 "Number of total callee lookups on combined index.");
45STATISTIC(NumCombinedCalleeLookupFailed,
46 "Number of failed callee lookups on combined index.");
47STATISTIC(NumModuleCalleeLookupTotal,
48 "Number of total callee lookups on module index.");
49STATISTIC(NumModuleCalleeLookupFailed,
50 "Number of failed callee lookups on module index.");
51STATISTIC(NumCombinedParamAccessesBefore,
52 "Number of total param accesses before generateParamAccessSummary.");
53STATISTIC(NumCombinedParamAccessesAfter,
54 "Number of total param accesses after generateParamAccessSummary.");
55STATISTIC(NumCombinedDataFlowNodes,
56 "Number of total nodes in combined index for dataflow processing.");
57STATISTIC(NumIndexCalleeUnhandled, "Number of index callee which are unhandled.");
58STATISTIC(NumIndexCalleeMultipleWeak, "Number of index callee non-unique weak.");
59STATISTIC(NumIndexCalleeMultipleExternal, "Number of index callee non-unique external.");
60
61
62namespace {
63
64// Check if we should bailout for such ranges.
65bool isUnsafe(const ConstantRange &R) {
66 return R.isEmptySet() || R.isFullSet() || R.isUpperSignWrapped();
67}
68
69ConstantRange addOverflowNever(const ConstantRange &L, const ConstantRange &R) {
70 assert(!L.isSignWrappedSet());
71 assert(!R.isSignWrappedSet());
72 if (L.signedAddMayOverflow(R) !=
74 return ConstantRange::getFull(L.getBitWidth());
75 ConstantRange Result = L.add(R);
76 assert(!Result.isSignWrappedSet());
77 return Result;
78}
79
80ConstantRange unionNoWrap(const ConstantRange &L, const ConstantRange &R) {
81 assert(!L.isSignWrappedSet());
82 assert(!R.isSignWrappedSet());
83 auto Result = L.unionWith(R);
84 // Two non-wrapped sets can produce wrapped.
85 if (Result.isSignWrappedSet())
86 Result = ConstantRange::getFull(Result.getBitWidth());
87 return Result;
88}
89
90/// Describes use of address in as a function call argument.
91template <typename CalleeTy> struct CallInfo {
92 /// Function being called.
93 const CalleeTy *Callee = nullptr;
94 /// Index of argument which pass address.
95 size_t ParamNo = 0;
96
97 CallInfo(const CalleeTy *Callee, size_t ParamNo)
98 : Callee(Callee), ParamNo(ParamNo) {}
99
100 struct Less {
101 bool operator()(const CallInfo &L, const CallInfo &R) const {
102 return std::tie(L.ParamNo, L.Callee) < std::tie(R.ParamNo, R.Callee);
103 }
104 };
105};
106
107/// Describe uses of address (alloca or parameter) inside of the function.
108template <typename CalleeTy> struct UseInfo {
109 // Access range if the address (alloca or parameters).
110 // It is allowed to be empty-set when there are no known accesses.
111 ConstantRange Range;
112 std::set<const Instruction *> UnsafeAccesses;
113
114 // List of calls which pass address as an argument.
115 // Value is offset range of address from base address (alloca or calling
116 // function argument). Range should never set to empty-set, that is an invalid
117 // access range that can cause empty-set to be propagated with
118 // ConstantRange::add
119 using CallsTy = std::map<CallInfo<CalleeTy>, ConstantRange,
120 typename CallInfo<CalleeTy>::Less>;
121 CallsTy Calls;
122
123 UseInfo(unsigned PointerSize) : Range{PointerSize, false} {}
124
125 void updateRange(const ConstantRange &R) { Range = unionNoWrap(Range, R); }
126 void addRange(const Instruction *I, const ConstantRange &R, bool IsSafe) {
127 if (!IsSafe)
128 UnsafeAccesses.insert(I);
129 updateRange(R);
130 }
131};
132
133template <typename CalleeTy>
134raw_ostream &operator<<(raw_ostream &OS, const UseInfo<CalleeTy> &U) {
135 OS << U.Range;
136 for (auto &Call : U.Calls)
137 OS << ", "
138 << "@" << Call.first.Callee->getName() << "(arg" << Call.first.ParamNo
139 << ", " << Call.second << ")";
140 return OS;
141}
142
143/// Calculate the allocation size of a given alloca. Returns empty range
144// in case of confution.
145ConstantRange getStaticAllocaSizeRange(const AllocaInst &AI) {
146 const DataLayout &DL = AI.getDataLayout();
148 unsigned PointerSize = DL.getPointerTypeSizeInBits(AI.getType());
149 // Fallback to empty range for alloca size.
150 ConstantRange R = ConstantRange::getEmpty(PointerSize);
151 if (TS.isScalable())
152 return R;
153 APInt APSize(PointerSize, TS.getFixedValue(), true);
154 if (APSize.isNonPositive())
155 return R;
156 if (AI.isArrayAllocation()) {
157 const auto *C = dyn_cast<ConstantInt>(AI.getArraySize());
158 if (!C)
159 return R;
160 bool Overflow = false;
161 APInt Mul = C->getValue();
162 if (Mul.isNonPositive())
163 return R;
164 Mul = Mul.sextOrTrunc(PointerSize);
165 APSize = APSize.smul_ov(Mul, Overflow);
166 if (Overflow)
167 return R;
168 }
169 R = ConstantRange(APInt::getZero(PointerSize), APSize);
170 assert(!isUnsafe(R));
171 return R;
172}
173
174template <typename CalleeTy> struct FunctionInfo {
175 std::map<const AllocaInst *, UseInfo<CalleeTy>> Allocas;
176 std::map<uint32_t, UseInfo<CalleeTy>> Params;
177 // TODO: describe return value as depending on one or more of its arguments.
178
179 // StackSafetyDataFlowAnalysis counter stored here for faster access.
180 int UpdateCount = 0;
181
182 void print(raw_ostream &O, StringRef Name, const Function *F) const {
183 // TODO: Consider different printout format after
184 // StackSafetyDataFlowAnalysis. Calls and parameters are irrelevant then.
185 O << " @" << Name << ((F && F->isDSOLocal()) ? "" : " dso_preemptable")
186 << ((F && F->isInterposable()) ? " interposable" : "") << "\n";
187
188 O << " args uses:\n";
189 for (auto &KV : Params) {
190 O << " ";
191 if (F)
192 O << F->getArg(KV.first)->getName();
193 else
194 O << formatv("arg{0}", KV.first);
195 O << "[]: " << KV.second << "\n";
196 }
197
198 O << " allocas uses:\n";
199 if (F) {
200 for (const auto &I : instructions(F)) {
201 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
202 auto &AS = Allocas.find(AI)->second;
203 O << " " << AI->getName() << "["
204 << getStaticAllocaSizeRange(*AI).getUpper() << "]: " << AS << "\n";
205 }
206 }
207 } else {
208 assert(Allocas.empty());
209 }
210 }
211};
212
213using GVToSSI = std::map<const GlobalValue *, FunctionInfo<GlobalValue>>;
214
215} // namespace
216
218 FunctionInfo<GlobalValue> Info;
219};
220
226
227namespace {
228
229class StackSafetyLocalAnalysis {
230 Function &F;
231 const DataLayout &DL;
232 ScalarEvolution &SE;
233 unsigned PointerSize = 0;
234
235 const ConstantRange UnknownRange;
236
237 /// FIXME: This function is a bandaid, it's only needed
238 /// because this pass doesn't handle address spaces of different pointer
239 /// sizes.
240 ///
241 /// \returns \p Val's SCEV as a pointer of AS zero, or nullptr if it can't be
242 /// converted to AS 0.
243 const SCEV *getSCEVAsPointer(Value *Val);
244
245 ConstantRange offsetFrom(Value *Addr, Value *Base);
246 ConstantRange getAccessRange(Value *Addr, Value *Base,
247 const ConstantRange &SizeRange);
248 ConstantRange getAccessRange(Value *Addr, Value *Base, TypeSize Size);
249 ConstantRange getMemIntrinsicAccessRange(const MemIntrinsic *MI, const Use &U,
250 Value *Base);
251
252 void analyzeAllUses(Value *Ptr, UseInfo<GlobalValue> &AS,
253 const StackLifetime &SL);
254
255
256 bool isSafeAccess(const Use &U, AllocaInst *AI, const SCEV *AccessSize);
257 bool isSafeAccess(const Use &U, AllocaInst *AI, Value *V);
258 bool isSafeAccess(const Use &U, AllocaInst *AI, TypeSize AccessSize);
259
260public:
261 StackSafetyLocalAnalysis(Function &F, ScalarEvolution &SE)
262 : F(F), DL(F.getDataLayout()), SE(SE),
263 PointerSize(DL.getPointerSizeInBits()),
264 UnknownRange(PointerSize, true) {}
265
266 // Run the transformation on the associated function.
267 FunctionInfo<GlobalValue> run();
268};
269
270const SCEV *StackSafetyLocalAnalysis::getSCEVAsPointer(Value *Val) {
271 Type *ValTy = Val->getType();
272
273 // We don't handle targets with multiple address spaces.
274 if (!ValTy->isPointerTy()) {
275 auto *PtrTy = PointerType::getUnqual(SE.getContext());
276 return SE.getTruncateOrZeroExtend(SE.getSCEV(Val), PtrTy);
277 }
278
279 if (ValTy->getPointerAddressSpace() != 0)
280 return nullptr;
281 return SE.getSCEV(Val);
282}
283
284ConstantRange StackSafetyLocalAnalysis::offsetFrom(Value *Addr, Value *Base) {
285 if (!SE.isSCEVable(Addr->getType()) || !SE.isSCEVable(Base->getType()))
286 return UnknownRange;
287
288 const SCEV *AddrExp = getSCEVAsPointer(Addr);
289 const SCEV *BaseExp = getSCEVAsPointer(Base);
290 if (!AddrExp || !BaseExp)
291 return UnknownRange;
292
293 const SCEV *Diff = SE.getMinusSCEV(AddrExp, BaseExp);
294 if (isa<SCEVCouldNotCompute>(Diff))
295 return UnknownRange;
296
297 ConstantRange Offset = SE.getSignedRange(Diff);
298 if (isUnsafe(Offset))
299 return UnknownRange;
300 return Offset.sextOrTrunc(PointerSize);
301}
302
303ConstantRange
304StackSafetyLocalAnalysis::getAccessRange(Value *Addr, Value *Base,
305 const ConstantRange &SizeRange) {
306 // Zero-size loads and stores do not access memory.
307 if (SizeRange.isEmptySet())
308 return ConstantRange::getEmpty(PointerSize);
309 assert(!isUnsafe(SizeRange));
310
311 ConstantRange Offsets = offsetFrom(Addr, Base);
312 if (isUnsafe(Offsets))
313 return UnknownRange;
314
315 Offsets = addOverflowNever(Offsets, SizeRange);
316 if (isUnsafe(Offsets))
317 return UnknownRange;
318 return Offsets;
319}
320
321ConstantRange StackSafetyLocalAnalysis::getAccessRange(Value *Addr, Value *Base,
322 TypeSize Size) {
323 if (Size.isScalable())
324 return UnknownRange;
325 APInt APSize(PointerSize, Size.getFixedValue(), true);
326 if (APSize.isNegative())
327 return UnknownRange;
328 return getAccessRange(Addr, Base,
329 ConstantRange(APInt::getZero(PointerSize), APSize));
330}
331
332ConstantRange StackSafetyLocalAnalysis::getMemIntrinsicAccessRange(
333 const MemIntrinsic *MI, const Use &U, Value *Base) {
334 if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
335 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
336 return ConstantRange::getEmpty(PointerSize);
337 } else {
338 if (MI->getRawDest() != U)
339 return ConstantRange::getEmpty(PointerSize);
340 }
341
342 auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
343 if (!SE.isSCEVable(MI->getLength()->getType()))
344 return UnknownRange;
345
346 const SCEV *Expr =
347 SE.getTruncateOrZeroExtend(SE.getSCEV(MI->getLength()), CalculationTy);
348 ConstantRange Sizes = SE.getSignedRange(Expr);
349 if (!Sizes.getUpper().isStrictlyPositive() || isUnsafe(Sizes))
350 return UnknownRange;
351 Sizes = Sizes.sextOrTrunc(PointerSize);
352 ConstantRange SizeRange(APInt::getZero(PointerSize), Sizes.getUpper() - 1);
353 return getAccessRange(U, Base, SizeRange);
354}
355
356bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
357 Value *V) {
358 return isSafeAccess(U, AI, SE.getSCEV(V));
359}
360
361bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
362 TypeSize TS) {
363 if (TS.isScalable())
364 return false;
365 auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
366 const SCEV *SV = SE.getConstant(CalculationTy, TS.getFixedValue());
367 return isSafeAccess(U, AI, SV);
368}
369
370bool StackSafetyLocalAnalysis::isSafeAccess(const Use &U, AllocaInst *AI,
371 const SCEV *AccessSize) {
372
373 if (!AI)
374 return true; // This only judges whether it is a safe *stack* access.
375 if (isa<SCEVCouldNotCompute>(AccessSize))
376 return false;
377
378 const auto *I = cast<Instruction>(U.getUser());
379
380 const SCEV *AddrExp = getSCEVAsPointer(U.get());
381 const SCEV *BaseExp = getSCEVAsPointer(AI);
382 if (!AddrExp || !BaseExp)
383 return false;
384
385 const SCEV *Diff = SE.getMinusSCEV(AddrExp, BaseExp);
386 if (isa<SCEVCouldNotCompute>(Diff))
387 return false;
388
389 auto Size = getStaticAllocaSizeRange(*AI);
390
391 auto *CalculationTy = IntegerType::getIntNTy(SE.getContext(), PointerSize);
392 auto ToDiffTy = [&](const SCEV *V) {
393 return SE.getTruncateOrZeroExtend(V, CalculationTy);
394 };
395 const SCEV *Min = ToDiffTy(SE.getConstant(Size.getLower()));
396 const SCEV *Max = SE.getMinusSCEV(ToDiffTy(SE.getConstant(Size.getUpper())),
397 ToDiffTy(AccessSize));
398 return SE.evaluatePredicateAt(ICmpInst::Predicate::ICMP_SGE, Diff, Min, I)
399 .value_or(false) &&
400 SE.evaluatePredicateAt(ICmpInst::Predicate::ICMP_SLE, Diff, Max, I)
401 .value_or(false);
402}
403
404/// The function analyzes all local uses of Ptr (alloca or argument) and
405/// calculates local access range and all function calls where it was used.
406void StackSafetyLocalAnalysis::analyzeAllUses(Value *Ptr,
407 UseInfo<GlobalValue> &US,
408 const StackLifetime &SL) {
409 SmallPtrSet<const Value *, 16> Visited;
410 SmallVector<const Value *, 8> WorkList;
411 WorkList.push_back(Ptr);
412 AllocaInst *AI = dyn_cast<AllocaInst>(Ptr);
413
414 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
415 while (!WorkList.empty()) {
416 const Value *V = WorkList.pop_back_val();
417 for (const Use &UI : V->uses()) {
418 const auto *I = cast<Instruction>(UI.getUser());
419 if (!SL.isReachable(I))
420 continue;
421
422 assert(V == UI.get());
423
424 auto RecordStore = [&](const Value* StoredVal) {
425 if (V == StoredVal) {
426 // Stored the pointer - conservatively assume it may be unsafe.
427 US.addRange(I, UnknownRange, /*IsSafe=*/false);
428 return;
429 }
430 if (AI && !SL.isAliveAfter(AI, I)) {
431 US.addRange(I, UnknownRange, /*IsSafe=*/false);
432 return;
433 }
434 auto TypeSize = DL.getTypeStoreSize(StoredVal->getType());
435 auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
436 bool Safe = isSafeAccess(UI, AI, TypeSize);
437 US.addRange(I, AccessRange, Safe);
438 return;
439 };
440
441 switch (I->getOpcode()) {
442 case Instruction::Load: {
443 if (AI && !SL.isAliveAfter(AI, I)) {
444 US.addRange(I, UnknownRange, /*IsSafe=*/false);
445 break;
446 }
447 auto TypeSize = DL.getTypeStoreSize(I->getType());
448 auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
449 bool Safe = isSafeAccess(UI, AI, TypeSize);
450 US.addRange(I, AccessRange, Safe);
451 break;
452 }
453
454 case Instruction::VAArg:
455 // "va-arg" from a pointer is safe.
456 break;
457 case Instruction::Store:
458 RecordStore(cast<StoreInst>(I)->getValueOperand());
459 break;
460 case Instruction::AtomicCmpXchg:
461 RecordStore(cast<AtomicCmpXchgInst>(I)->getNewValOperand());
462 break;
463 case Instruction::AtomicRMW:
464 RecordStore(cast<AtomicRMWInst>(I)->getValOperand());
465 break;
466
467 case Instruction::Ret:
468 // Information leak.
469 // FIXME: Process parameters correctly. This is a leak only if we return
470 // alloca.
471 US.addRange(I, UnknownRange, /*IsSafe=*/false);
472 break;
473
474 case Instruction::Call:
475 case Instruction::Invoke: {
476 if (I->isLifetimeStartOrEnd())
477 break;
478
479 if (AI && !SL.isAliveAfter(AI, I)) {
480 US.addRange(I, UnknownRange, /*IsSafe=*/false);
481 break;
482 }
483 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
484 auto AccessRange = getMemIntrinsicAccessRange(MI, UI, Ptr);
485 bool Safe = false;
486 if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
487 if (MTI->getRawSource() != UI && MTI->getRawDest() != UI)
488 Safe = true;
489 } else if (MI->getRawDest() != UI) {
490 Safe = true;
491 }
492 Safe = Safe || isSafeAccess(UI, AI, MI->getLength());
493 US.addRange(I, AccessRange, Safe);
494 break;
495 }
496
497 const auto &CB = cast<CallBase>(*I);
498 if (CB.getReturnedArgOperand() == V) {
499 if (Visited.insert(I).second)
501 }
502
503 if (!CB.isArgOperand(&UI)) {
504 US.addRange(I, UnknownRange, /*IsSafe=*/false);
505 break;
506 }
507
508 unsigned ArgNo = CB.getArgOperandNo(&UI);
509 if (CB.isByValArgument(ArgNo)) {
510 auto TypeSize = DL.getTypeStoreSize(CB.getParamByValType(ArgNo));
511 auto AccessRange = getAccessRange(UI, Ptr, TypeSize);
512 bool Safe = isSafeAccess(UI, AI, TypeSize);
513 US.addRange(I, AccessRange, Safe);
514 break;
515 }
516
517 // FIXME: consult devirt?
518 // Do not follow aliases, otherwise we could inadvertently follow
519 // dso_preemptable aliases or aliases with interposable linkage.
520 const GlobalValue *Callee =
521 dyn_cast<GlobalValue>(CB.getCalledOperand()->stripPointerCasts());
522 if (!Callee || isa<GlobalIFunc>(Callee) ||
523 isa<GlobalVariable>(Callee)) {
524 US.addRange(I, UnknownRange, /*IsSafe=*/false);
525 break;
526 }
527
528 assert(isa<Function>(Callee) || isa<GlobalAlias>(Callee));
529 ConstantRange Offsets = offsetFrom(UI, Ptr);
530 auto Insert =
531 US.Calls.emplace(CallInfo<GlobalValue>(Callee, ArgNo), Offsets);
532 if (!Insert.second)
533 Insert.first->second = Insert.first->second.unionWith(Offsets);
534 break;
535 }
536
537 default:
538 if (Visited.insert(I).second)
540 }
541 }
542 }
543}
544
545FunctionInfo<GlobalValue> StackSafetyLocalAnalysis::run() {
546 FunctionInfo<GlobalValue> Info;
547 assert(!F.isDeclaration() &&
548 "Can't run StackSafety on a function declaration");
549
550 LLVM_DEBUG(dbgs() << "[StackSafety] " << F.getName() << "\n");
551
553 for (auto &I : instructions(F))
554 if (auto *AI = dyn_cast<AllocaInst>(&I))
555 Allocas.push_back(AI);
556 StackLifetime SL(F, Allocas, StackLifetime::LivenessType::Must);
557 SL.run();
558
559 for (auto *AI : Allocas) {
560 auto &UI = Info.Allocas.emplace(AI, PointerSize).first->second;
561 analyzeAllUses(AI, UI, SL);
562 }
563
564 for (Argument &A : F.args()) {
565 // Non pointers and bypass arguments are not going to be used in any global
566 // processing.
567 if (A.getType()->isPointerTy() && !A.hasByValAttr()) {
568 auto &UI = Info.Params.emplace(A.getArgNo(), PointerSize).first->second;
569 analyzeAllUses(&A, UI, SL);
570 }
571 }
572
573 LLVM_DEBUG(Info.print(dbgs(), F.getName(), &F));
574 LLVM_DEBUG(dbgs() << "\n[StackSafety] done\n");
575 return Info;
576}
577
578template <typename CalleeTy> class StackSafetyDataFlowAnalysis {
579 using FunctionMap = std::map<const CalleeTy *, FunctionInfo<CalleeTy>>;
580
581 FunctionMap Functions;
582 const ConstantRange UnknownRange;
583 const int MaxIterations;
584
585 // Callee-to-Caller multimap.
586 DenseMap<const CalleeTy *, SmallVector<const CalleeTy *, 4>> Callers;
587 SetVector<const CalleeTy *> WorkList;
588
589 bool updateOneUse(UseInfo<CalleeTy> &US, bool UpdateToFullSet);
590 void updateOneNode(const CalleeTy *Callee, FunctionInfo<CalleeTy> &FS);
591 void updateOneNode(const CalleeTy *Callee) {
592 updateOneNode(Callee, Functions.find(Callee)->second);
593 }
594 void updateAllNodes() {
595 for (auto &F : Functions)
596 updateOneNode(F.first, F.second);
597 }
598 void runDataFlow();
599#ifndef NDEBUG
600 void verifyFixedPoint();
601#endif
602
603public:
604 StackSafetyDataFlowAnalysis(uint32_t PointerBitWidth, FunctionMap Functions,
605 int MaxIterations)
606 : Functions(std::move(Functions)),
607 UnknownRange(ConstantRange::getFull(PointerBitWidth)),
608 MaxIterations(MaxIterations) {}
609
610 const FunctionMap &run();
611
612 ConstantRange getArgumentAccessRange(const CalleeTy *Callee, unsigned ParamNo,
613 const ConstantRange &Offsets) const;
614};
615
616template <typename CalleeTy>
617ConstantRange StackSafetyDataFlowAnalysis<CalleeTy>::getArgumentAccessRange(
618 const CalleeTy *Callee, unsigned ParamNo,
619 const ConstantRange &Offsets) const {
620 auto FnIt = Functions.find(Callee);
621 // Unknown callee (outside of LTO domain or an indirect call).
622 if (FnIt == Functions.end())
623 return UnknownRange;
624 auto &FS = FnIt->second;
625 auto ParamIt = FS.Params.find(ParamNo);
626 if (ParamIt == FS.Params.end())
627 return UnknownRange;
628 auto &Access = ParamIt->second.Range;
629 if (Access.isEmptySet())
630 return Access;
631 if (Access.isFullSet())
632 return UnknownRange;
633 return addOverflowNever(Access, Offsets);
634}
635
636template <typename CalleeTy>
637bool StackSafetyDataFlowAnalysis<CalleeTy>::updateOneUse(UseInfo<CalleeTy> &US,
638 bool UpdateToFullSet) {
639 bool Changed = false;
640 for (auto &KV : US.Calls) {
641 assert(!KV.second.isEmptySet() &&
642 "Param range can't be empty-set, invalid offset range");
643
644 ConstantRange CalleeRange =
645 getArgumentAccessRange(KV.first.Callee, KV.first.ParamNo, KV.second);
646 if (!US.Range.contains(CalleeRange)) {
647 Changed = true;
648 if (UpdateToFullSet)
649 US.Range = UnknownRange;
650 else
651 US.updateRange(CalleeRange);
652 }
653 }
654 return Changed;
655}
656
657template <typename CalleeTy>
658void StackSafetyDataFlowAnalysis<CalleeTy>::updateOneNode(
659 const CalleeTy *Callee, FunctionInfo<CalleeTy> &FS) {
660 bool UpdateToFullSet = FS.UpdateCount > MaxIterations;
661 bool Changed = false;
662 for (auto &KV : FS.Params)
663 Changed |= updateOneUse(KV.second, UpdateToFullSet);
664
665 if (Changed) {
666 LLVM_DEBUG(dbgs() << "=== update [" << FS.UpdateCount
667 << (UpdateToFullSet ? ", full-set" : "") << "] " << &FS
668 << "\n");
669 // Callers of this function may need updating.
670 WorkList.insert_range(Callers[Callee]);
671
672 ++FS.UpdateCount;
673 }
674}
675
676template <typename CalleeTy>
677void StackSafetyDataFlowAnalysis<CalleeTy>::runDataFlow() {
679 for (auto &F : Functions) {
680 Callees.clear();
681 auto &FS = F.second;
682 for (auto &KV : FS.Params)
683 for (auto &CS : KV.second.Calls)
684 Callees.push_back(CS.first.Callee);
685
686 llvm::sort(Callees);
687 Callees.erase(llvm::unique(Callees), Callees.end());
688
689 for (auto &Callee : Callees)
690 Callers[Callee].push_back(F.first);
691 }
692
693 updateAllNodes();
694
695 while (!WorkList.empty()) {
696 const CalleeTy *Callee = WorkList.pop_back_val();
697 updateOneNode(Callee);
698 }
699}
700
701#ifndef NDEBUG
702template <typename CalleeTy>
703void StackSafetyDataFlowAnalysis<CalleeTy>::verifyFixedPoint() {
704 WorkList.clear();
705 updateAllNodes();
706 assert(WorkList.empty());
707}
708#endif
709
710template <typename CalleeTy>
711const typename StackSafetyDataFlowAnalysis<CalleeTy>::FunctionMap &
712StackSafetyDataFlowAnalysis<CalleeTy>::run() {
713 runDataFlow();
714 LLVM_DEBUG(verifyFixedPoint());
715 return Functions;
716}
717
718FunctionSummary *findCalleeFunctionSummary(ValueInfo VI, StringRef ModuleId) {
719 if (!VI)
720 return nullptr;
721 auto SummaryList = VI.getSummaryList();
722 GlobalValueSummary* S = nullptr;
723 for (const auto& GVS : SummaryList) {
724 if (!GVS->isLive())
725 continue;
726 if (const AliasSummary *AS = dyn_cast<AliasSummary>(GVS.get()))
727 if (!AS->hasAliasee())
728 continue;
729 if (!isa<FunctionSummary>(GVS->getBaseObject()))
730 continue;
731 if (GlobalValue::isLocalLinkage(GVS->linkage())) {
732 if (GVS->modulePath() == ModuleId) {
733 S = GVS.get();
734 break;
735 }
736 } else if (GlobalValue::isExternalLinkage(GVS->linkage())) {
737 if (S) {
738 ++NumIndexCalleeMultipleExternal;
739 return nullptr;
740 }
741 S = GVS.get();
742 } else if (GlobalValue::isWeakLinkage(GVS->linkage())) {
743 if (S) {
744 ++NumIndexCalleeMultipleWeak;
745 return nullptr;
746 }
747 S = GVS.get();
748 } else if (GlobalValue::isAvailableExternallyLinkage(GVS->linkage()) ||
749 GlobalValue::isLinkOnceLinkage(GVS->linkage())) {
750 if (SummaryList.size() == 1)
751 S = GVS.get();
752 // According thinLTOResolvePrevailingGUID these are unlikely prevailing.
753 } else {
754 ++NumIndexCalleeUnhandled;
755 }
756 };
757 while (S) {
758 if (!S->isLive() || !S->isDSOLocal())
759 return nullptr;
760 if (FunctionSummary *FS = dyn_cast<FunctionSummary>(S))
761 return FS;
762 AliasSummary *AS = dyn_cast<AliasSummary>(S);
763 if (!AS || !AS->hasAliasee())
764 return nullptr;
765 S = AS->getBaseObject();
766 if (S == AS)
767 return nullptr;
768 }
769 return nullptr;
770}
771
772const Function *findCalleeInModule(const GlobalValue *GV) {
773 while (GV) {
774 if (GV->isDeclaration() || GV->isInterposable() || !GV->isDSOLocal())
775 return nullptr;
776 if (const Function *F = dyn_cast<Function>(GV))
777 return F;
778 const GlobalAlias *A = dyn_cast<GlobalAlias>(GV);
779 if (!A)
780 return nullptr;
781 GV = A->getAliaseeObject();
782 if (GV == A)
783 return nullptr;
784 }
785 return nullptr;
786}
787
788const ConstantRange *findParamAccess(const FunctionSummary &FS,
789 uint32_t ParamNo) {
790 assert(FS.isLive());
791 assert(FS.isDSOLocal());
792 for (const auto &PS : FS.paramAccesses())
793 if (ParamNo == PS.ParamNo)
794 return &PS.Use;
795 return nullptr;
796}
797
798void resolveAllCalls(UseInfo<GlobalValue> &Use,
799 const ModuleSummaryIndex *Index) {
800 ConstantRange FullSet(Use.Range.getBitWidth(), true);
801 // Move Use.Calls to a temp storage and repopulate - don't use std::move as it
802 // leaves Use.Calls in an undefined state.
803 UseInfo<GlobalValue>::CallsTy TmpCalls;
804 std::swap(TmpCalls, Use.Calls);
805 for (const auto &C : TmpCalls) {
806 const Function *F = findCalleeInModule(C.first.Callee);
807 if (F) {
808 Use.Calls.emplace(CallInfo<GlobalValue>(F, C.first.ParamNo), C.second);
809 continue;
810 }
811
812 if (!Index)
813 return Use.updateRange(FullSet);
814 FunctionSummary *FS =
815 findCalleeFunctionSummary(Index->getValueInfo(C.first.Callee->getGUID()),
816 C.first.Callee->getParent()->getModuleIdentifier());
817 ++NumModuleCalleeLookupTotal;
818 if (!FS) {
819 ++NumModuleCalleeLookupFailed;
820 return Use.updateRange(FullSet);
821 }
822 const ConstantRange *Found = findParamAccess(*FS, C.first.ParamNo);
823 if (!Found || Found->isFullSet())
824 return Use.updateRange(FullSet);
825 ConstantRange Access = Found->sextOrTrunc(Use.Range.getBitWidth());
826 if (!Access.isEmptySet())
827 Use.updateRange(addOverflowNever(Access, C.second));
828 }
829}
830
831GVToSSI createGlobalStackSafetyInfo(
832 std::map<const GlobalValue *, FunctionInfo<GlobalValue>> Functions,
833 const ModuleSummaryIndex *Index) {
834 GVToSSI SSI;
835 if (Functions.empty())
836 return SSI;
837
838 // FIXME: Simplify printing and remove copying here.
839 auto Copy = Functions;
840
841 for (auto &FnKV : Copy)
842 for (auto &KV : FnKV.second.Params) {
843 resolveAllCalls(KV.second, Index);
844 if (KV.second.Range.isFullSet())
845 KV.second.Calls.clear();
846 }
847
848 uint32_t PointerSize =
849 Copy.begin()->first->getDataLayout().getPointerSizeInBits();
850 int MaxIterations = getAnalysisOptions(Copy.begin()->first->getContext())
851 .stack_safety_max_iterations;
852 StackSafetyDataFlowAnalysis<GlobalValue> SSDFA(PointerSize, std::move(Copy),
853 MaxIterations);
854
855 for (const auto &F : SSDFA.run()) {
856 auto FI = F.second;
857 auto &SrcF = Functions[F.first];
858 for (auto &KV : FI.Allocas) {
859 auto &A = KV.second;
860 resolveAllCalls(A, Index);
861 for (auto &C : A.Calls) {
862 A.updateRange(SSDFA.getArgumentAccessRange(C.first.Callee,
863 C.first.ParamNo, C.second));
864 }
865 // FIXME: This is needed only to preserve calls in print() results.
866 A.Calls = SrcF.Allocas.find(KV.first)->second.Calls;
867 }
868 for (auto &KV : FI.Params) {
869 auto &P = KV.second;
870 P.Calls = SrcF.Params.find(KV.first)->second.Calls;
871 }
872 SSI[F.first] = std::move(FI);
873 }
874
875 return SSI;
876}
877
878} // end anonymous namespace
879
881
883 std::function<ScalarEvolution &()> GetSE)
884 : F(F), GetSE(GetSE) {}
885
887
889
891
893 if (!Info) {
894 StackSafetyLocalAnalysis SSLA(*F, GetSE());
895 Info.reset(new InfoTy{SSLA.run()});
896 }
897 return *Info;
898}
899
901 getInfo().Info.print(O, F->getName(), F);
902 O << "\n";
903}
904
905const StackSafetyGlobalInfo::InfoTy &StackSafetyGlobalInfo::getInfo() const {
906 if (!Info) {
907 std::map<const GlobalValue *, FunctionInfo<GlobalValue>> Functions;
908 for (auto &F : M->functions()) {
909 if (!F.isDeclaration()) {
910 auto FI = GetSSI(F).getInfo().Info;
911 Functions.emplace(&F, std::move(FI));
912 }
913 }
914 Info.reset(new InfoTy{
915 createGlobalStackSafetyInfo(std::move(Functions), Index), {}, {}});
916
917 for (auto &FnKV : Info->Info) {
918 for (auto &KV : FnKV.second.Allocas) {
919 ++NumAllocaTotal;
920 const AllocaInst *AI = KV.first;
921 auto AIRange = getStaticAllocaSizeRange(*AI);
922 if (AIRange.contains(KV.second.Range)) {
923 Info->SafeAllocas.insert(AI);
924 ++NumAllocaStackSafe;
925 }
926 Info->UnsafeAccesses.insert(KV.second.UnsafeAccesses.begin(),
927 KV.second.UnsafeAccesses.end());
928 }
929 }
930
931 if (getAnalysisOptions(*M).stack_safety_print)
932 print(errs());
933 }
934 return *Info;
935}
936
937std::vector<FunctionSummary::ParamAccess>
939 // Implementation transforms internal representation of parameter information
940 // into FunctionSummary format.
941 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
942 for (const auto &KV : getInfo().Info.Params) {
943 auto &PS = KV.second;
944 // Parameter accessed by any or unknown offset, represented as FullSet by
945 // StackSafety, is handled as the parameter for which we have no
946 // StackSafety info at all. So drop it to reduce summary size.
947 if (PS.Range.isFullSet())
948 continue;
949
950 ParamAccesses.emplace_back(KV.first, PS.Range);
951 FunctionSummary::ParamAccess &Param = ParamAccesses.back();
952
953 Param.Calls.reserve(PS.Calls.size());
954 for (const auto &C : PS.Calls) {
955 // Parameter forwarded into another function by any or unknown offset
956 // will make ParamAccess::Range as FullSet anyway. So we can drop the
957 // entire parameter like we did above.
958 // TODO(vitalybuka): Return already filtered parameters from getInfo().
959 if (C.second.isFullSet()) {
960 ParamAccesses.pop_back();
961 break;
962 }
963 Param.Calls.emplace_back(C.first.ParamNo,
964 Index.getOrInsertValueInfo(C.first.Callee),
965 C.second);
966 }
967 }
968 for (FunctionSummary::ParamAccess &Param : ParamAccesses) {
969 sort(Param.Calls, [](const FunctionSummary::ParamAccess::Call &L,
971 return std::tie(L.ParamNo, L.Callee) < std::tie(R.ParamNo, R.Callee);
972 });
973 }
974 return ParamAccesses;
975}
976
978
980 Module *M, std::function<const StackSafetyInfo &(Function &F)> GetSSI,
981 const ModuleSummaryIndex *Index)
982 : M(M), GetSSI(GetSSI), Index(Index) {
983 if (getAnalysisOptions(*M).stack_safety_run)
984 getInfo();
985}
986
988 default;
989
992
994
996 const auto &Info = getInfo();
997 return Info.SafeAllocas.count(&AI);
998}
999
1001 const auto &Info = getInfo();
1002 return Info.UnsafeAccesses.find(&I) == Info.UnsafeAccesses.end();
1003}
1004
1006 auto &SSI = getInfo().Info;
1007 if (SSI.empty())
1008 return;
1009 const Module &M = *SSI.begin()->first->getParent();
1010 for (const auto &F : M.functions()) {
1011 if (!F.isDeclaration()) {
1012 SSI.find(&F)->second.print(O, F.getName(), &F);
1013 O << " safe accesses:"
1014 << "\n";
1015 for (const auto &I : instructions(F)) {
1016 const CallInst *Call = dyn_cast<CallInst>(&I);
1019 (Call && Call->hasByValArgument())) &&
1021 O << " " << I << "\n";
1022 }
1023 }
1024 O << "\n";
1025 }
1026 }
1027}
1028
1030
1031AnalysisKey StackSafetyAnalysis::Key;
1032
1039
1042 OS << "'Stack Safety Local Analysis' for function '" << F.getName() << "'\n";
1044 return PreservedAnalyses::all();
1045}
1046
1048
1050
1055
1057 SSI.print(O);
1058}
1059
1061 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1062 SSI = {&F, [SE]() -> ScalarEvolution & { return *SE; }};
1063 return false;
1064}
1065
1066AnalysisKey StackSafetyGlobalAnalysis::Key;
1067
1072 const ModuleSummaryIndex *Index = nullptr;
1073 if (auto *IndexPass =
1075 Index = IndexPass->getIndex();
1076 return {&M,
1077 [&FAM](Function &F) -> const StackSafetyInfo & {
1078 return FAM.getResult<StackSafetyAnalysis>(F);
1079 },
1080 Index};
1081}
1082
1085 OS << "'Stack Safety Analysis' for module '" << M.getName() << "'\n";
1087 return PreservedAnalyses::all();
1088}
1089
1091
1094
1096
1098 const Module *M) const {
1099 SSGI.print(O);
1100}
1101
1107
1109 const ModuleSummaryIndex *ImportSummary = nullptr;
1110 if (auto *IndexWrapperPass =
1112 ImportSummary = IndexWrapperPass->getIndex();
1113
1114 SSGI = {&M,
1115 [this](Function &F) -> const StackSafetyInfo & {
1116 return getAnalysis<StackSafetyInfoWrapperPass>(F).getResult();
1117 },
1118 ImportSummary};
1119 return false;
1120}
1121
1123 if (getAnalysisOptions(M).stack_safety_run)
1124 return true;
1125 for (const auto &F : M.functions())
1126 if (F.hasFnAttribute(Attribute::SanitizeMemTag))
1127 return true;
1128 return false;
1129}
1130
1132 const cl::LibraryOptionsContext *LibraryOptions,
1133 ModuleSummaryIndex &Index) {
1134 if (!Index.hasParamAccess())
1135 return;
1137
1138 auto CountParamAccesses = [&](auto &Stat) {
1139 if (!AreStatisticsEnabled())
1140 return;
1141 for (auto &GVS : Index)
1142 for (auto &GV : GVS.second.getSummaryList())
1143 if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GV.get()))
1144 Stat += FS->paramAccesses().size();
1145 };
1146
1147 CountParamAccesses(NumCombinedParamAccessesBefore);
1148
1149 std::map<const FunctionSummary *, FunctionInfo<FunctionSummary>> Functions;
1150
1151 // Convert the ModuleSummaryIndex to a FunctionMap
1152 for (auto &GVS : Index) {
1153 for (auto &GV : GVS.second.getSummaryList()) {
1155 if (!FS || FS->paramAccesses().empty())
1156 continue;
1157 if (FS->isLive() && FS->isDSOLocal()) {
1158 FunctionInfo<FunctionSummary> FI;
1159 for (const auto &PS : FS->paramAccesses()) {
1160 auto &US =
1161 FI.Params
1162 .emplace(PS.ParamNo, FunctionSummary::ParamAccess::RangeWidth)
1163 .first->second;
1164 US.Range = PS.Use;
1165 for (const auto &Call : PS.Calls) {
1166 assert(!Call.Offsets.isFullSet());
1167 FunctionSummary *S =
1168 findCalleeFunctionSummary(Call.Callee, FS->modulePath());
1169 ++NumCombinedCalleeLookupTotal;
1170 if (!S) {
1171 ++NumCombinedCalleeLookupFailed;
1172 US.Range = FullSet;
1173 US.Calls.clear();
1174 break;
1175 }
1176 US.Calls.emplace(CallInfo<FunctionSummary>(S, Call.ParamNo),
1177 Call.Offsets);
1178 }
1179 }
1180 Functions.emplace(FS, std::move(FI));
1181 }
1182 // Reset data for all summaries. Alive and DSO local will be set back from
1183 // of data flow results below. Anything else will not be accessed
1184 // by ThinLTO backend, so we can save on bitcode size.
1185 FS->setParamAccesses({});
1186 }
1187 }
1188 NumCombinedDataFlowNodes += Functions.size();
1189 StackSafetyDataFlowAnalysis<FunctionSummary> SSDFA(
1190 FunctionSummary::ParamAccess::RangeWidth, std::move(Functions),
1192 .stack_safety_max_iterations);
1193 for (const auto &KV : SSDFA.run()) {
1194 std::vector<FunctionSummary::ParamAccess> NewParams;
1195 NewParams.reserve(KV.second.Params.size());
1196 for (const auto &Param : KV.second.Params) {
1197 // It's not needed as FullSet is processed the same as a missing value.
1198 if (Param.second.Range.isFullSet())
1199 continue;
1200 NewParams.emplace_back();
1201 FunctionSummary::ParamAccess &New = NewParams.back();
1202 New.ParamNo = Param.first;
1203 New.Use = Param.second.Range; // Only range is needed.
1204 }
1205 const_cast<FunctionSummary *>(KV.first)->setParamAccesses(
1206 std::move(NewParams));
1207 }
1208
1209 CountParamAccesses(NumCombinedParamAccessesAfter);
1210}
1211
1212static const char LocalPassArg[] = "stack-safety-local";
1213static const char LocalPassName[] = "Stack Safety Local Analysis";
1215 false, true)
1219
1220static const char GlobalPassName[] = "Stack Safety Analysis";
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:690
DXIL Resource Access
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
This is the interface to build a ModuleSummaryIndex for a module.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static const char LocalPassArg[]
static const char LocalPassName[]
static true const char GlobalPassName[]
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
an instruction to allocate memory on the stack
LLVM_ABI TypeSize getAllocationBaseSize(const DataLayout &DL) const
Get the size of the allocated type.
PointerType * getType() const
Overload to return most specific pointer type.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
This class represents a function call, abstracting a target machine's calling convention.
This class represents a range of values.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
FunctionPass(char &pid)
Definition Pass.h:314
Function summary information to aid decisions and implementation of importing.
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
bool isDSOLocal() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
static bool isLinkOnceLinkage(LinkageTypes Linkage)
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
static bool isExternalLinkage(LinkageTypes Linkage)
static bool isWeakLinkage(LinkageTypes Linkage)
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
NPM analysis to provide an externally-built ModuleSummaryIndex (e.g.
Legacy wrapper pass to provide the ModuleSummaryIndex object.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
This is the common base class for memset/memcpy/memmove.
ModulePass(char &pid)
Definition Pass.h:255
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents an analyzed expression in the program.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVMContext & getContext() const
void insert_range(Range &&R)
Definition SetVector.h:182
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
value_type pop_back_val()
Definition SetVector.h:285
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator erase(const_iterator CI)
void push_back(const T &Elt)
Compute live ranges of allocas.
LLVM_ABI void run()
LLVM_ABI bool isReachable(const Instruction *I) const
Returns true if instruction is reachable from entry.
LLVM_ABI bool isAliveAfter(const AllocaInst *AI, const Instruction *I) const
Returns true if the alloca is alive after the instruction.
StackSafetyInfo wrapper for the new pass manager.
LLVM_ABI StackSafetyInfo run(Function &F, FunctionAnalysisManager &AM)
This pass performs the global (interprocedural) stack safety analysis (new pass manager).
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &AM)
This pass performs the global (interprocedural) stack safety analysis (legacy pass manager).
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &O, const Module *M) const override
print - Print out the internal state of the pass.
LLVM_ABI void print(raw_ostream &O) const
LLVM_ABI bool stackAccessIsSafe(const Instruction &I) const
LLVM_ABI bool isSafe(const AllocaInst &AI) const
LLVM_ABI StackSafetyGlobalInfo & operator=(StackSafetyGlobalInfo &&)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
StackSafetyInfo wrapper for the legacy pass manager.
void print(raw_ostream &O, const Module *M) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Interface to access stack safety analysis results for single function.
LLVM_ABI void print(raw_ostream &O) const
LLVM_ABI ~StackSafetyInfo()
LLVM_ABI const InfoTy & getInfo() const
LLVM_ABI StackSafetyInfo()
LLVM_ABI StackSafetyInfo & operator=(StackSafetyInfo &&)
LLVM_ABI std::vector< FunctionSummary::ParamAccess > getParamAccesses(ModuleSummaryIndex &Index) const
Parameters use for a FunctionSummary.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
Offsets
Offsets in bytes from the start of the input buffer.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool needsParamAccessSummary(const Module &M)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI void generateParamAccessSummary(const cl::LibraryOptionsContext *LibraryOptions, ModuleSummaryIndex &Index)
Reads -stack-safety-max-iterations from LibraryOptions, or its global value if null.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
std::set< const Instruction * > UnsafeAccesses
SmallPtrSet< const AllocaInst *, 8 > SafeAllocas
FunctionInfo< GlobalValue > Info
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
static constexpr uint32_t RangeWidth