LLVM 23.0.0git
FunctionAttrs.cpp
Go to the documentation of this file.
1//===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
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/// \file
10/// This file implements interprocedural passes which walk the
11/// call-graph deducing and/or propagating function attributes.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/CFG.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/Function.h"
43#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
47#include "llvm/IR/Metadata.h"
49#include "llvm/IR/PassManager.h"
51#include "llvm/IR/Type.h"
52#include "llvm/IR/Use.h"
53#include "llvm/IR/User.h"
54#include "llvm/IR/Value.h"
58#include "llvm/Support/Debug.h"
62#include "llvm/Transforms/IPO.h"
64#include <cassert>
65#include <iterator>
66#include <map>
67#include <optional>
68#include <vector>
69
70using namespace llvm;
71using namespace llvm::PatternMatch;
72
73#define DEBUG_TYPE "function-attrs"
74
75STATISTIC(NumMemoryAttr, "Number of functions with improved memory attribute");
76STATISTIC(NumCapturesNone, "Number of arguments marked captures(none)");
77STATISTIC(NumCapturesPartial, "Number of arguments marked with captures "
78 "attribute other than captures(none)");
79STATISTIC(NumReturned, "Number of arguments marked returned");
80STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
81STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
82STATISTIC(NumWriteOnlyArg, "Number of arguments marked writeonly");
83STATISTIC(NumNoAlias, "Number of function returns marked noalias");
84STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
85STATISTIC(NumNoUndefReturn, "Number of function returns marked noundef");
86STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
87STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
88STATISTIC(NumNoFree, "Number of functions marked as nofree");
89STATISTIC(NumWillReturn, "Number of functions marked as willreturn");
90STATISTIC(NumNoSync, "Number of functions marked as nosync");
91STATISTIC(NumCold, "Number of functions marked as cold");
92
93STATISTIC(NumThinLinkNoRecurse,
94 "Number of functions marked as norecurse during thinlink");
95STATISTIC(NumThinLinkNoUnwind,
96 "Number of functions marked as nounwind during thinlink");
97
99 "enable-poison-arg-attr-prop", cl::init(true), cl::Hidden,
100 cl::desc("Try to propagate nonnull and nofpclass argument attributes from "
101 "callsites to caller functions."));
102
104 "disable-nounwind-inference", cl::Hidden,
105 cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
106
108 "disable-nofree-inference", cl::Hidden,
109 cl::desc("Stop inferring nofree attribute during function-attrs pass"));
110
112 "disable-thinlto-funcattrs", cl::init(true), cl::Hidden,
113 cl::desc("Don't propagate function-attrs in thinLTO"));
114
116 if (capturesNothing(CI))
117 ++NumCapturesNone;
118 else
119 ++NumCapturesPartial;
120}
121
122namespace {
123
124using SCCNodeSet = SmallSetVector<Function *, 8>;
125
126} // end anonymous namespace
127
129 ModRefInfo MR, AAResults &AAR) {
130 // Ignore accesses to known-invariant or local memory.
131 MR &= AAR.getModRefInfoMask(Loc, /*IgnoreLocal=*/true);
132 if (isNoModRef(MR))
133 return;
134
135 const Value *UO = getUnderlyingObjectAggressive(Loc.Ptr);
136 if (isa<AllocaInst>(UO))
137 return;
138 if (isa<Argument>(UO)) {
140 return;
141 }
142
143 // If it's not an identified object, it might be an argument.
144 if (!isIdentifiedObject(UO))
148}
149
150static void addArgLocs(MemoryEffects &ME, const CallBase *Call,
151 ModRefInfo ArgMR, AAResults &AAR) {
152 for (const Value *Arg : Call->args()) {
153 if (!Arg->getType()->isPtrOrPtrVectorTy())
154 continue;
155
156 addLocAccess(ME,
157 MemoryLocation::getBeforeOrAfter(Arg, Call->getAAMetadata()),
158 ArgMR, AAR);
159 }
160}
161
162/// Returns the memory access attribute for function F using AAR for AA results,
163/// where SCCNodes is the current SCC.
164///
165/// If ThisBody is true, this function may examine the function body and will
166/// return a result pertaining to this copy of the function. If it is false, the
167/// result will be based only on AA results for the function declaration; it
168/// will be assumed that some other (perhaps less optimized) version of the
169/// function may be selected at link time.
170///
171/// The return value is split into two parts: Memory effects that always apply,
172/// and additional memory effects that apply if any of the functions in the SCC
173/// can access argmem.
174static std::pair<MemoryEffects, MemoryEffects>
176 const SCCNodeSet &SCCNodes) {
177 MemoryEffects OrigME = AAR.getMemoryEffects(&F);
178 if (OrigME.doesNotAccessMemory())
179 // Already perfect!
180 return {OrigME, MemoryEffects::none()};
181
182 if (!ThisBody)
183 return {OrigME, MemoryEffects::none()};
184
186 // Additional locations accessed if the SCC accesses argmem.
187 MemoryEffects RecursiveArgME = MemoryEffects::none();
188
189 auto AddNonArgMemoryEffects = [&ME](MemoryEffects InstME) {
190 // Merge instruction memory effects, including inaccessible and errno
191 // memory, but excluding argument memory, which is handled separately.
193
194 // If the instruction accesses captured memory (currently part of "other")
195 // and an argument is captured (currently not tracked), then it may also
196 // access argument memory.
197 ModRefInfo OtherMR = InstME.getModRef(IRMemLocation::Other);
198 ME |= MemoryEffects::argMemOnly(OtherMR);
199 };
200
201 // Inalloca and preallocated arguments are always clobbered by the call.
202 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
203 F.getAttributes().hasAttrSomewhere(Attribute::Preallocated))
205
206 // Scan the function body for instructions that may read or write memory.
207 for (Instruction &I : instructions(F)) {
208 // Some instructions can be ignored even if they read or write memory.
209 // Detect these now, skipping to the next instruction if one is found.
210 if (auto *Call = dyn_cast<CallBase>(&I)) {
211 // We can optimistically ignore calls to functions in the same SCC, with
212 // two caveats:
213 // * Calls with operand bundles may have additional effects.
214 // * Argument memory accesses may imply additional effects depending on
215 // what the argument location is.
216 if (!Call->hasOperandBundles() && Call->getCalledFunction() &&
217 SCCNodes.count(Call->getCalledFunction())) {
218 // Keep track of which additional locations are accessed if the SCC
219 // turns out to access argmem.
220 addArgLocs(RecursiveArgME, Call, ModRefInfo::ModRef, AAR);
221 continue;
222 }
223
224 MemoryEffects CallME = AAR.getMemoryEffects(Call);
225
226 // If the call doesn't access memory, we're done.
227 if (CallME.doesNotAccessMemory())
228 continue;
229
230 // A pseudo probe call shouldn't change any function attribute since it
231 // doesn't translate to a real instruction. It comes with a memory access
232 // tag to prevent itself being removed by optimizations and not block
233 // other instructions being optimized.
235 continue;
236
237 AddNonArgMemoryEffects(CallME);
238
239 // Check whether all pointer arguments point to local memory, and
240 // ignore calls that only access local memory.
242 if (ArgMR != ModRefInfo::NoModRef)
243 addArgLocs(ME, Call, ArgMR, AAR);
244 continue;
245 }
246
247 MemoryEffects InstME = I.getMemoryEffects();
248 if (InstME.doesNotAccessMemory())
249 continue;
250
251 std::optional<MemoryLocation> Loc = MemoryLocation::getOrNone(&I);
252 if (!Loc) {
253 // If no location is known, conservatively assume anything can be
254 // accessed.
255 ME |= MemoryEffects(InstME.getModRef());
256 continue;
257 }
258
259 AddNonArgMemoryEffects(InstME);
261 }
262
263 return {OrigME & ME, RecursiveArgME};
264}
265
267 AAResults &AAR) {
268 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {}).first;
269}
270
271/// Deduce readonly/readnone/writeonly attributes for the SCC.
272template <typename AARGetterT>
273static void addMemoryAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter,
276 MemoryEffects RecursiveArgME = MemoryEffects::none();
277 for (Function *F : SCCNodes) {
278 // Call the callable parameter to look up AA results for this function.
279 AAResults &AAR = AARGetter(*F);
280 // Non-exact function definitions may not be selected at link time, and an
281 // alternative version that writes to memory may be selected. See the
282 // comment on GlobalValue::isDefinitionExact for more details.
283 auto [FnME, FnRecursiveArgME] =
284 checkFunctionMemoryAccess(*F, F->hasExactDefinition(), AAR, SCCNodes);
285 ME |= FnME;
286 RecursiveArgME |= FnRecursiveArgME;
287 // Reached bottom of the lattice, we will not be able to improve the result.
288 if (ME == MemoryEffects::unknown())
289 return;
290 }
291
292 // If the SCC accesses argmem, add recursive accesses resulting from that.
294 if (ArgMR != ModRefInfo::NoModRef)
295 ME |= RecursiveArgME & MemoryEffects(ArgMR);
296
297 for (Function *F : SCCNodes) {
298 MemoryEffects OldME = F->getMemoryEffects();
299 MemoryEffects NewME = ME & OldME;
300 if (NewME != OldME) {
301 ++NumMemoryAttr;
302 F->setMemoryEffects(NewME);
303 // Remove conflicting writable attributes.
305 for (Argument &A : F->args())
306 A.removeAttr(Attribute::Writable);
307 Changed.insert(F);
308 }
309 }
310}
311
312// Compute definitive function attributes for a function taking into account
313// prevailing definitions and linkage types
315 ValueInfo VI,
316 DenseMap<ValueInfo, FunctionSummary *> &CachedPrevailingSummary,
318 IsPrevailing) {
319
320 auto [It, Inserted] = CachedPrevailingSummary.try_emplace(VI);
321 if (!Inserted)
322 return It->second;
323
324 /// At this point, prevailing symbols have been resolved. The following leads
325 /// to returning a conservative result:
326 /// - Multiple instances with local linkage. Normally local linkage would be
327 /// unique per module
328 /// as the GUID includes the module path. We could have a guid alias if
329 /// there wasn't any distinguishing path when each file was compiled, but
330 /// that should be rare so we'll punt on those.
331
332 /// These next 2 cases should not happen and will assert:
333 /// - Multiple instances with external linkage. This should be caught in
334 /// symbol resolution
335 /// - Non-existent FunctionSummary for Aliasee. This presents a hole in our
336 /// knowledge meaning we have to go conservative.
337
338 /// Otherwise, we calculate attributes for a function as:
339 /// 1. If we have a local linkage, take its attributes. If there's somehow
340 /// multiple, bail and go conservative.
341 /// 2. If we have an external/WeakODR/LinkOnceODR linkage check that it is
342 /// prevailing, take its attributes.
343 /// 3. If we have a Weak/LinkOnce linkage the copies can have semantic
344 /// differences. However, if the prevailing copy is known it will be used
345 /// so take its attributes. If the prevailing copy is in a native file
346 /// all IR copies will be dead and propagation will go conservative.
347 /// 4. AvailableExternally summaries without a prevailing copy are known to
348 /// occur in a couple of circumstances:
349 /// a. An internal function gets imported due to its caller getting
350 /// imported, it becomes AvailableExternally but no prevailing
351 /// definition exists. Because it has to get imported along with its
352 /// caller the attributes will be captured by propagating on its
353 /// caller.
354 /// b. C++11 [temp.explicit]p10 can generate AvailableExternally
355 /// definitions of explicitly instanced template declarations
356 /// for inlining which are ultimately dropped from the TU. Since this
357 /// is localized to the TU the attributes will have already made it to
358 /// the callers.
359 /// These are edge cases and already captured by their callers so we
360 /// ignore these for now. If they become relevant to optimize in the
361 /// future this can be revisited.
362 /// 5. Otherwise, go conservative.
363
364 FunctionSummary *Local = nullptr;
365 FunctionSummary *Prevailing = nullptr;
366
367 for (const auto &GVS : VI.getSummaryList()) {
368 if (!GVS->isLive())
369 continue;
370
371 FunctionSummary *FS = dyn_cast<FunctionSummary>(GVS->getBaseObject());
372 // Virtual and Unknown (e.g. indirect) calls require going conservative
373 if (!FS || FS->fflags().HasUnknownCall)
374 return nullptr;
375
376 const auto &Linkage = GVS->linkage();
378 if (Local) {
380 dbgs()
381 << "ThinLTO FunctionAttrs: Multiple Local Linkage, bailing on "
382 "function "
383 << VI.name() << " from " << FS->modulePath() << ". Previous module "
384 << Local->modulePath() << "\n");
385 return nullptr;
386 }
387 Local = FS;
389 assert(IsPrevailing(VI.getGUID(), GVS.get()) || GVS->wasPromoted());
390 Prevailing = FS;
391 break;
396 if (IsPrevailing(VI.getGUID(), GVS.get())) {
397 Prevailing = FS;
398 break;
399 }
401 // TODO: Handle these cases if they become meaningful
402 continue;
403 }
404 }
405
406 auto &CPS = CachedPrevailingSummary[VI];
407 if (Local) {
408 assert(!Prevailing);
409 CPS = Local;
410 } else if (Prevailing) {
411 assert(!Local);
412 CPS = Prevailing;
413 }
414
415 return CPS;
416}
417
419 ModuleSummaryIndex &Index,
421 IsPrevailing) {
422 // TODO: implement addNoAliasAttrs once
423 // there's more information about the return type in the summary
425 return false;
426
427 DenseMap<ValueInfo, FunctionSummary *> CachedPrevailingSummary;
428 bool Changed = false;
429
430 auto PropagateAttributes = [&](std::vector<ValueInfo> &SCCNodes) {
431 // Assume we can propagate unless we discover otherwise
432 FunctionSummary::FFlags InferredFlags;
433 InferredFlags.NoRecurse = (SCCNodes.size() == 1);
434 InferredFlags.NoUnwind = true;
435
436 for (auto &V : SCCNodes) {
437 FunctionSummary *CallerSummary =
438 calculatePrevailingSummary(V, CachedPrevailingSummary, IsPrevailing);
439
440 // Function summaries can fail to contain information such as declarations
441 if (!CallerSummary)
442 return;
443
444 if (CallerSummary->fflags().MayThrow)
445 InferredFlags.NoUnwind = false;
446
447 for (const auto &Callee : CallerSummary->calls()) {
449 Callee.first, CachedPrevailingSummary, IsPrevailing);
450
451 if (!CalleeSummary)
452 return;
453
454 if (!CalleeSummary->fflags().NoRecurse)
455 InferredFlags.NoRecurse = false;
456
457 if (!CalleeSummary->fflags().NoUnwind)
458 InferredFlags.NoUnwind = false;
459
460 if (!InferredFlags.NoUnwind && !InferredFlags.NoRecurse)
461 break;
462 }
463 }
464
465 if (InferredFlags.NoUnwind || InferredFlags.NoRecurse) {
466 Changed = true;
467 for (auto &V : SCCNodes) {
468 if (InferredFlags.NoRecurse) {
469 LLVM_DEBUG(dbgs() << "ThinLTO FunctionAttrs: Propagated NoRecurse to "
470 << V.name() << "\n");
471 ++NumThinLinkNoRecurse;
472 }
473
474 if (InferredFlags.NoUnwind) {
475 LLVM_DEBUG(dbgs() << "ThinLTO FunctionAttrs: Propagated NoUnwind to "
476 << V.name() << "\n");
477 ++NumThinLinkNoUnwind;
478 }
479
480 for (const auto &S : V.getSummaryList()) {
481 if (auto *FS = dyn_cast<FunctionSummary>(S.get())) {
482 if (InferredFlags.NoRecurse)
483 FS->setNoRecurse();
484
485 if (InferredFlags.NoUnwind)
486 FS->setNoUnwind();
487 }
488 }
489 }
490 }
491 };
492
493 // Call propagation functions on each SCC in the Index
494 for (scc_iterator<ModuleSummaryIndex *> I = scc_begin(&Index); !I.isAtEnd();
495 ++I) {
496 std::vector<ValueInfo> Nodes(*I);
497 PropagateAttributes(Nodes);
498 }
499 return Changed;
500}
501
502namespace {
503
504/// For a given pointer Argument, this retains a list of Arguments of functions
505/// in the same SCC that the pointer data flows into. We use this to build an
506/// SCC of the arguments.
507struct ArgumentGraphNode {
508 Argument *Definition;
509 /// CaptureComponents for this argument, excluding captures via Uses.
510 /// We don't distinguish between other/return captures here.
513};
514
515class ArgumentGraph {
516 // We store pointers to ArgumentGraphNode objects, so it's important that
517 // that they not move around upon insert.
518 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
519
520 ArgumentMapTy ArgumentMap;
521
522 // There is no root node for the argument graph, in fact:
523 // void f(int *x, int *y) { if (...) f(x, y); }
524 // is an example where the graph is disconnected. The SCCIterator requires a
525 // single entry point, so we maintain a fake ("synthetic") root node that
526 // uses every node. Because the graph is directed and nothing points into
527 // the root, it will not participate in any SCCs (except for its own).
528 ArgumentGraphNode SyntheticRoot;
529
530public:
531 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
532
534
535 iterator begin() { return SyntheticRoot.Uses.begin(); }
536 iterator end() { return SyntheticRoot.Uses.end(); }
537 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
538
539 ArgumentGraphNode *operator[](Argument *A) {
540 ArgumentGraphNode &Node = ArgumentMap[A];
541 Node.Definition = A;
542 SyntheticRoot.Uses.push_back(&Node);
543 return &Node;
544 }
545};
546
547/// This tracker checks whether callees are in the SCC, and if so it does not
548/// consider that a capture, instead adding it to the "Uses" list and
549/// continuing with the analysis.
550struct ArgumentUsesTracker : public CaptureTracker {
551 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
552
553 void tooManyUses() override { CI = CaptureInfo::all(); }
554
555 Action captured(const Use *U, UseCaptureInfo UseCI) override {
556 if (updateCaptureInfo(U, UseCI.UseCC)) {
557 // Don't bother continuing if we already capture everything.
558 if (capturesAll(CI.getOtherComponents()))
559 return Stop;
560 return Continue;
561 }
562
563 // For SCC argument tracking, we're not going to analyze other/ret
564 // components separately, so don't follow the return value.
565 return ContinueIgnoringReturn;
566 }
567
568 bool updateCaptureInfo(const Use *U, CaptureComponents CC) {
569 CallBase *CB = dyn_cast<CallBase>(U->getUser());
570 if (!CB) {
571 if (isa<ReturnInst>(U->getUser()))
572 CI |= CaptureInfo::retOnly(CC);
573 else
574 // Conservatively assume that the captured value might make its way
575 // into the return value as well. This could be made more precise.
576 CI |= CaptureInfo(CC);
577 return true;
578 }
579
581 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
582 CI |= CaptureInfo(CC);
583 return true;
584 }
585
586 assert(!CB->isCallee(U) && "callee operand reported captured?");
587 const unsigned UseIndex = CB->getDataOperandNo(U);
588 if (UseIndex >= CB->arg_size()) {
589 // Data operand, but not a argument operand -- must be a bundle operand
590 assert(CB->hasOperandBundles() && "Must be!");
591
592 // CaptureTracking told us that we're being captured by an operand bundle
593 // use. In this case it does not matter if the callee is within our SCC
594 // or not -- we've been captured in some unknown way, and we have to be
595 // conservative.
596 CI |= CaptureInfo(CC);
597 return true;
598 }
599
600 if (UseIndex >= F->arg_size()) {
601 assert(F->isVarArg() && "More params than args in non-varargs call");
602 CI |= CaptureInfo(CC);
603 return true;
604 }
605
606 // TODO(captures): Could improve precision by remembering maximum
607 // capture components for the argument.
608 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
609 return false;
610 }
611
612 // Does not include potential captures via Uses in the SCC.
613 CaptureInfo CI = CaptureInfo::none();
614
615 // Uses within our SCC.
617
618 const SCCNodeSet &SCCNodes;
619};
620
621/// A struct of argument use: a Use and the offset it accesses. This struct
622/// is to track uses inside function via GEP. If GEP has a non-constant index,
623/// the Offset field is nullopt.
624struct ArgumentUse {
625 Use *U;
626 std::optional<int64_t> Offset;
627};
628
629/// A struct of argument access info. "Unknown" accesses are the cases like
630/// unrecognized instructions, instructions that have more than one use of
631/// the argument, or volatile memory accesses. "WriteWithSideEffect" are call
632/// instructions that not only write an argument but also capture it.
633struct ArgumentAccessInfo {
634 enum class AccessType : uint8_t { Write, WriteWithSideEffect, Read, Unknown };
635 AccessType ArgAccessType;
636 ConstantRangeList AccessRanges;
637};
638
639/// A struct to wrap the argument use info per block.
640struct UsesPerBlockInfo {
641 SmallDenseMap<Instruction *, ArgumentAccessInfo, 4> Insts;
642 bool HasWrites = false;
643 bool HasUnknownAccess = false;
644};
645
646/// A struct to summarize the argument use info in a function.
647struct ArgumentUsesSummary {
648 bool HasAnyWrite = false;
649 bool HasWriteOutsideEntryBB = false;
650 SmallDenseMap<const BasicBlock *, UsesPerBlockInfo, 16> UsesPerBlock;
651};
652
653ArgumentAccessInfo getArgumentAccessInfo(const Instruction *I,
654 const ArgumentUse &ArgUse,
655 const DataLayout &DL) {
656 auto GetTypeAccessRange =
657 [&DL](Type *Ty,
658 std::optional<int64_t> Offset) -> std::optional<ConstantRange> {
659 auto TypeSize = DL.getTypeStoreSize(Ty);
660 if (!TypeSize.isScalable() && Offset) {
661 int64_t Size = TypeSize.getFixedValue();
662 APInt Low(64, *Offset, true);
663 bool Overflow;
664 APInt High = Low.sadd_ov(APInt(64, Size, true), Overflow);
665 // Bail if the range overflows signed 64-bit int.
666 if (Overflow)
667 return std::nullopt;
668 return ConstantRange(Low, High);
669 }
670 return std::nullopt;
671 };
672 auto GetConstantIntRange =
673 [](Value *Length,
674 std::optional<int64_t> Offset) -> std::optional<ConstantRange> {
675 auto *ConstantLength = dyn_cast<ConstantInt>(Length);
676 if (ConstantLength && Offset) {
677 int64_t Len = ConstantLength->getSExtValue();
678
679 // Reject zero or negative lengths
680 if (Len <= 0)
681 return std::nullopt;
682
683 APInt Low(64, *Offset, true);
684 bool Overflow;
685 APInt High = Low.sadd_ov(APInt(64, Len, true), Overflow);
686 if (Overflow)
687 return std::nullopt;
688
689 return ConstantRange(Low, High);
690 }
691 return std::nullopt;
692 };
693
694 if (auto *SI = dyn_cast<StoreInst>(I)) {
695 if (SI->isSimple() && &SI->getOperandUse(1) == ArgUse.U) {
696 // Get the fixed type size of "SI". Since the access range of a write
697 // will be unioned, if "SI" doesn't have a fixed type size, we just set
698 // the access range to empty.
699 ConstantRangeList AccessRanges;
700 if (auto TypeAccessRange =
701 GetTypeAccessRange(SI->getAccessType(), ArgUse.Offset))
702 AccessRanges.insert(*TypeAccessRange);
703 return {ArgumentAccessInfo::AccessType::Write, std::move(AccessRanges)};
704 }
705 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
706 if (LI->isSimple()) {
707 assert(&LI->getOperandUse(0) == ArgUse.U);
708 // Get the fixed type size of "LI". Different from Write, if "LI"
709 // doesn't have a fixed type size, we conservatively set as a clobber
710 // with an empty access range.
711 if (auto TypeAccessRange =
712 GetTypeAccessRange(LI->getAccessType(), ArgUse.Offset))
713 return {ArgumentAccessInfo::AccessType::Read, {*TypeAccessRange}};
714 }
715 } else if (auto *MemSet = dyn_cast<MemSetInst>(I)) {
716 if (!MemSet->isVolatile()) {
717 ConstantRangeList AccessRanges;
718 if (auto AccessRange =
719 GetConstantIntRange(MemSet->getLength(), ArgUse.Offset))
720 AccessRanges.insert(*AccessRange);
721 return {ArgumentAccessInfo::AccessType::Write, AccessRanges};
722 }
723 } else if (auto *MTI = dyn_cast<MemTransferInst>(I)) {
724 if (!MTI->isVolatile()) {
725 if (&MTI->getOperandUse(0) == ArgUse.U) {
726 ConstantRangeList AccessRanges;
727 if (auto AccessRange =
728 GetConstantIntRange(MTI->getLength(), ArgUse.Offset))
729 AccessRanges.insert(*AccessRange);
730 return {ArgumentAccessInfo::AccessType::Write, AccessRanges};
731 } else if (&MTI->getOperandUse(1) == ArgUse.U) {
732 if (auto AccessRange =
733 GetConstantIntRange(MTI->getLength(), ArgUse.Offset))
734 return {ArgumentAccessInfo::AccessType::Read, {*AccessRange}};
735 }
736 }
737 } else if (auto *CB = dyn_cast<CallBase>(I)) {
738 if (CB->isArgOperand(ArgUse.U) &&
739 !CB->isByValArgument(CB->getArgOperandNo(ArgUse.U))) {
740 unsigned ArgNo = CB->getArgOperandNo(ArgUse.U);
741 bool IsInitialize = CB->paramHasAttr(ArgNo, Attribute::Initializes);
742 if (IsInitialize && ArgUse.Offset) {
743 // Argument is a Write when parameter is writeonly/readnone
744 // and nocapture. Otherwise, it's a WriteWithSideEffect.
745 auto Access = CB->onlyWritesMemory(ArgNo) && CB->doesNotCapture(ArgNo)
746 ? ArgumentAccessInfo::AccessType::Write
747 : ArgumentAccessInfo::AccessType::WriteWithSideEffect;
748 ConstantRangeList AccessRanges;
749 Attribute Attr = CB->getParamAttr(ArgNo, Attribute::Initializes);
751 for (ConstantRange &CR : CBCRL)
752 AccessRanges.insert(ConstantRange(CR.getLower() + *ArgUse.Offset,
753 CR.getUpper() + *ArgUse.Offset));
754 return {Access, AccessRanges};
755 }
756 }
757 }
758 // Other unrecognized instructions are considered as unknown.
759 return {ArgumentAccessInfo::AccessType::Unknown, {}};
760}
761
762// Collect the uses of argument "A" in "F".
763ArgumentUsesSummary collectArgumentUsesPerBlock(Argument &A, Function &F) {
764 auto &DL = F.getParent()->getDataLayout();
765 unsigned PointerSize =
766 DL.getIndexSizeInBits(A.getType()->getPointerAddressSpace());
767 ArgumentUsesSummary Result;
768
769 BasicBlock &EntryBB = F.getEntryBlock();
771 for (Use &U : A.uses())
772 Worklist.push_back({&U, 0});
773
774 // Update "UsesPerBlock" with the block of "I" as key and "Info" as value.
775 // Return true if the block of "I" has write accesses after updating.
776 auto UpdateUseInfo = [&Result](Instruction *I, ArgumentAccessInfo Info) {
777 auto *BB = I->getParent();
778 auto &BBInfo = Result.UsesPerBlock[BB];
779 auto [It, Inserted] = BBInfo.Insts.try_emplace(I);
780 auto &IInfo = It->second;
781
782 // Instructions that have more than one use of the argument are considered
783 // as clobbers.
784 if (!Inserted) {
785 IInfo = {ArgumentAccessInfo::AccessType::Unknown, {}};
786 BBInfo.HasUnknownAccess = true;
787 return false;
788 }
789
790 IInfo = std::move(Info);
791 BBInfo.HasUnknownAccess |=
792 IInfo.ArgAccessType == ArgumentAccessInfo::AccessType::Unknown;
793 bool InfoHasWrites =
794 (IInfo.ArgAccessType == ArgumentAccessInfo::AccessType::Write ||
795 IInfo.ArgAccessType ==
796 ArgumentAccessInfo::AccessType::WriteWithSideEffect) &&
797 !IInfo.AccessRanges.empty();
798 BBInfo.HasWrites |= InfoHasWrites;
799 return InfoHasWrites;
800 };
801
802 // No need for a visited set because we don't look through phis, so there are
803 // no cycles.
804 while (!Worklist.empty()) {
805 ArgumentUse ArgUse = Worklist.pop_back_val();
806 User *U = ArgUse.U->getUser();
807 // Add GEP uses to worklist.
808 // If the GEP is not a constant GEP, set the ArgumentUse::Offset to nullopt.
809 if (auto *GEP = dyn_cast<GEPOperator>(U)) {
810 std::optional<int64_t> NewOffset = std::nullopt;
811 if (ArgUse.Offset) {
812 APInt Offset(PointerSize, 0);
813 if (GEP->accumulateConstantOffset(DL, Offset))
814 NewOffset = *ArgUse.Offset + Offset.getSExtValue();
815 }
816 for (Use &U : GEP->uses())
817 Worklist.push_back({&U, NewOffset});
818 continue;
819 }
820
821 auto *I = cast<Instruction>(U);
822 bool HasWrite = UpdateUseInfo(I, getArgumentAccessInfo(I, ArgUse, DL));
823
824 Result.HasAnyWrite |= HasWrite;
825
826 if (HasWrite && I->getParent() != &EntryBB)
827 Result.HasWriteOutsideEntryBB = true;
828 }
829 return Result;
830}
831
832} // end anonymous namespace
833
834namespace llvm {
835
836template <> struct GraphTraits<ArgumentGraphNode *> {
837 using NodeRef = ArgumentGraphNode *;
839
840 static NodeRef getEntryNode(NodeRef A) { return A; }
841 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
842 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
843};
844
845template <>
846struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
847 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
848
849 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
850 return AG->begin();
851 }
852
853 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
854};
855
856} // end namespace llvm
857
858/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
861 const SmallPtrSet<Argument *, 8> &SCCNodes) {
862 SmallVector<Use *, 32> Worklist;
864
865 // inalloca arguments are always clobbered by the call.
866 if (A->hasInAllocaAttr() || A->hasPreallocatedAttr())
867 return Attribute::None;
868
869 bool IsRead = false;
870 bool IsWrite = false;
871
872 for (Use &U : A->uses()) {
873 Visited.insert(&U);
874 Worklist.push_back(&U);
875 }
876
877 while (!Worklist.empty()) {
878 if (IsWrite && IsRead)
879 // No point in searching further..
880 return Attribute::None;
881
882 Use *U = Worklist.pop_back_val();
883 Instruction *I = cast<Instruction>(U->getUser());
884
885 switch (I->getOpcode()) {
886 case Instruction::BitCast:
887 case Instruction::GetElementPtr:
888 case Instruction::PHI:
889 case Instruction::Select:
890 case Instruction::AddrSpaceCast:
891 // The original value is not read/written via this if the new value isn't.
892 for (Use &UU : I->uses())
893 if (Visited.insert(&UU).second)
894 Worklist.push_back(&UU);
895 break;
896
897 case Instruction::Call:
898 case Instruction::Invoke: {
899 CallBase &CB = cast<CallBase>(*I);
900 if (CB.isCallee(U)) {
901 IsRead = true;
902 // Note that indirect calls do not capture, see comment in
903 // CaptureTracking for context
904 continue;
905 }
906
907 // Given we've explicitly handled the callee operand above, what's left
908 // must be a data operand (e.g. argument or operand bundle)
909 const unsigned UseIndex = CB.getDataOperandNo(U);
910
911 // Some intrinsics (for instance ptrmask) do not capture their results,
912 // but return results thas alias their pointer argument, and thus should
913 // be handled like GEP or addrspacecast above.
915 &CB, /*MustPreserveOffset=*/false)) {
916 for (Use &UU : CB.uses())
917 if (Visited.insert(&UU).second)
918 Worklist.push_back(&UU);
919 } else if (capturesAnyProvenance(CB.getCaptureInfo(UseIndex))) {
920 if (!CB.onlyReadsMemory())
921 // If the callee can save a copy into other memory, then simply
922 // scanning uses of the call is insufficient. We have no way
923 // of tracking copies of the pointer through memory to see
924 // if a reloaded copy is written to, thus we must give up.
925 return Attribute::None;
926 // Push users for processing once we finish this one
927 if (!I->getType()->isVoidTy())
928 for (Use &UU : I->uses())
929 if (Visited.insert(&UU).second)
930 Worklist.push_back(&UU);
931 }
932
934 if (isNoModRef(ArgMR))
935 continue;
936
937 if (Function *F = CB.getCalledFunction())
938 if (CB.isArgOperand(U) && UseIndex < F->arg_size() &&
939 SCCNodes.count(F->getArg(UseIndex)))
940 // This is an argument which is part of the speculative SCC. Note
941 // that only operands corresponding to formal arguments of the callee
942 // can participate in the speculation.
943 break;
944
945 // The accessors used on call site here do the right thing for calls and
946 // invokes with operand bundles.
947 if (CB.doesNotAccessMemory(UseIndex)) {
948 /* nop */
949 } else if (!isModSet(ArgMR) || CB.onlyReadsMemory(UseIndex)) {
950 IsRead = true;
951 } else if (!isRefSet(ArgMR) ||
952 CB.dataOperandHasImpliedAttr(UseIndex, Attribute::WriteOnly)) {
953 IsWrite = true;
954 } else {
955 return Attribute::None;
956 }
957 break;
958 }
959
960 case Instruction::Load:
961 // Volatile and ordered atomic accesses are modelled as reading and
962 // writing the location.
963 if (!cast<LoadInst>(I)->isUnordered())
964 return Attribute::None;
965
966 IsRead = true;
967 break;
968
969 case Instruction::Store:
970 if (cast<StoreInst>(I)->getValueOperand() == *U)
971 // untrackable capture
972 return Attribute::None;
973
974 // Volatile and ordered atomic accesses are modelled as reading and
975 // writing the location.
976 if (!cast<StoreInst>(I)->isUnordered())
977 return Attribute::None;
978
979 IsWrite = true;
980 break;
981
982 case Instruction::ICmp:
983 case Instruction::Ret:
984 break;
985
986 default:
987 return Attribute::None;
988 }
989 }
990
991 if (IsWrite && IsRead)
992 return Attribute::None;
993 else if (IsRead)
994 return Attribute::ReadOnly;
995 else if (IsWrite)
996 return Attribute::WriteOnly;
997 else
998 return Attribute::ReadNone;
999}
1000
1001/// Deduce returned attributes for the SCC.
1002static void addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes,
1004 // Check each function in turn, determining if an argument is always returned.
1005 for (Function *F : SCCNodes) {
1006 // We can infer and propagate function attributes only when we know that the
1007 // definition we'll get at link time is *exactly* the definition we see now.
1008 // For more details, see GlobalValue::mayBeDerefined.
1009 if (!F->hasExactDefinition())
1010 continue;
1011
1012 if (F->getReturnType()->isVoidTy())
1013 continue;
1014
1015 // There is nothing to do if an argument is already marked as 'returned'.
1016 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned))
1017 continue;
1018
1019 auto FindRetArg = [&]() -> Argument * {
1020 Argument *RetArg = nullptr;
1021 for (BasicBlock &BB : *F)
1022 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
1023 // Note that stripPointerCasts should look through functions with
1024 // returned arguments.
1025 auto *RetVal =
1026 dyn_cast<Argument>(Ret->getReturnValue()->stripPointerCasts());
1027 if (!RetVal || RetVal->getType() != F->getReturnType())
1028 return nullptr;
1029
1030 if (!RetArg)
1031 RetArg = RetVal;
1032 else if (RetArg != RetVal)
1033 return nullptr;
1034 }
1035
1036 return RetArg;
1037 };
1038
1039 if (Argument *RetArg = FindRetArg()) {
1040 RetArg->addAttr(Attribute::Returned);
1041 ++NumReturned;
1042 Changed.insert(F);
1043 }
1044 }
1045}
1046
1047/// If a callsite has arguments that are also arguments to the parent function,
1048/// try to propagate attributes from the callsite's arguments to the parent's
1049/// arguments. This may be important because inlining can cause information loss
1050/// when attribute knowledge disappears with the inlined call.
1053 return false;
1054
1055 bool Changed = false;
1056
1057 // For an argument attribute to transfer from a callsite to the parent, the
1058 // call must be guaranteed to execute every time the parent is called.
1059 // Conservatively, just check for calls in the entry block that are guaranteed
1060 // to execute.
1061 // TODO: This could be enhanced by testing if the callsite post-dominates the
1062 // entry block or by doing simple forward walks or backward walks to the
1063 // callsite.
1064 BasicBlock &Entry = F.getEntryBlock();
1065 for (Instruction &I : Entry) {
1066 if (auto *CB = dyn_cast<CallBase>(&I)) {
1067 if (auto *CalledFunc = CB->getCalledFunction()) {
1068 for (auto &CSArg : CalledFunc->args()) {
1069 unsigned ArgNo = CSArg.getArgNo();
1070 auto *FArg = dyn_cast<Argument>(CB->getArgOperand(ArgNo));
1071 if (!FArg)
1072 continue;
1073
1074 if (CSArg.hasNonNullAttr(/*AllowUndefOrPoison=*/false)) {
1075 // If the non-null callsite argument operand is an argument to 'F'
1076 // (the caller) and the call is guaranteed to execute, then the
1077 // value must be non-null throughout 'F'.
1078 if (!FArg->hasNonNullAttr()) {
1079 FArg->addAttr(Attribute::NonNull);
1080 Changed = true;
1081 }
1082 } else if (FPClassTest CSNoFPClass = CB->getParamNoFPClass(ArgNo);
1083 CSNoFPClass != fcNone &&
1084 CB->paramHasAttr(ArgNo, Attribute::NoUndef)) {
1085 FPClassTest ArgNoFPClass = FArg->getNoFPClass();
1086
1087 if ((CSNoFPClass | ArgNoFPClass) != ArgNoFPClass) {
1088 FArg->addAttr(Attribute::getWithNoFPClass(
1089 FArg->getContext(), CSNoFPClass | ArgNoFPClass));
1090 Changed = true;
1091 }
1092 }
1093 }
1094 }
1095 }
1097 break;
1098 }
1099
1100 return Changed;
1101}
1102
1104 assert((R == Attribute::ReadOnly || R == Attribute::ReadNone ||
1105 R == Attribute::WriteOnly)
1106 && "Must be an access attribute.");
1107 assert(A && "Argument must not be null.");
1108
1109 // If the argument already has the attribute, nothing needs to be done.
1110 if (A->hasAttribute(R))
1111 return false;
1112
1113 // Otherwise, remove potentially conflicting attribute, add the new one,
1114 // and update statistics.
1115 A->removeAttr(Attribute::WriteOnly);
1116 A->removeAttr(Attribute::ReadOnly);
1117 A->removeAttr(Attribute::ReadNone);
1118 // Remove conflicting writable attribute.
1119 if (R == Attribute::ReadNone || R == Attribute::ReadOnly)
1120 A->removeAttr(Attribute::Writable);
1121 A->addAttr(R);
1122 if (R == Attribute::ReadOnly)
1123 ++NumReadOnlyArg;
1124 else if (R == Attribute::WriteOnly)
1125 ++NumWriteOnlyArg;
1126 else
1127 ++NumReadNoneArg;
1128 return true;
1129}
1130
1132 auto ArgumentUses = collectArgumentUsesPerBlock(A, F);
1133 // No write anywhere in the function, bail.
1134 if (!ArgumentUses.HasAnyWrite)
1135 return false;
1136
1137 auto &UsesPerBlock = ArgumentUses.UsesPerBlock;
1138 BasicBlock &EntryBB = F.getEntryBlock();
1139 // A map to store the argument ranges initialized by a BasicBlock (including
1140 // its successors).
1142 // Visit the successors of "BB" block and the instructions in BB (post-order)
1143 // to get the argument ranges initialized by "BB" (including its successors).
1144 // The result will be cached in "Initialized".
1145 auto VisitBlock = [&](const BasicBlock *BB) -> ConstantRangeList {
1146 auto UPB = UsesPerBlock.find(BB);
1148
1149 // Start with intersection of successors.
1150 // If this block has any clobbering use, we're going to clear out the
1151 // ranges at some point in this block anyway, so don't bother looking at
1152 // successors.
1153 if (UPB == UsesPerBlock.end() || !UPB->second.HasUnknownAccess) {
1154 bool HasAddedSuccessor = false;
1155 for (auto *Succ : successors(BB)) {
1156 if (auto SuccI = Initialized.find(Succ); SuccI != Initialized.end()) {
1157 if (HasAddedSuccessor) {
1158 CRL = CRL.intersectWith(SuccI->second);
1159 } else {
1160 CRL = SuccI->second;
1161 HasAddedSuccessor = true;
1162 }
1163 } else {
1164 CRL = ConstantRangeList();
1165 break;
1166 }
1167 }
1168 }
1169
1170 if (UPB != UsesPerBlock.end()) {
1171 // Sort uses in this block by instruction order.
1173 append_range(Insts, UPB->second.Insts);
1174 sort(Insts, [](std::pair<Instruction *, ArgumentAccessInfo> &LHS,
1175 std::pair<Instruction *, ArgumentAccessInfo> &RHS) {
1176 return LHS.first->comesBefore(RHS.first);
1177 });
1178
1179 // From the end of the block to the beginning of the block, set
1180 // initializes ranges.
1181 for (auto &[_, Info] : reverse(Insts)) {
1182 if (Info.ArgAccessType == ArgumentAccessInfo::AccessType::Unknown ||
1183 Info.ArgAccessType ==
1184 ArgumentAccessInfo::AccessType::WriteWithSideEffect)
1185 CRL = ConstantRangeList();
1186 if (!Info.AccessRanges.empty()) {
1187 if (Info.ArgAccessType == ArgumentAccessInfo::AccessType::Write ||
1188 Info.ArgAccessType ==
1189 ArgumentAccessInfo::AccessType::WriteWithSideEffect) {
1190 CRL = CRL.unionWith(Info.AccessRanges);
1191 } else {
1192 assert(Info.ArgAccessType == ArgumentAccessInfo::AccessType::Read);
1193 for (const auto &ReadRange : Info.AccessRanges)
1194 CRL.subtract(ReadRange);
1195 }
1196 }
1197 }
1198 }
1199 return CRL;
1200 };
1201
1202 ConstantRangeList EntryCRL;
1203 // If all write instructions are in the EntryBB, or if the EntryBB has
1204 // a clobbering use, we only need to look at EntryBB.
1205 bool OnlyScanEntryBlock = !ArgumentUses.HasWriteOutsideEntryBB;
1206 if (!OnlyScanEntryBlock)
1207 if (auto EntryUPB = UsesPerBlock.find(&EntryBB);
1208 EntryUPB != UsesPerBlock.end())
1209 OnlyScanEntryBlock = EntryUPB->second.HasUnknownAccess;
1210 if (OnlyScanEntryBlock) {
1211 EntryCRL = VisitBlock(&EntryBB);
1212 if (EntryCRL.empty())
1213 return false;
1214 } else {
1215 // Now we have to go through CFG to get the initialized argument ranges
1216 // across blocks. With dominance and post-dominance, the initialized ranges
1217 // by a block include both accesses inside this block and accesses in its
1218 // (transitive) successors. So visit successors before predecessors with a
1219 // post-order walk of the blocks and memorize the results in "Initialized".
1220 for (const BasicBlock *BB : post_order(&F)) {
1221 ConstantRangeList CRL = VisitBlock(BB);
1222 if (!CRL.empty())
1223 Initialized[BB] = CRL;
1224 }
1225
1226 auto EntryCRLI = Initialized.find(&EntryBB);
1227 if (EntryCRLI == Initialized.end())
1228 return false;
1229
1230 EntryCRL = EntryCRLI->second;
1231 }
1232
1233 assert(!EntryCRL.empty() &&
1234 "should have bailed already if EntryCRL is empty");
1235
1236 if (A.hasAttribute(Attribute::Initializes)) {
1237 ConstantRangeList PreviousCRL =
1238 A.getAttribute(Attribute::Initializes).getValueAsConstantRangeList();
1239 if (PreviousCRL == EntryCRL)
1240 return false;
1241 EntryCRL = EntryCRL.unionWith(PreviousCRL);
1242 }
1243
1244 A.addAttr(Attribute::get(A.getContext(), Attribute::Initializes,
1245 EntryCRL.rangesRef()));
1246
1247 return true;
1248}
1249
1250/// Deduce nocapture attributes for the SCC.
1251static void addArgumentAttrs(const SCCNodeSet &SCCNodes,
1253 bool SkipInitializes) {
1254 ArgumentGraph AG;
1255
1256 auto DetermineAccessAttrsForSingleton = [](Argument *A) {
1258 Self.insert(A);
1260 if (R != Attribute::None)
1261 return addAccessAttr(A, R);
1262 return false;
1263 };
1264
1265 // Check each function in turn, determining which pointer arguments are not
1266 // captured.
1267 for (Function *F : SCCNodes) {
1268 // We can infer and propagate function attributes only when we know that the
1269 // definition we'll get at link time is *exactly* the definition we see now.
1270 // For more details, see GlobalValue::mayBeDerefined.
1271 if (!F->hasExactDefinition())
1272 continue;
1273
1275 Changed.insert(F);
1276
1277 // Functions that are readonly (or readnone) and nounwind and don't return
1278 // a value can't capture arguments. Don't analyze them.
1279 if (F->onlyReadsMemory() && F->doesNotThrow() && F->willReturn() &&
1280 F->getReturnType()->isVoidTy()) {
1281 for (Argument &A : F->args()) {
1282 if (A.getType()->isPointerTy() && !A.hasNoCaptureAttr()) {
1283 A.addAttr(Attribute::getWithCaptureInfo(A.getContext(),
1285 ++NumCapturesNone;
1286 Changed.insert(F);
1287 }
1288 }
1289 continue;
1290 }
1291
1292 for (Argument &A : F->args()) {
1293 if (!A.getType()->isPointerTy())
1294 continue;
1295 bool HasNonLocalUses = false;
1296 CaptureInfo OrigCI = A.getAttributes().getCaptureInfo();
1297 if (!capturesNothing(OrigCI)) {
1298 ArgumentUsesTracker Tracker(SCCNodes);
1299 PointerMayBeCaptured(&A, &Tracker);
1300 CaptureInfo NewCI = Tracker.CI & OrigCI;
1301 if (NewCI != OrigCI) {
1302 if (Tracker.Uses.empty()) {
1303 // If the information is complete, add the attribute now.
1304 A.addAttr(Attribute::getWithCaptureInfo(A.getContext(), NewCI));
1305 addCapturesStat(NewCI);
1306 Changed.insert(F);
1307 } else {
1308 // If it's not trivially captured and not trivially not captured,
1309 // then it must be calling into another function in our SCC. Save
1310 // its particulars for Argument-SCC analysis later.
1311 ArgumentGraphNode *Node = AG[&A];
1312 Node->CC = CaptureComponents(NewCI);
1313 for (Argument *Use : Tracker.Uses) {
1314 Node->Uses.push_back(AG[Use]);
1315 if (Use != &A)
1316 HasNonLocalUses = true;
1317 }
1318 }
1319 }
1320 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
1321 }
1322 if (!HasNonLocalUses && !A.onlyReadsMemory()) {
1323 // Can we determine that it's readonly/readnone/writeonly without doing
1324 // an SCC? Note that we don't allow any calls at all here, or else our
1325 // result will be dependent on the iteration order through the
1326 // functions in the SCC.
1327 if (DetermineAccessAttrsForSingleton(&A))
1328 Changed.insert(F);
1329 }
1330 if (!SkipInitializes && !A.onlyReadsMemory()) {
1331 if (inferInitializes(A, *F))
1332 Changed.insert(F);
1333 }
1334 }
1335 }
1336
1337 // The graph we've collected is partial because we stopped scanning for
1338 // argument uses once we solved the argument trivially. These partial nodes
1339 // show up as ArgumentGraphNode objects with an empty Uses list, and for
1340 // these nodes the final decision about whether they capture has already been
1341 // made. If the definition doesn't have a 'nocapture' attribute by now, it
1342 // captures.
1343
1344 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
1345 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
1346 if (ArgumentSCC.size() == 1) {
1347 if (!ArgumentSCC[0]->Definition)
1348 continue; // synthetic root node
1349
1350 // eg. "void f(int* x) { if (...) f(x); }"
1351 if (ArgumentSCC[0]->Uses.size() == 1 &&
1352 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
1353 Argument *A = ArgumentSCC[0]->Definition;
1354 CaptureInfo OrigCI = A->getAttributes().getCaptureInfo();
1355 CaptureInfo NewCI = CaptureInfo(ArgumentSCC[0]->CC) & OrigCI;
1356 if (NewCI != OrigCI) {
1357 A->addAttr(Attribute::getWithCaptureInfo(A->getContext(), NewCI));
1358 addCapturesStat(NewCI);
1359 Changed.insert(A->getParent());
1360 }
1361
1362 // Infer the access attributes given the new captures one
1363 if (DetermineAccessAttrsForSingleton(A))
1364 Changed.insert(A->getParent());
1365 }
1366 continue;
1367 }
1368
1369 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
1370 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
1371 // quickly looking up whether a given Argument is in this ArgumentSCC.
1372 for (ArgumentGraphNode *I : ArgumentSCC) {
1373 ArgumentSCCNodes.insert(I->Definition);
1374 }
1375
1376 // At the SCC level, only track merged CaptureComponents. We're not
1377 // currently prepared to handle propagation of return-only captures across
1378 // the SCC.
1380 for (ArgumentGraphNode *N : ArgumentSCC) {
1381 for (ArgumentGraphNode *Use : N->Uses) {
1382 Argument *A = Use->Definition;
1383 if (ArgumentSCCNodes.count(A))
1384 CC |= Use->CC;
1385 else
1386 CC |= CaptureComponents(A->getAttributes().getCaptureInfo());
1387 break;
1388 }
1389 if (capturesAll(CC))
1390 break;
1391 }
1392
1393 if (!capturesAll(CC)) {
1394 for (ArgumentGraphNode *N : ArgumentSCC) {
1395 Argument *A = N->Definition;
1396 CaptureInfo OrigCI = A->getAttributes().getCaptureInfo();
1397 CaptureInfo NewCI = CaptureInfo(N->CC | CC) & OrigCI;
1398 if (NewCI != OrigCI) {
1399 A->addAttr(Attribute::getWithCaptureInfo(A->getContext(), NewCI));
1400 addCapturesStat(NewCI);
1401 Changed.insert(A->getParent());
1402 }
1403 }
1404 }
1405
1406 if (capturesAnyProvenance(CC)) {
1407 // As the pointer provenance may be captured, determine the pointer
1408 // attributes looking at each argument individually.
1409 for (ArgumentGraphNode *N : ArgumentSCC) {
1410 if (DetermineAccessAttrsForSingleton(N->Definition))
1411 Changed.insert(N->Definition->getParent());
1412 }
1413 continue;
1414 }
1415
1416 // We also want to compute readonly/readnone/writeonly. With a small number
1417 // of false negatives, we can assume that any pointer which is captured
1418 // isn't going to be provably readonly or readnone, since by definition
1419 // we can't analyze all uses of a captured pointer.
1420 //
1421 // The false negatives happen when the pointer is captured by a function
1422 // that promises readonly/readnone behaviour on the pointer, then the
1423 // pointer's lifetime ends before anything that writes to arbitrary memory.
1424 // Also, a readonly/readnone pointer may be returned, but returning a
1425 // pointer is capturing it.
1426
1427 auto meetAccessAttr = [](Attribute::AttrKind A, Attribute::AttrKind B) {
1428 if (A == B)
1429 return A;
1430 if (A == Attribute::ReadNone)
1431 return B;
1432 if (B == Attribute::ReadNone)
1433 return A;
1434 return Attribute::None;
1435 };
1436
1437 Attribute::AttrKind AccessAttr = Attribute::ReadNone;
1438 for (ArgumentGraphNode *N : ArgumentSCC) {
1439 Argument *A = N->Definition;
1440 Attribute::AttrKind K = determinePointerAccessAttrs(A, ArgumentSCCNodes);
1441 AccessAttr = meetAccessAttr(AccessAttr, K);
1442 if (AccessAttr == Attribute::None)
1443 break;
1444 }
1445
1446 if (AccessAttr != Attribute::None) {
1447 for (ArgumentGraphNode *N : ArgumentSCC) {
1448 Argument *A = N->Definition;
1449 if (addAccessAttr(A, AccessAttr))
1450 Changed.insert(A->getParent());
1451 }
1452 }
1453 }
1454}
1455
1456/// Tests whether a function is "malloc-like".
1457///
1458/// A function is "malloc-like" if it returns either null or a pointer that
1459/// doesn't alias any other pointer visible to the caller.
1460static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
1461 SmallSetVector<Value *, 8> FlowsToReturn;
1462 for (BasicBlock &BB : *F)
1463 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1464 FlowsToReturn.insert(Ret->getReturnValue());
1465
1466 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1467 Value *RetVal = FlowsToReturn[i];
1468
1469 if (Constant *C = dyn_cast<Constant>(RetVal)) {
1470 if (!C->isNullValue() && !isa<UndefValue>(C))
1471 return false;
1472
1473 continue;
1474 }
1475
1476 if (isa<Argument>(RetVal))
1477 return false;
1478
1479 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
1480 switch (RVI->getOpcode()) {
1481 // Extend the analysis by looking upwards.
1482 case Instruction::BitCast:
1483 case Instruction::GetElementPtr:
1484 case Instruction::AddrSpaceCast:
1485 FlowsToReturn.insert(RVI->getOperand(0));
1486 continue;
1487 case Instruction::Select: {
1489 FlowsToReturn.insert(SI->getTrueValue());
1490 FlowsToReturn.insert(SI->getFalseValue());
1491 continue;
1492 }
1493 case Instruction::PHI: {
1494 PHINode *PN = cast<PHINode>(RVI);
1495 FlowsToReturn.insert_range(PN->incoming_values());
1496 continue;
1497 }
1498
1499 // Check whether the pointer came from an allocation.
1500 case Instruction::Alloca:
1501 break;
1502 case Instruction::Call:
1503 case Instruction::Invoke: {
1504 CallBase &CB = cast<CallBase>(*RVI);
1505 if (CB.hasRetAttr(Attribute::NoAlias))
1506 break;
1507 if (CB.getCalledFunction() && SCCNodes.count(CB.getCalledFunction()))
1508 break;
1509 [[fallthrough]];
1510 }
1511 default:
1512 return false; // Did not come from an allocation.
1513 }
1514
1515 if (PointerMayBeCaptured(RetVal, /*ReturnCaptures=*/false))
1516 return false;
1517 }
1518
1519 return true;
1520}
1521
1522/// Deduce noalias attributes for the SCC.
1523static void addNoAliasAttrs(const SCCNodeSet &SCCNodes,
1525 // Check each function in turn, determining which functions return noalias
1526 // pointers.
1527 for (Function *F : SCCNodes) {
1528 // Already noalias.
1529 if (F->returnDoesNotAlias())
1530 continue;
1531
1532 // We can infer and propagate function attributes only when we know that the
1533 // definition we'll get at link time is *exactly* the definition we see now.
1534 // For more details, see GlobalValue::mayBeDerefined.
1535 if (!F->hasExactDefinition())
1536 return;
1537
1538 // We annotate noalias return values, which are only applicable to
1539 // pointer types.
1540 if (!F->getReturnType()->isPointerTy())
1541 continue;
1542
1543 if (!isFunctionMallocLike(F, SCCNodes))
1544 return;
1545 }
1546
1547 for (Function *F : SCCNodes) {
1548 if (F->returnDoesNotAlias() ||
1549 !F->getReturnType()->isPointerTy())
1550 continue;
1551
1552 F->setReturnDoesNotAlias();
1553 ++NumNoAlias;
1554 Changed.insert(F);
1555 }
1556}
1557
1558/// Tests whether this function is known to not return null.
1559///
1560/// Requires that the function returns a pointer.
1561///
1562/// Returns true if it believes the function will not return a null, and sets
1563/// \p Speculative based on whether the returned conclusion is a speculative
1564/// conclusion due to SCC calls.
1565static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
1566 bool &Speculative) {
1567 assert(F->getReturnType()->isPointerTy() &&
1568 "nonnull only meaningful on pointer types");
1569 Speculative = false;
1570
1571 SmallSetVector<Value *, 8> FlowsToReturn;
1572 for (BasicBlock &BB : *F)
1573 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1574 FlowsToReturn.insert(Ret->getReturnValue());
1575
1576 auto &DL = F->getDataLayout();
1577
1578 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1579 Value *RetVal = FlowsToReturn[i];
1580
1581 // If this value is locally known to be non-null, we're good
1582 if (isKnownNonZero(RetVal, DL))
1583 continue;
1584
1585 // Otherwise, we need to look upwards since we can't make any local
1586 // conclusions.
1587 Instruction *RVI = dyn_cast<Instruction>(RetVal);
1588 if (!RVI)
1589 return false;
1590 switch (RVI->getOpcode()) {
1591 // Extend the analysis by looking upwards.
1592 case Instruction::BitCast:
1593 case Instruction::AddrSpaceCast:
1594 FlowsToReturn.insert(RVI->getOperand(0));
1595 continue;
1596 case Instruction::GetElementPtr:
1597 if (cast<GEPOperator>(RVI)->isInBounds()) {
1598 FlowsToReturn.insert(RVI->getOperand(0));
1599 continue;
1600 }
1601 return false;
1602 case Instruction::Select: {
1604 FlowsToReturn.insert(SI->getTrueValue());
1605 FlowsToReturn.insert(SI->getFalseValue());
1606 continue;
1607 }
1608 case Instruction::PHI: {
1609 PHINode *PN = cast<PHINode>(RVI);
1610 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1611 FlowsToReturn.insert(PN->getIncomingValue(i));
1612 continue;
1613 }
1614 case Instruction::Call:
1615 case Instruction::Invoke: {
1616 CallBase &CB = cast<CallBase>(*RVI);
1617 Function *Callee = CB.getCalledFunction();
1618 // A call to a node within the SCC is assumed to return null until
1619 // proven otherwise
1620 if (Callee && SCCNodes.count(Callee)) {
1621 Speculative = true;
1622 continue;
1623 }
1624 return false;
1625 }
1626 default:
1627 return false; // Unknown source, may be null
1628 };
1629 llvm_unreachable("should have either continued or returned");
1630 }
1631
1632 return true;
1633}
1634
1635/// Deduce nonnull attributes for the SCC.
1636static void addNonNullAttrs(const SCCNodeSet &SCCNodes,
1638 // Speculative that all functions in the SCC return only nonnull
1639 // pointers. We may refute this as we analyze functions.
1640 bool SCCReturnsNonNull = true;
1641
1642 // Check each function in turn, determining which functions return nonnull
1643 // pointers.
1644 for (Function *F : SCCNodes) {
1645 // Already nonnull.
1646 if (F->getAttributes().hasRetAttr(Attribute::NonNull))
1647 continue;
1648
1649 // We can infer and propagate function attributes only when we know that the
1650 // definition we'll get at link time is *exactly* the definition we see now.
1651 // For more details, see GlobalValue::mayBeDerefined.
1652 if (!F->hasExactDefinition())
1653 return;
1654
1655 // We annotate nonnull return values, which are only applicable to
1656 // pointer types.
1657 if (!F->getReturnType()->isPointerTy())
1658 continue;
1659
1660 bool Speculative = false;
1661 if (isReturnNonNull(F, SCCNodes, Speculative)) {
1662 if (!Speculative) {
1663 // Mark the function eagerly since we may discover a function
1664 // which prevents us from speculating about the entire SCC
1665 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1666 << " as nonnull\n");
1667 F->addRetAttr(Attribute::NonNull);
1668 ++NumNonNullReturn;
1669 Changed.insert(F);
1670 }
1671 continue;
1672 }
1673 // At least one function returns something which could be null, can't
1674 // speculate any more.
1675 SCCReturnsNonNull = false;
1676 }
1677
1678 if (SCCReturnsNonNull) {
1679 for (Function *F : SCCNodes) {
1680 if (F->getAttributes().hasRetAttr(Attribute::NonNull) ||
1681 !F->getReturnType()->isPointerTy())
1682 continue;
1683
1684 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1685 F->addRetAttr(Attribute::NonNull);
1686 ++NumNonNullReturn;
1687 Changed.insert(F);
1688 }
1689 }
1690}
1691
1692/// Deduce noundef attributes for the SCC.
1693static void addNoUndefAttrs(const SCCNodeSet &SCCNodes,
1695 // Check each function in turn, determining which functions return noundef
1696 // values.
1697 for (Function *F : SCCNodes) {
1698 // Already noundef.
1699 AttributeList Attrs = F->getAttributes();
1700 if (Attrs.hasRetAttr(Attribute::NoUndef))
1701 continue;
1702
1703 // We can infer and propagate function attributes only when we know that the
1704 // definition we'll get at link time is *exactly* the definition we see now.
1705 // For more details, see GlobalValue::mayBeDerefined.
1706 if (!F->hasExactDefinition())
1707 return;
1708
1709 // MemorySanitizer assumes that the definition and declaration of a
1710 // function will be consistent. A function with sanitize_memory attribute
1711 // should be skipped from inference.
1712 if (F->hasFnAttribute(Attribute::SanitizeMemory))
1713 continue;
1714
1715 if (F->getReturnType()->isVoidTy())
1716 continue;
1717
1718 const DataLayout &DL = F->getDataLayout();
1719 if (all_of(*F, [&](BasicBlock &BB) {
1720 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
1721 // TODO: perform context-sensitive analysis?
1722 Value *RetVal = Ret->getReturnValue();
1724 return false;
1725
1726 // We know the original return value is not poison now, but it
1727 // could still be converted to poison by another return attribute.
1728 // Try to explicitly re-prove the relevant attributes.
1729 if (Attrs.hasRetAttr(Attribute::NonNull) &&
1730 !isKnownNonZero(RetVal, DL))
1731 return false;
1732
1733 if (MaybeAlign Align = Attrs.getRetAlignment())
1734 if (RetVal->getPointerAlignment(DL) < *Align)
1735 return false;
1736
1737 Attribute Attr = Attrs.getRetAttr(Attribute::Range);
1738 if (Attr.isValid() &&
1739 !Attr.getRange().contains(
1740 computeConstantRange(RetVal, /*ForSigned=*/false,
1741 SimplifyQuery(F->getDataLayout()))))
1742 return false;
1743
1744 FPClassTest AttrFPClass = Attrs.getRetNoFPClass();
1745 if (AttrFPClass != fcNone) {
1746 KnownFPClass ComputedFPClass = computeKnownFPClass(RetVal, DL);
1747 if (!ComputedFPClass.isKnownNever(AttrFPClass))
1748 return false;
1749 }
1750 }
1751 return true;
1752 })) {
1753 F->addRetAttr(Attribute::NoUndef);
1754 ++NumNoUndefReturn;
1755 Changed.insert(F);
1756 }
1757 }
1758}
1759
1760namespace {
1761
1762/// Collects a set of attribute inference requests and performs them all in one
1763/// go on a single SCC Node. Inference involves scanning function bodies
1764/// looking for instructions that violate attribute assumptions.
1765/// As soon as all the bodies are fine we are free to set the attribute.
1766/// Customization of inference for individual attributes is performed by
1767/// providing a handful of predicates for each attribute.
1768class AttributeInferer {
1769public:
1770 /// Describes a request for inference of a single attribute.
1771 struct InferenceDescriptor {
1772
1773 /// Returns true if this function does not have to be handled.
1774 /// General intent for this predicate is to provide an optimization
1775 /// for functions that do not need this attribute inference at all
1776 /// (say, for functions that already have the attribute).
1777 std::function<bool(const Function &)> SkipFunction;
1778
1779 /// Returns true if this instruction violates attribute assumptions.
1780 std::function<bool(Instruction &)> InstrBreaksAttribute;
1781
1782 /// Sets the inferred attribute for this function.
1783 std::function<void(Function &)> SetAttribute;
1784
1785 /// Attribute we derive.
1786 Attribute::AttrKind AKind;
1787
1788 /// If true, only "exact" definitions can be used to infer this attribute.
1789 /// See GlobalValue::isDefinitionExact.
1790 bool RequiresExactDefinition;
1791
1792 InferenceDescriptor(Attribute::AttrKind AK,
1793 std::function<bool(const Function &)> SkipFunc,
1794 std::function<bool(Instruction &)> InstrScan,
1795 std::function<void(Function &)> SetAttr,
1796 bool ReqExactDef)
1797 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1798 SetAttribute(SetAttr), AKind(AK),
1799 RequiresExactDefinition(ReqExactDef) {}
1800 };
1801
1802private:
1803 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1804
1805public:
1806 void registerAttrInference(InferenceDescriptor AttrInference) {
1807 InferenceDescriptors.push_back(AttrInference);
1808 }
1809
1810 void run(const SCCNodeSet &SCCNodes, SmallPtrSet<Function *, 8> &Changed);
1811};
1812
1813/// Perform all the requested attribute inference actions according to the
1814/// attribute predicates stored before.
1815void AttributeInferer::run(const SCCNodeSet &SCCNodes,
1816 SmallPtrSet<Function *, 8> &Changed) {
1817 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1818 // Go through all the functions in SCC and check corresponding attribute
1819 // assumptions for each of them. Attributes that are invalid for this SCC
1820 // will be removed from InferInSCC.
1821 for (Function *F : SCCNodes) {
1822
1823 // No attributes whose assumptions are still valid - done.
1824 if (InferInSCC.empty())
1825 return;
1826
1827 // Check if our attributes ever need scanning/can be scanned.
1828 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1829 if (ID.SkipFunction(*F))
1830 return false;
1831
1832 // Remove from further inference (invalidate) when visiting a function
1833 // that has no instructions to scan/has an unsuitable definition.
1834 return F->isDeclaration() ||
1835 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1836 });
1837
1838 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1839 // set up the F instructions scan to verify assumptions of the attribute.
1842 InferInSCC, std::back_inserter(InferInThisFunc),
1843 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1844
1845 if (InferInThisFunc.empty())
1846 continue;
1847
1848 // Start instruction scan.
1849 for (Instruction &I : instructions(*F)) {
1850 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1851 if (!ID.InstrBreaksAttribute(I))
1852 return false;
1853 // Remove attribute from further inference on any other functions
1854 // because attribute assumptions have just been violated.
1855 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1856 return D.AKind == ID.AKind;
1857 });
1858 // Remove attribute from the rest of current instruction scan.
1859 return true;
1860 });
1861
1862 if (InferInThisFunc.empty())
1863 break;
1864 }
1865 }
1866
1867 if (InferInSCC.empty())
1868 return;
1869
1870 for (Function *F : SCCNodes)
1871 // At this point InferInSCC contains only functions that were either:
1872 // - explicitly skipped from scan/inference, or
1873 // - verified to have no instructions that break attribute assumptions.
1874 // Hence we just go and force the attribute for all non-skipped functions.
1875 for (auto &ID : InferInSCC) {
1876 if (ID.SkipFunction(*F))
1877 continue;
1878 Changed.insert(F);
1879 ID.SetAttribute(*F);
1880 }
1881}
1882
1883struct SCCNodesResult {
1884 SCCNodeSet SCCNodes;
1885};
1886
1887} // end anonymous namespace
1888
1889/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1891 const SCCNodeSet &SCCNodes) {
1892 const CallBase *CB = dyn_cast<CallBase>(&I);
1893 // Breaks non-convergent assumption if CS is a convergent call to a function
1894 // not in the SCC.
1895 return CB && CB->isConvergent() &&
1896 !SCCNodes.contains(CB->getCalledFunction());
1897}
1898
1899/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1900static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1901 if (!I.mayThrow(/* IncludePhaseOneUnwind */ true))
1902 return false;
1903 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1904 if (Function *Callee = CI->getCalledFunction()) {
1905 // I is a may-throw call to a function inside our SCC. This doesn't
1906 // invalidate our current working assumption that the SCC is no-throw; we
1907 // just have to scan that other function.
1908 if (SCCNodes.contains(Callee))
1909 return false;
1910 }
1911 }
1912 return true;
1913}
1914
1915/// Helper for NoFree inference predicate InstrBreaksAttribute.
1916static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes) {
1918 if (!CB) {
1919 // Synchronization may establish happens-before with a free on another
1920 // thread.
1921 return I.maySynchronize();
1922 }
1923
1924 if (CB->hasFnAttr(Attribute::NoFree))
1925 return false;
1926
1927 // Speculatively assume in SCC.
1928 if (Function *Callee = CB->getCalledFunction())
1929 if (SCCNodes.contains(Callee))
1930 return false;
1931
1932 return true;
1933}
1934
1935static bool InstrBreaksNoSync(Instruction &I, const SCCNodeSet &SCCNodes) {
1936 if (!I.maySynchronize())
1937 return false;
1938
1939 // Optimistically assume calls within the SCC are nosync: if nothing else in
1940 // the SCC synchronizes, the assumption holds.
1941 if (auto *CB = dyn_cast<CallBase>(&I))
1942 if (Function *Callee = CB->getCalledFunction())
1943 if (SCCNodes.contains(Callee))
1944 return false;
1945
1946 return true;
1947}
1948
1949/// Attempt to remove convergent function attribute when possible.
1950///
1951/// Returns true if any changes to function attributes were made.
1952static void inferConvergent(const SCCNodeSet &SCCNodes,
1954 AttributeInferer AI;
1955
1956 // Request to remove the convergent attribute from all functions in the SCC
1957 // if every callsite within the SCC is not convergent (except for calls
1958 // to functions within the SCC).
1959 // Note: Removal of the attr from the callsites will happen in
1960 // InstCombineCalls separately.
1961 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1962 Attribute::Convergent,
1963 // Skip non-convergent functions.
1964 [](const Function &F) { return !F.isConvergent(); },
1965 // Instructions that break non-convergent assumption.
1966 [SCCNodes](Instruction &I) {
1967 return InstrBreaksNonConvergent(I, SCCNodes);
1968 },
1969 [](Function &F) {
1970 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1971 << "\n");
1972 F.setNotConvergent();
1973 },
1974 /* RequiresExactDefinition= */ false});
1975 // Perform all the requested attribute inference actions.
1976 AI.run(SCCNodes, Changed);
1977}
1978
1979/// Infer attributes from all functions in the SCC by scanning every
1980/// instruction for compliance to the attribute assumptions.
1981///
1982/// Returns true if any changes to function attributes were made.
1983static void inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes,
1985 AttributeInferer AI;
1986
1988 // Request to infer nounwind attribute for all the functions in the SCC if
1989 // every callsite within the SCC is not throwing (except for calls to
1990 // functions within the SCC). Note that nounwind attribute suffers from
1991 // derefinement - results may change depending on how functions are
1992 // optimized. Thus it can be inferred only from exact definitions.
1993 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1994 Attribute::NoUnwind,
1995 // Skip non-throwing functions.
1996 [](const Function &F) { return F.doesNotThrow(); },
1997 // Instructions that break non-throwing assumption.
1998 [&SCCNodes](Instruction &I) {
1999 return InstrBreaksNonThrowing(I, SCCNodes);
2000 },
2001 [](Function &F) {
2003 << "Adding nounwind attr to fn " << F.getName() << "\n");
2004 F.setDoesNotThrow();
2005 ++NumNoUnwind;
2006 },
2007 /* RequiresExactDefinition= */ true});
2008
2010 // Request to infer nofree attribute for all the functions in the SCC if
2011 // every callsite within the SCC does not directly or indirectly free
2012 // memory (except for calls to functions within the SCC). Note that nofree
2013 // attribute suffers from derefinement - results may change depending on
2014 // how functions are optimized. Thus it can be inferred only from exact
2015 // definitions.
2016 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
2017 Attribute::NoFree,
2018 // Skip functions known not to free memory.
2019 [](const Function &F) { return F.doesNotFreeMemory(); },
2020 // Instructions that break non-deallocating assumption.
2021 [&SCCNodes](Instruction &I) {
2022 return InstrBreaksNoFree(I, SCCNodes);
2023 },
2024 [](Function &F) {
2026 << "Adding nofree attr to fn " << F.getName() << "\n");
2027 F.setDoesNotFreeMemory();
2028 ++NumNoFree;
2029 },
2030 /* RequiresExactDefinition= */ true});
2031
2032 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
2033 Attribute::NoSync,
2034 // Skip already marked functions.
2035 [](const Function &F) { return F.hasNoSync(); },
2036 // Instructions that break nosync assumption.
2037 [&SCCNodes](Instruction &I) {
2038 return InstrBreaksNoSync(I, SCCNodes);
2039 },
2040 [](Function &F) {
2042 << "Adding nosync attr to fn " << F.getName() << "\n");
2043 F.setNoSync();
2044 ++NumNoSync;
2045 },
2046 /* RequiresExactDefinition= */ true});
2047
2048 // Perform all the requested attribute inference actions.
2049 AI.run(SCCNodes, Changed);
2050}
2051
2052// Determines if the function 'F' can be marked 'norecurse'.
2053// It returns true if any call within 'F' could lead to a recursive
2054// call back to 'F', and false otherwise.
2055// The 'AnyFunctionsAddressIsTaken' parameter is a module-wide flag
2056// that is true if any function's address is taken, or if any function
2057// has external linkage. This is used to determine the safety of
2058// external/library calls.
2060 bool AnyFunctionsAddressIsTaken = true) {
2061 for (const auto &BB : F) {
2062 for (const auto &I : BB) {
2063 if (const auto *CB = dyn_cast<CallBase>(&I)) {
2064 const Function *Callee = CB->getCalledFunction();
2065 if (!Callee || Callee == &F)
2066 return true;
2067
2068 if (Callee->doesNotRecurse())
2069 continue;
2070
2071 if (!AnyFunctionsAddressIsTaken ||
2072 (Callee->isDeclaration() &&
2073 Callee->hasFnAttribute(Attribute::NoCallback)))
2074 continue;
2075 return true;
2076 }
2077 }
2078 }
2079 return false;
2080}
2081
2082static void addNoRecurseAttrs(const SCCNodeSet &SCCNodes,
2084 // Try and identify functions that do not recurse.
2085
2086 // If the SCC contains multiple nodes we know for sure there is recursion.
2087 if (SCCNodes.size() != 1)
2088 return;
2089
2090 Function *F = *SCCNodes.begin();
2091 if (!F || !F->hasExactDefinition() || F->doesNotRecurse())
2092 return;
2093 if (!mayHaveRecursiveCallee(*F)) {
2094 // Every call was to a non-recursive function other than this function, and
2095 // we have no indirect recursion as the SCC size is one. This function
2096 // cannot recurse.
2097 F->setDoesNotRecurse();
2098 ++NumNoRecurse;
2099 Changed.insert(F);
2100 }
2101}
2102
2103// Set the noreturn function attribute if possible.
2104static void addNoReturnAttrs(const SCCNodeSet &SCCNodes,
2106 for (Function *F : SCCNodes) {
2107 if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
2108 F->doesNotReturn())
2109 continue;
2110
2111 if (!canReturn(*F)) {
2112 F->setDoesNotReturn();
2113 Changed.insert(F);
2114 }
2115 }
2116}
2117
2120 ColdPaths[&F.front()] = false;
2122 Jobs.push_back(&F.front());
2123
2124 while (!Jobs.empty()) {
2125 BasicBlock *BB = Jobs.pop_back_val();
2126
2127 // If block contains a cold callsite this path through the CG is cold.
2128 // Ignore whether the instructions actually are guaranteed to transfer
2129 // execution. Divergent behavior is considered unlikely.
2130 if (any_of(*BB, [](Instruction &I) {
2131 if (auto *CB = dyn_cast<CallBase>(&I))
2132 return CB->hasFnAttr(Attribute::Cold);
2133 return false;
2134 })) {
2135 ColdPaths[BB] = true;
2136 continue;
2137 }
2138
2139 auto Succs = successors(BB);
2140 // We found a path that doesn't go through any cold callsite.
2141 if (Succs.empty())
2142 return false;
2143
2144 // We didn't find a cold callsite in this BB, so check that all successors
2145 // contain a cold callsite (or that their successors do).
2146 // Potential TODO: We could use static branch hints to assume certain
2147 // successor paths are inherently cold, irrespective of if they contain a
2148 // cold callsite.
2149 for (BasicBlock *Succ : Succs) {
2150 // Start with false, this is necessary to ensure we don't turn loops into
2151 // cold.
2152 auto [Iter, Inserted] = ColdPaths.try_emplace(Succ, false);
2153 if (!Inserted) {
2154 if (Iter->second)
2155 continue;
2156 return false;
2157 }
2158 Jobs.push_back(Succ);
2159 }
2160 }
2161 return true;
2162}
2163
2164// Set the cold function attribute if possible.
2165static void addColdAttrs(const SCCNodeSet &SCCNodes,
2167 for (Function *F : SCCNodes) {
2168 if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
2169 F->hasFnAttribute(Attribute::Cold) || F->hasFnAttribute(Attribute::Hot))
2170 continue;
2171
2172 // Potential TODO: We could add attribute `cold` on functions with `coldcc`.
2173 if (allPathsGoThroughCold(*F)) {
2174 F->addFnAttr(Attribute::Cold);
2175 ++NumCold;
2176 Changed.insert(F);
2177 continue;
2178 }
2179 }
2180}
2181
2182static bool functionWillReturn(const Function &F) {
2183 // We can infer and propagate function attributes only when we know that the
2184 // definition we'll get at link time is *exactly* the definition we see now.
2185 // For more details, see GlobalValue::mayBeDerefined.
2186 if (!F.hasExactDefinition())
2187 return false;
2188
2189 // Must-progress function without side-effects must return.
2190 if (F.mustProgress() && F.onlyReadsMemory())
2191 return true;
2192
2193 // Can only analyze functions with a definition.
2194 if (F.isDeclaration())
2195 return false;
2196
2197 // Functions with loops require more sophisticated analysis, as the loop
2198 // may be infinite. For now, don't try to handle them.
2200 FindFunctionBackedges(F, Backedges);
2201 if (!Backedges.empty())
2202 return false;
2203
2204 // If there are no loops, then the function is willreturn if all calls in
2205 // it are willreturn.
2206 return all_of(instructions(F), [](const Instruction &I) {
2207 return I.willReturn();
2208 });
2209}
2210
2211// Set the willreturn function attribute if possible.
2212static void addWillReturn(const SCCNodeSet &SCCNodes,
2214 for (Function *F : SCCNodes) {
2215 if (!F || F->willReturn() || !functionWillReturn(*F))
2216 continue;
2217
2218 F->setWillReturn();
2219 NumWillReturn++;
2220 Changed.insert(F);
2221 }
2222}
2223
2224static SCCNodesResult createSCCNodeSet(ArrayRef<Function *> Functions) {
2225 SCCNodesResult Res;
2226 for (Function *F : Functions) {
2227 if (!F || F->hasOptNone() || F->hasFnAttribute(Attribute::Naked) ||
2228 F->isPresplitCoroutine()) {
2229 // Omit any functions we're trying not to optimize from the set.
2230 continue;
2231 }
2232
2233 Res.SCCNodes.insert(F);
2234 }
2235 return Res;
2236}
2237
2238template <typename AARGetterT>
2240deriveAttrsInPostOrder(ArrayRef<Function *> Functions, AARGetterT &&AARGetter,
2241 bool ArgAttrsOnly) {
2242 SCCNodesResult Nodes = createSCCNodeSet(Functions);
2243
2244 // Bail if the SCC only contains optnone functions.
2245 if (Nodes.SCCNodes.empty())
2246 return {};
2247
2249 if (ArgAttrsOnly) {
2250 // ArgAttrsOnly means to only infer attributes that may aid optimizations
2251 // on the *current* function. "initializes" attribute is to aid
2252 // optimizations (like DSE) on the callers, so skip "initializes" here.
2253 addArgumentAttrs(Nodes.SCCNodes, Changed, /*SkipInitializes=*/true);
2254 return Changed;
2255 }
2256
2257 addArgumentReturnedAttrs(Nodes.SCCNodes, Changed);
2258 addMemoryAttrs(Nodes.SCCNodes, AARGetter, Changed);
2259 addArgumentAttrs(Nodes.SCCNodes, Changed, /*SkipInitializes=*/false);
2260 inferConvergent(Nodes.SCCNodes, Changed);
2261 addNoReturnAttrs(Nodes.SCCNodes, Changed);
2262 addColdAttrs(Nodes.SCCNodes, Changed);
2263 addWillReturn(Nodes.SCCNodes, Changed);
2264 addNoUndefAttrs(Nodes.SCCNodes, Changed);
2265 addNoAliasAttrs(Nodes.SCCNodes, Changed);
2266 addNonNullAttrs(Nodes.SCCNodes, Changed);
2267 inferAttrsFromFunctionBodies(Nodes.SCCNodes, Changed);
2268 addNoRecurseAttrs(Nodes.SCCNodes, Changed);
2269
2270 // Finally, infer the maximal set of attributes from the ones we've inferred
2271 // above. This is handling the cases where one attribute on a signature
2272 // implies another, but for implementation reasons the inference rule for
2273 // the later is missing (or simply less sophisticated).
2274 for (Function *F : Nodes.SCCNodes)
2275 if (F)
2277 Changed.insert(F);
2278
2279 return Changed;
2280}
2281
2284 LazyCallGraph &CG,
2286 // Skip non-recursive functions if requested.
2287 // Only infer argument attributes for non-recursive functions, because
2288 // it can affect optimization behavior in conjunction with noalias.
2289 bool ArgAttrsOnly = false;
2290 if (C.size() == 1 && SkipNonRecursive) {
2291 LazyCallGraph::Node &N = *C.begin();
2292 if (!N->lookup(N))
2293 ArgAttrsOnly = true;
2294 }
2295
2297 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2298
2299 // We pass a lambda into functions to wire them up to the analysis manager
2300 // for getting function analyses.
2301 auto AARGetter = [&](Function &F) -> AAResults & {
2302 return FAM.getResult<AAManager>(F);
2303 };
2304
2306 for (LazyCallGraph::Node &N : C) {
2307 Functions.push_back(&N.getFunction());
2308 }
2309
2310 auto ChangedFunctions =
2311 deriveAttrsInPostOrder(Functions, AARGetter, ArgAttrsOnly);
2312 if (ChangedFunctions.empty())
2313 return PreservedAnalyses::all();
2314
2315 // Invalidate analyses for modified functions so that we don't have to
2316 // invalidate all analyses for all functions in this SCC.
2317 PreservedAnalyses FuncPA;
2318 // We haven't changed the CFG for modified functions.
2319 FuncPA.preserveSet<CFGAnalyses>();
2320 for (Function *Changed : ChangedFunctions) {
2321 FAM.invalidate(*Changed, FuncPA);
2322 // Also invalidate any direct callers of changed functions since analyses
2323 // may care about attributes of direct callees. For example, MemorySSA cares
2324 // about whether or not a call's callee modifies memory and queries that
2325 // through function attributes.
2326 for (auto *U : Changed->users()) {
2327 if (auto *Call = dyn_cast<CallBase>(U)) {
2328 if (Call->getCalledOperand() == Changed)
2329 FAM.invalidate(*Call->getFunction(), FuncPA);
2330 }
2331 }
2332 }
2333
2335 // We have not added or removed functions.
2337 // We already invalidated all relevant function analyses above.
2339 return PA;
2340}
2341
2343 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
2345 OS, MapClassName2PassName);
2346 if (SkipNonRecursive)
2347 OS << "<skip-non-recursive-function-attrs>";
2348}
2349
2350template <typename AARGetterT>
2351static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
2353 for (CallGraphNode *I : SCC) {
2354 Functions.push_back(I->getFunction());
2355 }
2356
2357 return !deriveAttrsInPostOrder(Functions, AARGetter).empty();
2358}
2359
2361 if (F.doesNotRecurse())
2362 return false;
2363
2364 // We check the preconditions for the function prior to calling this to avoid
2365 // the cost of building up a reversible post-order list. We assert them here
2366 // to make sure none of the invariants this relies on were violated.
2367 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
2368 assert(F.hasInternalLinkage() &&
2369 "Can only do top-down deduction for internal linkage functions!");
2370
2371 // If F is internal and all of its uses are calls from a non-recursive
2372 // functions, then none of its calls could in fact recurse without going
2373 // through a function marked norecurse, and so we can mark this function too
2374 // as norecurse. Note that the uses must actually be calls -- otherwise
2375 // a pointer to this function could be returned from a norecurse function but
2376 // this function could be recursively (indirectly) called. Note that this
2377 // also detects if F is directly recursive as F is not yet marked as
2378 // a norecurse function.
2379 for (auto &U : F.uses()) {
2380 const CallBase *CB = dyn_cast<CallBase>(U.getUser());
2381 if (!CB || !CB->isCallee(&U) ||
2382 !CB->getParent()->getParent()->doesNotRecurse())
2383 return false;
2384 }
2385 F.setDoesNotRecurse();
2386 ++NumNoRecurse;
2387 return true;
2388}
2389
2391 assert(!F.isDeclaration() && "Cannot deduce nofpclass without a definition!");
2392 unsigned NumArgs = F.arg_size();
2393 SmallVector<FPClassTest, 8> ArgsNoFPClass(NumArgs, fcAllFlags);
2394 FPClassTest RetNoFPClass = fcAllFlags;
2395
2396 bool Changed = false;
2397 for (User *U : F.users()) {
2398 auto *CB = dyn_cast<CallBase>(U);
2399 if (!CB || CB->getCalledFunction() != &F)
2400 return false;
2401
2402 RetNoFPClass &= CB->getRetNoFPClass();
2403 for (unsigned I = 0; I != NumArgs; ++I) {
2404 // TODO: Consider computeKnownFPClass, at least with a small search
2405 // depth. This will currently not catch non-splat vectors.
2406 const APFloat *Cst;
2407 if (match(CB->getArgOperand(I), m_APFloat(Cst)))
2408 ArgsNoFPClass[I] &= ~Cst->classify();
2409 else
2410 ArgsNoFPClass[I] &= CB->getParamNoFPClass(I);
2411 }
2412 }
2413
2414 LLVMContext &Ctx = F.getContext();
2415
2416 if (RetNoFPClass != fcNone) {
2417 FPClassTest OldAttr = F.getAttributes().getRetNoFPClass();
2418 if (OldAttr != RetNoFPClass) {
2419 F.addRetAttr(Attribute::getWithNoFPClass(Ctx, RetNoFPClass));
2420 Changed = true;
2421 }
2422 }
2423
2424 for (unsigned I = 0; I != NumArgs; ++I) {
2425 FPClassTest ArgNoFPClass = ArgsNoFPClass[I];
2426 if (ArgNoFPClass == fcNone)
2427 continue;
2428 FPClassTest OldAttr = F.getParamNoFPClass(I);
2429 if (OldAttr == ArgNoFPClass)
2430 continue;
2431
2432 F.addParamAttr(I, Attribute::getWithNoFPClass(Ctx, ArgNoFPClass));
2433 Changed = true;
2434 }
2435
2436 return Changed;
2437}
2438
2440 // We only have a post-order SCC traversal (because SCCs are inherently
2441 // discovered in post-order), so we accumulate them in a vector and then walk
2442 // it in reverse. This is simpler than using the RPO iterator infrastructure
2443 // because we need to combine SCC detection and the PO walk of the call
2444 // graph. We can also cheat egregiously because we're primarily interested in
2445 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
2446 // with multiple functions in them will clearly be recursive.
2447
2449 CG.buildRefSCCs();
2450 for (LazyCallGraph::RefSCC &RC : CG.postorder_ref_sccs()) {
2451 for (LazyCallGraph::SCC &SCC : RC) {
2452 if (SCC.size() != 1)
2453 continue;
2454 Function &F = SCC.begin()->getFunction();
2455 if (!F.isDeclaration() && F.hasInternalLinkage() && !F.use_empty())
2456 Worklist.push_back(&F);
2457 }
2458 }
2459 bool Changed = false;
2460 for (auto *F : llvm::reverse(Worklist)) {
2463 }
2464
2465 return Changed;
2466}
2467
2470 auto &CG = AM.getResult<LazyCallGraphAnalysis>(M);
2471
2472 if (!deduceFunctionAttributeInRPO(M, CG))
2473 return PreservedAnalyses::all();
2474
2477 return PA;
2478}
2479
2482
2483 // Check if any function in the whole program has its address taken or has
2484 // potentially external linkage.
2485 // We use this information when inferring norecurse attribute: If there is
2486 // no function whose address is taken and all functions have internal
2487 // linkage, there is no path for a callback to any user function.
2488 bool AnyFunctionsAddressIsTaken = false;
2489 for (Function &F : M) {
2490 if (F.isDeclaration() || F.doesNotRecurse())
2491 continue;
2492 if (!F.hasLocalLinkage() || F.hasAddressTaken()) {
2493 AnyFunctionsAddressIsTaken = true;
2494 break;
2495 }
2496 }
2497
2498 // Run norecurse inference on all RefSCCs in the LazyCallGraph for this
2499 // module.
2500 bool Changed = false;
2501 LazyCallGraph &CG = MAM.getResult<LazyCallGraphAnalysis>(M);
2502 CG.buildRefSCCs();
2503
2504 for (LazyCallGraph::RefSCC &RC : CG.postorder_ref_sccs()) {
2505 // Skip any RefSCC that is part of a call cycle. A RefSCC containing more
2506 // than one SCC indicates a recursive relationship involving indirect calls.
2507 if (RC.size() > 1)
2508 continue;
2509
2510 // RefSCC contains a single-SCC. SCC size > 1 indicates mutually recursive
2511 // functions. Ex: foo1 -> foo2 -> foo3 -> foo1.
2512 LazyCallGraph::SCC &S = *RC.begin();
2513 if (S.size() > 1)
2514 continue;
2515
2516 // Get the single function from this SCC.
2517 Function &F = S.begin()->getFunction();
2518 if (!F.hasExactDefinition() || F.doesNotRecurse())
2519 continue;
2520
2521 // If the analysis confirms that this function has no recursive calls
2522 // (either direct, indirect, or through external linkages),
2523 // we can safely apply the norecurse attribute.
2524 if (!mayHaveRecursiveCallee(F, AnyFunctionsAddressIsTaken)) {
2525 F.setDoesNotRecurse();
2526 ++NumNoRecurse;
2527 Changed = true;
2528 }
2529 }
2530
2532 if (Changed)
2534 else
2536 return PA;
2537}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This header provides classes for managing passes over SCCs of the call graph.
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
DXIL Resource Access
This file defines the DenseMap class.
static bool runImpl(Function &F, const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, AssumptionCache *AC)
static SmallPtrSet< Function *, 8 > deriveAttrsInPostOrder(ArrayRef< Function * > Functions, AARGetterT &&AARGetter, bool ArgAttrsOnly)
static Attribute::AttrKind determinePointerAccessAttrs(Argument *A, const SmallPtrSet< Argument *, 8 > &SCCNodes)
Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
static cl::opt< bool > DisableNoFreeInference("disable-nofree-inference", cl::Hidden, cl::desc("Stop inferring nofree attribute during function-attrs pass"))
static bool inferInitializes(Argument &A, Function &F)
static bool allPathsGoThroughCold(Function &F)
static bool addAccessAttr(Argument *A, Attribute::AttrKind R)
static FunctionSummary * calculatePrevailingSummary(ValueInfo VI, DenseMap< ValueInfo, FunctionSummary * > &CachedPrevailingSummary, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing)
static void addMemoryAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter, SmallPtrSet< Function *, 8 > &Changed)
Deduce readonly/readnone/writeonly attributes for the SCC.
static bool addArgumentAttrsFromCallsites(Function &F)
If a callsite has arguments that are also arguments to the parent function, try to propagate attribut...
static void addCapturesStat(CaptureInfo CI)
static void addArgLocs(MemoryEffects &ME, const CallBase *Call, ModRefInfo ArgMR, AAResults &AAR)
static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes)
Tests whether a function is "malloc-like".
static void addColdAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static bool mayHaveRecursiveCallee(Function &F, bool AnyFunctionsAddressIsTaken=true)
static void addNoReturnAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static bool addNoFPClassAttrsTopDown(Function &F)
static cl::opt< bool > DisableNoUnwindInference("disable-nounwind-inference", cl::Hidden, cl::desc("Stop inferring nounwind attribute during function-attrs pass"))
static void addWillReturn(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static void addNonNullAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce nonnull attributes for the SCC.
static std::pair< MemoryEffects, MemoryEffects > checkFunctionMemoryAccess(Function &F, bool ThisBody, AAResults &AAR, const SCCNodeSet &SCCNodes)
Returns the memory access attribute for function F using AAR for AA results, where SCCNodes is the cu...
static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes)
Helper for NoUnwind inference predicate InstrBreaksAttribute.
static void inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Infer attributes from all functions in the SCC by scanning every instruction for compliance to the at...
static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes, bool &Speculative)
Tests whether this function is known to not return null.
static bool InstrBreaksNoSync(Instruction &I, const SCCNodeSet &SCCNodes)
static bool deduceFunctionAttributeInRPO(Module &M, LazyCallGraph &CG)
static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes)
Helper for NoFree inference predicate InstrBreaksAttribute.
static cl::opt< bool > EnablePoisonArgAttrPropagation("enable-poison-arg-attr-prop", cl::init(true), cl::Hidden, cl::desc("Try to propagate nonnull and nofpclass argument attributes from " "callsites to caller functions."))
static void addNoAliasAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce noalias attributes for the SCC.
static bool addNoRecurseAttrsTopDown(Function &F)
static void addLocAccess(MemoryEffects &ME, const MemoryLocation &Loc, ModRefInfo MR, AAResults &AAR)
static void inferConvergent(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Attempt to remove convergent function attribute when possible.
static cl::opt< bool > DisableThinLTOPropagation("disable-thinlto-funcattrs", cl::init(true), cl::Hidden, cl::desc("Don't propagate function-attrs in thinLTO"))
static SCCNodesResult createSCCNodeSet(ArrayRef< Function * > Functions)
static bool InstrBreaksNonConvergent(Instruction &I, const SCCNodeSet &SCCNodes)
Helper for non-Convergent inference predicate InstrBreaksAttribute.
static void addArgumentAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed, bool SkipInitializes)
Deduce nocapture attributes for the SCC.
static void addNoRecurseAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
static bool functionWillReturn(const Function &F)
static void addNoUndefAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce noundef attributes for the SCC.
static void addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes, SmallPtrSet< Function *, 8 > &Changed)
Deduce returned attributes for the SCC.
Provides passes for computing function attributes based on interprocedural analyses.
Hexagon Common GEP
#define _
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
Implements a lazy call graph analysis and related passes for the new pass manager.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
uint64_t High
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
Remove Loads Into Fake Uses
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
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
Value * RHS
Value * LHS
A manager for alias analyses.
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
Class for arbitrary precision integers.
Definition APInt.h:78
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM_ABI ArrayRef< ConstantRange > getValueAsConstantRangeList() const
Return the attribute's value as a ConstantRange array.
static LLVM_ABI Attribute getWithNoFPClass(LLVMContext &Context, FPClassTest Mask)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ None
No attributes have been set.
Definition Attributes.h:126
static LLVM_ABI Attribute getWithCaptureInfo(LLVMContext &Context, CaptureInfo CI)
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI FPClassTest getParamNoFPClass(unsigned i) const
Extract a test mask for disallowed floating-point value classes for the parameter.
LLVM_ABI FPClassTest getRetNoFPClass() const
Extract a test mask for disallowed floating-point value classes for the return value.
LLVM_ABI MemoryEffects getMemoryEffects() const
bool doesNotCapture(unsigned OpNo) const
Determine whether this data operand is not captured.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getDataOperandNo(Value::const_user_iterator UI) const
Given a value use iterator, return the data operand corresponding to it.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const
Return true if the data operand at index i has the attribute A.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
bool onlyWritesMemory(unsigned OpNo) const
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
LLVM_ABI CaptureInfo getCaptureInfo(unsigned OpNo) const
Return which pointer components this operand may capture.
bool onlyReadsMemory(unsigned OpNo) const
Value * getArgOperand(unsigned i) const
bool isConvergent() const
Determine if the invoke is convergent.
unsigned getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it.
unsigned arg_size() const
bool isArgOperand(const Use *U) const
bool hasOperandBundles() const
Return true if this User has any operand bundles.
A node in the call graph for a module.
Definition CallGraph.h:162
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
Represents which components of the pointer may be captured in which location.
Definition ModRef.h:414
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static CaptureInfo retOnly(CaptureComponents RetComponents=CaptureComponents::All)
Create CaptureInfo that may only capture via the return value.
Definition ModRef.h:434
static CaptureInfo all()
Create CaptureInfo that may capture all components of the pointer.
Definition ModRef.h:430
This class represents a list of constant ranges.
LLVM_ABI void subtract(const ConstantRange &SubRange)
LLVM_ABI void insert(const ConstantRange &NewRange)
Insert a new range to Ranges and keep the list ordered.
bool empty() const
Return true if this list contains no members.
ArrayRef< ConstantRange > rangesRef() const
LLVM_ABI ConstantRangeList intersectWith(const ConstantRangeList &CRL) const
Return the range list that results from the intersection of this ConstantRangeList with another Const...
LLVM_ABI ConstantRangeList unionWith(const ConstantRangeList &CRL) const
Return the range list that results from the union of this ConstantRangeList with another ConstantRang...
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:254
iterator end()
Definition DenseMap.h:85
A proxy from a FunctionAnalysisManager to an SCC.
Function summary information to aid decisions and implementation of importing.
ArrayRef< EdgeTy > calls() const
Return the list of <CalleeValueInfo, CalleeInfo> pairs.
FFlags fflags() const
Get function summary flags.
Function and variable summary information to aid decisions and implementation of importing.
static bool isWeakAnyLinkage(LinkageTypes Linkage)
static bool isLinkOnceAnyLinkage(LinkageTypes Linkage)
static bool isLocalLinkage(LinkageTypes Linkage)
static bool isWeakODRLinkage(LinkageTypes Linkage)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
static bool isExternalLinkage(LinkageTypes Linkage)
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An analysis pass which computes the call graph for a module.
A node in the call graph.
A RefSCC of the call graph.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
LLVM_ABI void buildRefSCCs()
iterator_range< postorder_ref_scc_iterator > postorder_ref_sccs()
MemoryEffectsBase getWithoutLoc(Location Loc) const
Get new MemoryEffectsBase with NoModRef on the given Loc.
Definition ModRef.h:231
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
Definition ModRef.h:219
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Representation for a specific memory location.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
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
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
op_range incoming_values()
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Return a value (possibly void), from a function.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:176
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:972
iterator_range< use_iterator > uses()
Definition Value.h:380
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Definition SCCIterator.h:49
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
bool match(Val *V, const Pattern &P)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:558
@ Length
Definition DWP.cpp:558
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
LLVM_ABI MemoryEffects computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool thinLTOPropagateFunctionAttrs(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Propagate function attributes for function summaries along the index's callgraph during thinlink.
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1790
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
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 bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2191
@ Continue
Definition DWP.h:26
LLVM_ABI bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
Definition Local.cpp:4039
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool capturesAll(CaptureComponents CC)
Definition ModRef.h:404
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
LLVM_ABI void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock * > > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them.
Definition CFG.cpp:36
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool capturesAnyProvenance(CaptureComponents CC)
Definition ModRef.h:400
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI bool canReturn(const Function &F)
Return true if there is at least a path through which F can return, false if there is no such path.
Definition CFG.cpp:405
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
This callback is used in conjunction with PointerMayBeCaptured.
Flags specific to function summaries.
SmallVectorImpl< ArgumentGraphNode * >::iterator ChildIteratorType
static ChildIteratorType child_begin(NodeRef N)
static ChildIteratorType child_end(NodeRef N)
static ChildIteratorType nodes_end(ArgumentGraph *AG)
static NodeRef getEntryNode(ArgumentGraph *AG)
static ChildIteratorType nodes_begin(ArgumentGraph *AG)
typename ArgumentGraph *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:95
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:89
LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
CaptureComponents UseCC
Components captured by this use.
Struct that holds a reference to a particular GUID in a global value summary.