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