blob: 6e036664377dece68c507e5b967fb60a17ed7519 [file] [log] [blame]
Meador Inge6b6a1612013-03-21 00:55:59 +00001//===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
Duncan Sands44c8cd92008-12-31 16:14:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chandler Carruth1926b702016-01-08 10:55:52 +00009///
10/// \file
11/// This file implements interprocedural passes which walk the
12/// call-graph deducing and/or propagating function attributes.
13///
Duncan Sands44c8cd92008-12-31 16:14:43 +000014//===----------------------------------------------------------------------===//
15
Chandler Carruth9c4ed172016-02-18 11:03:11 +000016#include "llvm/Transforms/IPO/FunctionAttrs.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000017#include "llvm/Transforms/IPO.h"
Nick Lewycky4c378a42011-12-28 23:24:21 +000018#include "llvm/ADT/SCCIterator.h"
Benjamin Kramer15591272012-10-31 13:45:49 +000019#include "llvm/ADT/SetVector.h"
Duncan Sandsb193a372009-01-02 11:54:37 +000020#include "llvm/ADT/SmallSet.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000021#include "llvm/ADT/Statistic.h"
James Molloy0ecdbe72015-11-19 08:49:57 +000022#include "llvm/ADT/StringSwitch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/AssumptionCache.h"
25#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000027#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000029#include "llvm/Analysis/TargetLibraryInfo.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000030#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000032#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000035#include "llvm/Support/Debug.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000037#include "llvm/Analysis/TargetLibraryInfo.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000038using namespace llvm;
39
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "functionattrs"
41
Duncan Sands44c8cd92008-12-31 16:14:43 +000042STATISTIC(NumReadNone, "Number of functions marked readnone");
43STATISTIC(NumReadOnly, "Number of functions marked readonly");
44STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
David Majnemer5246e0b2016-07-19 18:50:26 +000045STATISTIC(NumReturned, "Number of arguments marked returned");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000046STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
47STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000048STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000049STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000050STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Duncan Sands44c8cd92008-12-31 16:14:43 +000051
52namespace {
Chandler Carruthc518ebd2015-10-29 18:29:15 +000053typedef SmallSetVector<Function *, 8> SCCNodeSet;
54}
55
56namespace {
Chandler Carruth7542d372015-09-21 17:39:41 +000057/// The three kinds of memory access relevant to 'readonly' and
58/// 'readnone' attributes.
59enum MemoryAccessKind {
60 MAK_ReadNone = 0,
61 MAK_ReadOnly = 1,
62 MAK_MayWrite = 2
63};
64}
65
Chandler Carruthc518ebd2015-10-29 18:29:15 +000066static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
67 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +000068 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
69 if (MRB == FMRB_DoesNotAccessMemory)
70 // Already perfect!
71 return MAK_ReadNone;
72
Sanjoy Das5ce32722016-04-08 00:48:30 +000073 // Non-exact function definitions may not be selected at link time, and an
74 // alternative version that writes to memory may be selected. See the comment
75 // on GlobalValue::isDefinitionExact for more details.
76 if (!F.hasExactDefinition()) {
Chandler Carruth7542d372015-09-21 17:39:41 +000077 if (AliasAnalysis::onlyReadsMemory(MRB))
78 return MAK_ReadOnly;
79
80 // Conservatively assume it writes to memory.
81 return MAK_MayWrite;
82 }
83
84 // Scan the function body for instructions that may read or write memory.
85 bool ReadsMemory = false;
86 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
87 Instruction *I = &*II;
88
89 // Some instructions can be ignored even if they read or write memory.
90 // Detect these now, skipping to the next instruction if one is found.
91 CallSite CS(cast<Value>(I));
92 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +000093 // Ignore calls to functions in the same SCC, as long as the call sites
94 // don't have operand bundles. Calls with operand bundles are allowed to
95 // have memory effects not described by the memory effects of the call
96 // target.
97 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
98 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +000099 continue;
100 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Chandler Carruth7542d372015-09-21 17:39:41 +0000101
Chandler Carruth69798fb2015-10-27 01:41:43 +0000102 // If the call doesn't access memory, we're done.
103 if (!(MRB & MRI_ModRef))
104 continue;
105
106 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
107 // The call could access any memory. If that includes writes, give up.
108 if (MRB & MRI_Mod)
109 return MAK_MayWrite;
110 // If it reads, note it.
111 if (MRB & MRI_Ref)
112 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000113 continue;
114 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000115
116 // Check whether all pointer arguments point to local memory, and
117 // ignore calls that only access local memory.
118 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
119 CI != CE; ++CI) {
120 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000121 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000122 continue;
123
124 AAMDNodes AAInfo;
125 I->getAAMetadata(AAInfo);
126 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
127
128 // Skip accesses to local or constant memory as they don't impact the
129 // externally visible mod/ref behavior.
130 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
131 continue;
132
133 if (MRB & MRI_Mod)
134 // Writes non-local memory. Give up.
135 return MAK_MayWrite;
136 if (MRB & MRI_Ref)
137 // Ok, it reads non-local memory.
138 ReadsMemory = true;
139 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000140 continue;
141 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
142 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
143 if (!LI->isVolatile()) {
144 MemoryLocation Loc = MemoryLocation::get(LI);
145 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
146 continue;
147 }
148 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
149 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
150 if (!SI->isVolatile()) {
151 MemoryLocation Loc = MemoryLocation::get(SI);
152 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
153 continue;
154 }
155 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
156 // Ignore vaargs on local memory.
157 MemoryLocation Loc = MemoryLocation::get(VI);
158 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
159 continue;
160 }
161
162 // Any remaining instructions need to be taken seriously! Check if they
163 // read or write memory.
164 if (I->mayWriteToMemory())
165 // Writes memory. Just give up.
166 return MAK_MayWrite;
167
168 // If this instruction may read memory, remember that.
169 ReadsMemory |= I->mayReadFromMemory();
170 }
171
172 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
173}
174
Chandler Carrutha632fb92015-09-13 06:57:25 +0000175/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000176template <typename AARGetterT>
177static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000178 // Check if any of the functions in the SCC read or write memory. If they
179 // write memory then they can't be marked readnone or readonly.
180 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000181 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000182 // Call the callable parameter to look up AA results for this function.
183 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000184
Chandler Carruth7542d372015-09-21 17:39:41 +0000185 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
186 case MAK_MayWrite:
187 return false;
188 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000189 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000190 break;
191 case MAK_ReadNone:
192 // Nothing to do!
193 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000194 }
195 }
196
197 // Success! Functions in this SCC do not access memory, or only read memory.
198 // Give them the appropriate attribute.
199 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000200 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000201 if (F->doesNotAccessMemory())
202 // Already perfect!
203 continue;
204
205 if (F->onlyReadsMemory() && ReadsMemory)
206 // No change.
207 continue;
208
209 MadeChange = true;
210
211 // Clear out any existing attributes.
Bill Wendling50d27842012-10-15 20:35:56 +0000212 AttrBuilder B;
Chandler Carruth63559d72015-09-13 06:47:20 +0000213 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
214 F->removeAttributes(
215 AttributeSet::FunctionIndex,
216 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
Duncan Sands44c8cd92008-12-31 16:14:43 +0000217
218 // Add in the new attribute.
Bill Wendlinge94d8432012-12-07 23:16:57 +0000219 F->addAttribute(AttributeSet::FunctionIndex,
Bill Wendlingc0e2a1f2013-01-23 00:20:53 +0000220 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000221
222 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000223 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000224 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000225 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000226 }
227
228 return MadeChange;
229}
230
Nick Lewycky4c378a42011-12-28 23:24:21 +0000231namespace {
Chandler Carrutha632fb92015-09-13 06:57:25 +0000232/// For a given pointer Argument, this retains a list of Arguments of functions
233/// in the same SCC that the pointer data flows into. We use this to build an
234/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000235struct ArgumentGraphNode {
236 Argument *Definition;
237 SmallVector<ArgumentGraphNode *, 4> Uses;
238};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000239
Chandler Carruth63559d72015-09-13 06:47:20 +0000240class ArgumentGraph {
241 // We store pointers to ArgumentGraphNode objects, so it's important that
242 // that they not move around upon insert.
243 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000244
Chandler Carruth63559d72015-09-13 06:47:20 +0000245 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000246
Chandler Carruth63559d72015-09-13 06:47:20 +0000247 // There is no root node for the argument graph, in fact:
248 // void f(int *x, int *y) { if (...) f(x, y); }
249 // is an example where the graph is disconnected. The SCCIterator requires a
250 // single entry point, so we maintain a fake ("synthetic") root node that
251 // uses every node. Because the graph is directed and nothing points into
252 // the root, it will not participate in any SCCs (except for its own).
253 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000254
Chandler Carruth63559d72015-09-13 06:47:20 +0000255public:
256 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000257
Chandler Carruth63559d72015-09-13 06:47:20 +0000258 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000259
Chandler Carruth63559d72015-09-13 06:47:20 +0000260 iterator begin() { return SyntheticRoot.Uses.begin(); }
261 iterator end() { return SyntheticRoot.Uses.end(); }
262 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000263
Chandler Carruth63559d72015-09-13 06:47:20 +0000264 ArgumentGraphNode *operator[](Argument *A) {
265 ArgumentGraphNode &Node = ArgumentMap[A];
266 Node.Definition = A;
267 SyntheticRoot.Uses.push_back(&Node);
268 return &Node;
269 }
270};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000271
Chandler Carrutha632fb92015-09-13 06:57:25 +0000272/// This tracker checks whether callees are in the SCC, and if so it does not
273/// consider that a capture, instead adding it to the "Uses" list and
274/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000275struct ArgumentUsesTracker : public CaptureTracker {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000276 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
Nick Lewycky4c378a42011-12-28 23:24:21 +0000277 : Captured(false), SCCNodes(SCCNodes) {}
278
Chandler Carruth63559d72015-09-13 06:47:20 +0000279 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000280
Chandler Carruth63559d72015-09-13 06:47:20 +0000281 bool captured(const Use *U) override {
282 CallSite CS(U->getUser());
283 if (!CS.getInstruction()) {
284 Captured = true;
285 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000286 }
287
Chandler Carruth63559d72015-09-13 06:47:20 +0000288 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000289 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000290 Captured = true;
291 return true;
292 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000293
Sanjoy Das98bfe262015-11-05 03:04:40 +0000294 // Note: the callee and the two successor blocks *follow* the argument
295 // operands. This means there is no need to adjust UseIndex to account for
296 // these.
297
298 unsigned UseIndex =
299 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
300
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000301 assert(UseIndex < CS.data_operands_size() &&
302 "Indirect function calls should have been filtered above!");
303
304 if (UseIndex >= CS.getNumArgOperands()) {
305 // Data operand, but not a argument operand -- must be a bundle operand
306 assert(CS.hasOperandBundles() && "Must be!");
307
308 // CaptureTracking told us that we're being captured by an operand bundle
309 // use. In this case it does not matter if the callee is within our SCC
310 // or not -- we've been captured in some unknown way, and we have to be
311 // conservative.
312 Captured = true;
313 return true;
314 }
315
Sanjoy Das98bfe262015-11-05 03:04:40 +0000316 if (UseIndex >= F->arg_size()) {
317 assert(F->isVarArg() && "More params than args in non-varargs call");
318 Captured = true;
319 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000320 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000321
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000322 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000323 return false;
324 }
325
326 bool Captured; // True only if certainly captured (used outside our SCC).
327 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
328
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000329 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000330};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000331}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000332
333namespace llvm {
Chandler Carruth63559d72015-09-13 06:47:20 +0000334template <> struct GraphTraits<ArgumentGraphNode *> {
Tim Shenb44909e2016-08-01 22:32:20 +0000335 typedef ArgumentGraphNode *NodeRef;
Chandler Carruth63559d72015-09-13 06:47:20 +0000336 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000337
Tim Shenf2187ed2016-08-22 21:09:30 +0000338 static inline NodeRef getEntryNode(NodeRef A) { return A; }
339 static inline ChildIteratorType child_begin(NodeRef N) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000340 return N->Uses.begin();
341 }
Tim Shenf2187ed2016-08-22 21:09:30 +0000342 static inline ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000343};
344template <>
345struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000346 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000347 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
348 return AG->begin();
349 }
350 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
351};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000352}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000353
Chandler Carrutha632fb92015-09-13 06:57:25 +0000354/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000355static Attribute::AttrKind
356determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000357 const SmallPtrSet<Argument *, 8> &SCCNodes) {
358
359 SmallVector<Use *, 32> Worklist;
360 SmallSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000361
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000362 // inalloca arguments are always clobbered by the call.
363 if (A->hasInAllocaAttr())
364 return Attribute::None;
365
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000366 bool IsRead = false;
367 // We don't need to track IsWritten. If A is written to, return immediately.
368
Chandler Carruthcdf47882014-03-09 03:16:01 +0000369 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000370 Visited.insert(&U);
371 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000372 }
373
374 while (!Worklist.empty()) {
375 Use *U = Worklist.pop_back_val();
376 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000377
378 switch (I->getOpcode()) {
379 case Instruction::BitCast:
380 case Instruction::GetElementPtr:
381 case Instruction::PHI:
382 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000383 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000384 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000385 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000386 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000387 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000388 break;
389
390 case Instruction::Call:
391 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000392 bool Captures = true;
393
394 if (I->getType()->isVoidTy())
395 Captures = false;
396
397 auto AddUsersToWorklistIfCapturing = [&] {
398 if (Captures)
399 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000400 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000401 Worklist.push_back(&UU);
402 };
403
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000404 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000405 if (CS.doesNotAccessMemory()) {
406 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000407 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000408 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000409
410 Function *F = CS.getCalledFunction();
411 if (!F) {
412 if (CS.onlyReadsMemory()) {
413 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000414 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000415 continue;
416 }
417 return Attribute::None;
418 }
419
Sanjoy Das436e2392015-11-07 01:55:53 +0000420 // Note: the callee and the two successor blocks *follow* the argument
421 // operands. This means there is no need to adjust UseIndex to account
422 // for these.
423
424 unsigned UseIndex = std::distance(CS.arg_begin(), U);
425
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000426 // U cannot be the callee operand use: since we're exploring the
427 // transitive uses of an Argument, having such a use be a callee would
428 // imply the CallSite is an indirect call or invoke; and we'd take the
429 // early exit above.
430 assert(UseIndex < CS.data_operands_size() &&
431 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000432
433 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
434
435 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000436 assert(F->isVarArg() && "More params than args in non-varargs call");
437 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000438 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000439
Tilmann Scheller925b1932015-11-20 19:17:10 +0000440 Captures &= !CS.doesNotCapture(UseIndex);
441
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000442 // Since the optimizer (by design) cannot see the data flow corresponding
443 // to a operand bundle use, these cannot participate in the optimistic SCC
444 // analysis. Instead, we model the operand bundle uses as arguments in
445 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000446 if (IsOperandBundleUse ||
447 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000448
449 // The accessors used on CallSite here do the right thing for calls and
450 // invokes with operand bundles.
451
Sanjoy Das436e2392015-11-07 01:55:53 +0000452 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
453 return Attribute::None;
454 if (!CS.doesNotAccessMemory(UseIndex))
455 IsRead = true;
456 }
457
Nick Lewycky59633cb2014-05-30 02:31:27 +0000458 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000459 break;
460 }
461
462 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000463 // A volatile load has side effects beyond what readonly can be relied
464 // upon.
465 if (cast<LoadInst>(I)->isVolatile())
466 return Attribute::None;
467
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000468 IsRead = true;
469 break;
470
471 case Instruction::ICmp:
472 case Instruction::Ret:
473 break;
474
475 default:
476 return Attribute::None;
477 }
478 }
479
480 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
481}
482
David Majnemer5246e0b2016-07-19 18:50:26 +0000483/// Deduce returned attributes for the SCC.
484static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
485 bool Changed = false;
486
487 AttrBuilder B;
488 B.addAttribute(Attribute::Returned);
489
490 // Check each function in turn, determining if an argument is always returned.
491 for (Function *F : SCCNodes) {
492 // We can infer and propagate function attributes only when we know that the
493 // definition we'll get at link time is *exactly* the definition we see now.
494 // For more details, see GlobalValue::mayBeDerefined.
495 if (!F->hasExactDefinition())
496 continue;
497
498 if (F->getReturnType()->isVoidTy())
499 continue;
500
501 auto FindRetArg = [&]() -> Value * {
502 Value *RetArg = nullptr;
503 for (BasicBlock &BB : *F)
504 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
505 // Note that stripPointerCasts should look through functions with
506 // returned arguments.
507 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
508 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
509 return nullptr;
510
511 if (!RetArg)
512 RetArg = RetVal;
513 else if (RetArg != RetVal)
514 return nullptr;
515 }
516
517 return RetArg;
518 };
519
520 if (Value *RetArg = FindRetArg()) {
521 auto *A = cast<Argument>(RetArg);
522 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
523 ++NumReturned;
524 Changed = true;
525 }
526 }
527
528 return Changed;
529}
530
Chandler Carrutha632fb92015-09-13 06:57:25 +0000531/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000532static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000533 bool Changed = false;
534
Nick Lewycky4c378a42011-12-28 23:24:21 +0000535 ArgumentGraph AG;
536
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000537 AttrBuilder B;
538 B.addAttribute(Attribute::NoCapture);
539
Duncan Sands44c8cd92008-12-31 16:14:43 +0000540 // Check each function in turn, determining which pointer arguments are not
541 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000542 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000543 // We can infer and propagate function attributes only when we know that the
544 // definition we'll get at link time is *exactly* the definition we see now.
545 // For more details, see GlobalValue::mayBeDerefined.
546 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000547 continue;
548
Nick Lewycky4c378a42011-12-28 23:24:21 +0000549 // Functions that are readonly (or readnone) and nounwind and don't return
550 // a value can't capture arguments. Don't analyze them.
551 if (F->onlyReadsMemory() && F->doesNotThrow() &&
552 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000553 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
554 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000555 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
556 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
557 ++NumNoCapture;
558 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000559 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000560 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000561 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000562 }
563
Chandler Carruth63559d72015-09-13 06:47:20 +0000564 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
565 ++A) {
566 if (!A->getType()->isPointerTy())
567 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000568 bool HasNonLocalUses = false;
569 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000570 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000571 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000572 if (!Tracker.Captured) {
573 if (Tracker.Uses.empty()) {
574 // If it's trivially not captured, mark it nocapture now.
Chandler Carruth63559d72015-09-13 06:47:20 +0000575 A->addAttr(
576 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000577 ++NumNoCapture;
578 Changed = true;
579 } else {
580 // If it's not trivially captured and not trivially not captured,
581 // then it must be calling into another function in our SCC. Save
582 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000583 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000584 for (Argument *Use : Tracker.Uses) {
585 Node->Uses.push_back(AG[Use]);
586 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000587 HasNonLocalUses = true;
588 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000589 }
590 }
591 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
592 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000593 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
594 // Can we determine that it's readonly/readnone without doing an SCC?
595 // Note that we don't allow any calls at all here, or else our result
596 // will be dependent on the iteration order through the functions in the
597 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000598 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000599 Self.insert(&*A);
600 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000601 if (R != Attribute::None) {
602 AttrBuilder B;
603 B.addAttribute(R);
604 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
605 Changed = true;
606 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
607 }
608 }
609 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000610 }
611
612 // The graph we've collected is partial because we stopped scanning for
613 // argument uses once we solved the argument trivially. These partial nodes
614 // show up as ArgumentGraphNode objects with an empty Uses list, and for
615 // these nodes the final decision about whether they capture has already been
616 // made. If the definition doesn't have a 'nocapture' attribute by now, it
617 // captures.
618
Chandler Carruth63559d72015-09-13 06:47:20 +0000619 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000620 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000621 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000622 if (!ArgumentSCC[0]->Definition)
623 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000624
625 // eg. "void f(int* x) { if (...) f(x); }"
626 if (ArgumentSCC[0]->Uses.size() == 1 &&
627 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000628 Argument *A = ArgumentSCC[0]->Definition;
629 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky7e820552009-01-02 03:46:56 +0000630 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000631 Changed = true;
632 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000633 continue;
634 }
635
636 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000637 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
638 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000639 ArgumentGraphNode *Node = *I;
640 if (Node->Uses.empty()) {
641 if (!Node->Definition->hasNoCaptureAttr())
642 SCCCaptured = true;
643 }
644 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000645 if (SCCCaptured)
646 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000647
Chandler Carruth63559d72015-09-13 06:47:20 +0000648 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000649 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
650 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000651 for (ArgumentGraphNode *I : ArgumentSCC) {
652 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000653 }
654
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000655 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
656 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000657 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000658 for (ArgumentGraphNode *Use : N->Uses) {
659 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000660 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
661 continue;
662 SCCCaptured = true;
663 break;
664 }
665 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000666 if (SCCCaptured)
667 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000668
Nick Lewyckyf740db32012-01-05 22:21:45 +0000669 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000670 Argument *A = ArgumentSCC[i]->Definition;
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000671 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky4c378a42011-12-28 23:24:21 +0000672 ++NumNoCapture;
673 Changed = true;
674 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000675
676 // We also want to compute readonly/readnone. With a small number of false
677 // negatives, we can assume that any pointer which is captured isn't going
678 // to be provably readonly or readnone, since by definition we can't
679 // analyze all uses of a captured pointer.
680 //
681 // The false negatives happen when the pointer is captured by a function
682 // that promises readonly/readnone behaviour on the pointer, then the
683 // pointer's lifetime ends before anything that writes to arbitrary memory.
684 // Also, a readonly/readnone pointer may be returned, but returning a
685 // pointer is capturing it.
686
687 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
688 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
689 Argument *A = ArgumentSCC[i]->Definition;
690 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
691 if (K == Attribute::ReadNone)
692 continue;
693 if (K == Attribute::ReadOnly) {
694 ReadAttr = Attribute::ReadOnly;
695 continue;
696 }
697 ReadAttr = K;
698 break;
699 }
700
701 if (ReadAttr != Attribute::None) {
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000702 AttrBuilder B, R;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000703 B.addAttribute(ReadAttr);
Chandler Carruth63559d72015-09-13 06:47:20 +0000704 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000705 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
706 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000707 // Clear out existing readonly/readnone attributes
708 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000709 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
710 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
711 Changed = true;
712 }
713 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000714 }
715
716 return Changed;
717}
718
Chandler Carrutha632fb92015-09-13 06:57:25 +0000719/// Tests whether a function is "malloc-like".
720///
721/// A function is "malloc-like" if it returns either null or a pointer that
722/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000723static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000724 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000725 for (BasicBlock &BB : *F)
726 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000727 FlowsToReturn.insert(Ret->getReturnValue());
728
729 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000730 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000731
732 if (Constant *C = dyn_cast<Constant>(RetVal)) {
733 if (!C->isNullValue() && !isa<UndefValue>(C))
734 return false;
735
736 continue;
737 }
738
739 if (isa<Argument>(RetVal))
740 return false;
741
742 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
743 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000744 // Extend the analysis by looking upwards.
745 case Instruction::BitCast:
746 case Instruction::GetElementPtr:
747 case Instruction::AddrSpaceCast:
748 FlowsToReturn.insert(RVI->getOperand(0));
749 continue;
750 case Instruction::Select: {
751 SelectInst *SI = cast<SelectInst>(RVI);
752 FlowsToReturn.insert(SI->getTrueValue());
753 FlowsToReturn.insert(SI->getFalseValue());
754 continue;
755 }
756 case Instruction::PHI: {
757 PHINode *PN = cast<PHINode>(RVI);
758 for (Value *IncValue : PN->incoming_values())
759 FlowsToReturn.insert(IncValue);
760 continue;
761 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000762
Chandler Carruth63559d72015-09-13 06:47:20 +0000763 // Check whether the pointer came from an allocation.
764 case Instruction::Alloca:
765 break;
766 case Instruction::Call:
767 case Instruction::Invoke: {
768 CallSite CS(RVI);
769 if (CS.paramHasAttr(0, Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000770 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000771 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
772 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000773 LLVM_FALLTHROUGH;
774 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000775 default:
776 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000777 }
778
Dan Gohman94e61762009-11-19 21:57:48 +0000779 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000780 return false;
781 }
782
783 return true;
784}
785
Chandler Carrutha632fb92015-09-13 06:57:25 +0000786/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000787static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000788 // Check each function in turn, determining which functions return noalias
789 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000790 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000791 // Already noalias.
792 if (F->doesNotAlias(0))
793 continue;
794
Sanjoy Das5ce32722016-04-08 00:48:30 +0000795 // We can infer and propagate function attributes only when we know that the
796 // definition we'll get at link time is *exactly* the definition we see now.
797 // For more details, see GlobalValue::mayBeDerefined.
798 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000799 return false;
800
Chandler Carruth63559d72015-09-13 06:47:20 +0000801 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000802 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000803 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000804 continue;
805
Chandler Carruth3824f852015-09-13 08:23:27 +0000806 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000807 return false;
808 }
809
810 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000811 for (Function *F : SCCNodes) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000812 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000813 continue;
814
815 F->setDoesNotAlias(0);
816 ++NumNoAlias;
817 MadeChange = true;
818 }
819
820 return MadeChange;
821}
822
Chandler Carrutha632fb92015-09-13 06:57:25 +0000823/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000824///
825/// Requires that the function returns a pointer.
826///
827/// Returns true if it believes the function will not return a null, and sets
828/// \p Speculative based on whether the returned conclusion is a speculative
829/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000830static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000831 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000832 assert(F->getReturnType()->isPointerTy() &&
833 "nonnull only meaningful on pointer types");
834 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000835
Philip Reamesa88caea2015-08-31 19:44:38 +0000836 SmallSetVector<Value *, 8> FlowsToReturn;
837 for (BasicBlock &BB : *F)
838 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
839 FlowsToReturn.insert(Ret->getReturnValue());
840
841 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
842 Value *RetVal = FlowsToReturn[i];
843
844 // If this value is locally known to be non-null, we're good
Sean Silva45835e72016-07-02 23:47:27 +0000845 if (isKnownNonNull(RetVal))
Philip Reamesa88caea2015-08-31 19:44:38 +0000846 continue;
847
848 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000849 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000850 Instruction *RVI = dyn_cast<Instruction>(RetVal);
851 if (!RVI)
852 return false;
853 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000854 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000855 case Instruction::BitCast:
856 case Instruction::GetElementPtr:
857 case Instruction::AddrSpaceCast:
858 FlowsToReturn.insert(RVI->getOperand(0));
859 continue;
860 case Instruction::Select: {
861 SelectInst *SI = cast<SelectInst>(RVI);
862 FlowsToReturn.insert(SI->getTrueValue());
863 FlowsToReturn.insert(SI->getFalseValue());
864 continue;
865 }
866 case Instruction::PHI: {
867 PHINode *PN = cast<PHINode>(RVI);
868 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
869 FlowsToReturn.insert(PN->getIncomingValue(i));
870 continue;
871 }
872 case Instruction::Call:
873 case Instruction::Invoke: {
874 CallSite CS(RVI);
875 Function *Callee = CS.getCalledFunction();
876 // A call to a node within the SCC is assumed to return null until
877 // proven otherwise
878 if (Callee && SCCNodes.count(Callee)) {
879 Speculative = true;
880 continue;
881 }
882 return false;
883 }
884 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000885 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000886 };
887 llvm_unreachable("should have either continued or returned");
888 }
889
890 return true;
891}
892
Chandler Carrutha632fb92015-09-13 06:57:25 +0000893/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +0000894static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000895 // Speculative that all functions in the SCC return only nonnull
896 // pointers. We may refute this as we analyze functions.
897 bool SCCReturnsNonNull = true;
898
899 bool MadeChange = false;
900
901 // Check each function in turn, determining which functions return nonnull
902 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000903 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000904 // Already nonnull.
905 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
906 Attribute::NonNull))
907 continue;
908
Sanjoy Das5ce32722016-04-08 00:48:30 +0000909 // We can infer and propagate function attributes only when we know that the
910 // definition we'll get at link time is *exactly* the definition we see now.
911 // For more details, see GlobalValue::mayBeDerefined.
912 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +0000913 return false;
914
Chandler Carruth63559d72015-09-13 06:47:20 +0000915 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +0000916 // pointer types.
917 if (!F->getReturnType()->isPointerTy())
918 continue;
919
920 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +0000921 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000922 if (!Speculative) {
923 // Mark the function eagerly since we may discover a function
924 // which prevents us from speculating about the entire SCC
925 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
926 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
927 ++NumNonNullReturn;
928 MadeChange = true;
929 }
930 continue;
931 }
932 // At least one function returns something which could be null, can't
933 // speculate any more.
934 SCCReturnsNonNull = false;
935 }
936
937 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000938 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000939 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
940 Attribute::NonNull) ||
941 !F->getReturnType()->isPointerTy())
942 continue;
943
944 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
945 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
946 ++NumNonNullReturn;
947 MadeChange = true;
948 }
949 }
950
951 return MadeChange;
952}
953
Justin Lebar9d943972016-03-14 20:18:54 +0000954/// Remove the convergent attribute from all functions in the SCC if every
955/// callsite within the SCC is not convergent (except for calls to functions
956/// within the SCC). Returns true if changes were made.
Chandler Carruth3937bc72016-02-12 09:47:49 +0000957static bool removeConvergentAttrs(const SCCNodeSet &SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +0000958 // For every function in SCC, ensure that either
959 // * it is not convergent, or
960 // * we can remove its convergent attribute.
961 bool HasConvergentFn = false;
Chandler Carruth3937bc72016-02-12 09:47:49 +0000962 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +0000963 if (!F->isConvergent()) continue;
964 HasConvergentFn = true;
965
966 // Can't remove convergent from function declarations.
967 if (F->isDeclaration()) return false;
968
969 // Can't remove convergent if any of our functions has a convergent call to a
970 // function not in the SCC.
971 for (Instruction &I : instructions(*F)) {
972 CallSite CS(&I);
973 // Bail if CS is a convergent call to a function not in the SCC.
974 if (CS && CS.isConvergent() &&
975 SCCNodes.count(CS.getCalledFunction()) == 0)
976 return false;
977 }
978 }
979
980 // If the SCC doesn't have any convergent functions, we have nothing to do.
981 if (!HasConvergentFn) return false;
982
983 // If we got here, all of the calls the SCC makes to functions not in the SCC
984 // are non-convergent. Therefore all of the SCC's functions can also be made
985 // non-convergent. We'll remove the attr from the callsites in
986 // InstCombineCalls.
987 for (Function *F : SCCNodes) {
988 if (!F->isConvergent()) continue;
989
990 DEBUG(dbgs() << "Removing convergent attr from fn " << F->getName()
991 << "\n");
Chandler Carruth3937bc72016-02-12 09:47:49 +0000992 F->setNotConvergent();
993 }
Justin Lebar260854b2016-02-09 23:03:22 +0000994 return true;
995}
996
James Molloy7e9bdd52015-11-12 10:55:20 +0000997static bool setDoesNotRecurse(Function &F) {
998 if (F.doesNotRecurse())
999 return false;
1000 F.setDoesNotRecurse();
1001 ++NumNoRecurse;
1002 return true;
1003}
1004
Chandler Carruth632d2082016-02-13 08:47:51 +00001005static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001006 // Try and identify functions that do not recurse.
1007
1008 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001009 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001010 return false;
1011
Chandler Carruth632d2082016-02-13 08:47:51 +00001012 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001013 if (!F || F->isDeclaration() || F->doesNotRecurse())
1014 return false;
1015
1016 // If all of the calls in F are identifiable and are to norecurse functions, F
1017 // is norecurse. This check also detects self-recursion as F is not currently
1018 // marked norecurse, so any called from F to F will not be marked norecurse.
Chandler Carruth632d2082016-02-13 08:47:51 +00001019 for (Instruction &I : instructions(*F))
1020 if (auto CS = CallSite(&I)) {
1021 Function *Callee = CS.getCalledFunction();
1022 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1023 // Function calls a potentially recursive function.
1024 return false;
1025 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001026
Chandler Carruth632d2082016-02-13 08:47:51 +00001027 // Every call was to a non-recursive function other than this function, and
1028 // we have no indirect recursion as the SCC size is one. This function cannot
1029 // recurse.
1030 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001031}
1032
Chandler Carruthb47f8012016-03-11 11:05:24 +00001033PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
1034 CGSCCAnalysisManager &AM) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001035 FunctionAnalysisManager &FAM =
Chandler Carruthb47f8012016-03-11 11:05:24 +00001036 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001037
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001038 // We pass a lambda into functions to wire them up to the analysis manager
1039 // for getting function analyses.
1040 auto AARGetter = [&](Function &F) -> AAResults & {
1041 return FAM.getResult<AAManager>(F);
1042 };
1043
1044 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1045 // any external or opt-none nodes that will prevent us from optimizing any
1046 // part of the SCC.
1047 SCCNodeSet SCCNodes;
1048 bool HasUnknownCall = false;
1049 for (LazyCallGraph::Node &N : C) {
1050 Function &F = N.getFunction();
1051 if (F.hasFnAttribute(Attribute::OptimizeNone)) {
1052 // Treat any function we're trying not to optimize as if it were an
1053 // indirect call and omit it from the node set used below.
1054 HasUnknownCall = true;
1055 continue;
1056 }
1057 // Track whether any functions in this SCC have an unknown call edge.
1058 // Note: if this is ever a performance hit, we can common it with
1059 // subsequent routines which also do scans over the instructions of the
1060 // function.
1061 if (!HasUnknownCall)
1062 for (Instruction &I : instructions(F))
1063 if (auto CS = CallSite(&I))
1064 if (!CS.getCalledFunction()) {
1065 HasUnknownCall = true;
1066 break;
1067 }
1068
1069 SCCNodes.insert(&F);
1070 }
1071
1072 bool Changed = false;
David Majnemer5246e0b2016-07-19 18:50:26 +00001073 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001074 Changed |= addReadAttrs(SCCNodes, AARGetter);
1075 Changed |= addArgumentAttrs(SCCNodes);
1076
1077 // If we have no external nodes participating in the SCC, we can deduce some
1078 // more precise attributes as well.
1079 if (!HasUnknownCall) {
1080 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001081 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001082 Changed |= removeConvergentAttrs(SCCNodes);
1083 Changed |= addNoRecurseAttrs(SCCNodes);
1084 }
1085
1086 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1087}
1088
1089namespace {
1090struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1091 static char ID; // Pass identification, replacement for typeid
1092 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
1093 initializePostOrderFunctionAttrsLegacyPassPass(*PassRegistry::getPassRegistry());
1094 }
1095
1096 bool runOnSCC(CallGraphSCC &SCC) override;
1097
1098 void getAnalysisUsage(AnalysisUsage &AU) const override {
1099 AU.setPreservesCFG();
1100 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001101 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001102 CallGraphSCCPass::getAnalysisUsage(AU);
1103 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001104};
1105}
1106
1107char PostOrderFunctionAttrsLegacyPass::ID = 0;
1108INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1109 "Deduce function attributes", false, false)
1110INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1111INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001112INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1113 "Deduce function attributes", false, false)
1114
1115Pass *llvm::createPostOrderFunctionAttrsLegacyPass() { return new PostOrderFunctionAttrsLegacyPass(); }
1116
Sean Silva997cbea2016-07-03 03:35:03 +00001117template <typename AARGetterT>
1118static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthcada2d82015-10-31 00:28:37 +00001119 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001120
1121 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1122 // whether a given CallGraphNode is in this SCC. Also track whether there are
1123 // any external or opt-none nodes that will prevent us from optimizing any
1124 // part of the SCC.
1125 SCCNodeSet SCCNodes;
1126 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001127 for (CallGraphNode *I : SCC) {
1128 Function *F = I->getFunction();
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001129 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1130 // External node or function we're trying not to optimize - we both avoid
1131 // transform them and avoid leveraging information they provide.
1132 ExternalNode = true;
1133 continue;
1134 }
1135
1136 SCCNodes.insert(F);
1137 }
1138
David Majnemer5246e0b2016-07-19 18:50:26 +00001139 Changed |= addArgumentReturnedAttrs(SCCNodes);
Chandler Carrutha8125352015-10-30 16:48:08 +00001140 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001141 Changed |= addArgumentAttrs(SCCNodes);
1142
Chandler Carruth3a040e62015-12-27 08:41:34 +00001143 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001144 // more precise attributes as well.
1145 if (!ExternalNode) {
1146 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001147 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth3937bc72016-02-12 09:47:49 +00001148 Changed |= removeConvergentAttrs(SCCNodes);
Chandler Carruth632d2082016-02-13 08:47:51 +00001149 Changed |= addNoRecurseAttrs(SCCNodes);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001150 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001151
James Molloy7e9bdd52015-11-12 10:55:20 +00001152 return Changed;
1153}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001154
Sean Silva997cbea2016-07-03 03:35:03 +00001155bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1156 if (skipSCC(SCC))
1157 return false;
1158
1159 // We compute dedicated AA results for each function in the SCC as needed. We
1160 // use a lambda referencing external objects so that they live long enough to
1161 // be queried, but we re-use them each time.
1162 Optional<BasicAAResult> BAR;
1163 Optional<AAResults> AAR;
1164 auto AARGetter = [&](Function &F) -> AAResults & {
1165 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1166 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1167 return *AAR;
1168 };
1169
1170 return runImpl(SCC, AARGetter);
1171}
1172
Chandler Carruth1926b702016-01-08 10:55:52 +00001173namespace {
Sean Silvaf5080192016-06-12 07:48:51 +00001174struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Chandler Carruth1926b702016-01-08 10:55:52 +00001175 static char ID; // Pass identification, replacement for typeid
Sean Silvaf5080192016-06-12 07:48:51 +00001176 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
1177 initializeReversePostOrderFunctionAttrsLegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001178 }
1179
1180 bool runOnModule(Module &M) override;
1181
1182 void getAnalysisUsage(AnalysisUsage &AU) const override {
1183 AU.setPreservesCFG();
1184 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001185 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001186 }
1187};
1188}
1189
Sean Silvaf5080192016-06-12 07:48:51 +00001190char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1191INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001192 "Deduce function attributes in RPO", false, false)
1193INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001194INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001195 "Deduce function attributes in RPO", false, false)
1196
1197Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001198 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001199}
1200
1201static bool addNoRecurseAttrsTopDown(Function &F) {
1202 // We check the preconditions for the function prior to calling this to avoid
1203 // the cost of building up a reversible post-order list. We assert them here
1204 // to make sure none of the invariants this relies on were violated.
1205 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1206 assert(!F.doesNotRecurse() &&
1207 "This function has already been deduced as norecurs!");
1208 assert(F.hasInternalLinkage() &&
1209 "Can only do top-down deduction for internal linkage functions!");
1210
1211 // If F is internal and all of its uses are calls from a non-recursive
1212 // functions, then none of its calls could in fact recurse without going
1213 // through a function marked norecurse, and so we can mark this function too
1214 // as norecurse. Note that the uses must actually be calls -- otherwise
1215 // a pointer to this function could be returned from a norecurse function but
1216 // this function could be recursively (indirectly) called. Note that this
1217 // also detects if F is directly recursive as F is not yet marked as
1218 // a norecurse function.
1219 for (auto *U : F.users()) {
1220 auto *I = dyn_cast<Instruction>(U);
1221 if (!I)
1222 return false;
1223 CallSite CS(I);
1224 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1225 return false;
1226 }
1227 return setDoesNotRecurse(F);
1228}
1229
Sean Silvaadc79392016-06-12 05:44:51 +00001230static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001231 // We only have a post-order SCC traversal (because SCCs are inherently
1232 // discovered in post-order), so we accumulate them in a vector and then walk
1233 // it in reverse. This is simpler than using the RPO iterator infrastructure
1234 // because we need to combine SCC detection and the PO walk of the call
1235 // graph. We can also cheat egregiously because we're primarily interested in
1236 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1237 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001238 SmallVector<Function *, 16> Worklist;
1239 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1240 if (I->size() != 1)
1241 continue;
1242
1243 Function *F = I->front()->getFunction();
1244 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1245 F->hasInternalLinkage())
1246 Worklist.push_back(F);
1247 }
1248
James Molloy7e9bdd52015-11-12 10:55:20 +00001249 bool Changed = false;
Chandler Carruth1926b702016-01-08 10:55:52 +00001250 for (auto *F : reverse(Worklist))
1251 Changed |= addNoRecurseAttrsTopDown(*F);
1252
Duncan Sands44c8cd92008-12-31 16:14:43 +00001253 return Changed;
1254}
Sean Silvaadc79392016-06-12 05:44:51 +00001255
Sean Silvaf5080192016-06-12 07:48:51 +00001256bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001257 if (skipModule(M))
1258 return false;
1259
1260 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1261
1262 return deduceFunctionAttributeInRPO(M, CG);
1263}
Sean Silvaf5080192016-06-12 07:48:51 +00001264
1265PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001266ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001267 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1268
1269 bool Changed = deduceFunctionAttributeInRPO(M, CG);
Sean Silva744f7a82016-08-08 05:38:01 +00001270
1271 // CallGraphAnalysis holds AssertingVH and must be invalidated eagerly so
1272 // that other passes don't delete stuff from under it.
Sean Silva0873e7d2016-08-08 07:03:49 +00001273 // FIXME: We need to invalidate this to avoid PR28400. Is there a better
1274 // solution?
Sean Silva744f7a82016-08-08 05:38:01 +00001275 AM.invalidate<CallGraphAnalysis>(M);
1276
Sean Silvaf5080192016-06-12 07:48:51 +00001277 if (!Changed)
1278 return PreservedAnalyses::all();
1279 PreservedAnalyses PA;
1280 PA.preserve<CallGraphAnalysis>();
1281 return PA;
1282}