blob: a21a320faaa72c41ee09f4b3a57d5d62ffd37a01 [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");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000045STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
46STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000047STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000048STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000049STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Duncan Sands44c8cd92008-12-31 16:14:43 +000050
51namespace {
Chandler Carruthc518ebd2015-10-29 18:29:15 +000052typedef SmallSetVector<Function *, 8> SCCNodeSet;
53}
54
55namespace {
Chandler Carruth7542d372015-09-21 17:39:41 +000056/// The three kinds of memory access relevant to 'readonly' and
57/// 'readnone' attributes.
58enum MemoryAccessKind {
59 MAK_ReadNone = 0,
60 MAK_ReadOnly = 1,
61 MAK_MayWrite = 2
62};
63}
64
Chandler Carruthc518ebd2015-10-29 18:29:15 +000065static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
66 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +000067 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
68 if (MRB == FMRB_DoesNotAccessMemory)
69 // Already perfect!
70 return MAK_ReadNone;
71
Sanjoy Das5ce32722016-04-08 00:48:30 +000072 // Non-exact function definitions may not be selected at link time, and an
73 // alternative version that writes to memory may be selected. See the comment
74 // on GlobalValue::isDefinitionExact for more details.
75 if (!F.hasExactDefinition()) {
Chandler Carruth7542d372015-09-21 17:39:41 +000076 if (AliasAnalysis::onlyReadsMemory(MRB))
77 return MAK_ReadOnly;
78
79 // Conservatively assume it writes to memory.
80 return MAK_MayWrite;
81 }
82
83 // Scan the function body for instructions that may read or write memory.
84 bool ReadsMemory = false;
85 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
86 Instruction *I = &*II;
87
88 // Some instructions can be ignored even if they read or write memory.
89 // Detect these now, skipping to the next instruction if one is found.
90 CallSite CS(cast<Value>(I));
91 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +000092 // Ignore calls to functions in the same SCC, as long as the call sites
93 // don't have operand bundles. Calls with operand bundles are allowed to
94 // have memory effects not described by the memory effects of the call
95 // target.
96 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
97 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +000098 continue;
99 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Chandler Carruth7542d372015-09-21 17:39:41 +0000100
Chandler Carruth69798fb2015-10-27 01:41:43 +0000101 // If the call doesn't access memory, we're done.
102 if (!(MRB & MRI_ModRef))
103 continue;
104
105 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
106 // The call could access any memory. If that includes writes, give up.
107 if (MRB & MRI_Mod)
108 return MAK_MayWrite;
109 // If it reads, note it.
110 if (MRB & MRI_Ref)
111 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000112 continue;
113 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000114
115 // Check whether all pointer arguments point to local memory, and
116 // ignore calls that only access local memory.
117 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
118 CI != CE; ++CI) {
119 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000120 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000121 continue;
122
123 AAMDNodes AAInfo;
124 I->getAAMetadata(AAInfo);
125 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
126
127 // Skip accesses to local or constant memory as they don't impact the
128 // externally visible mod/ref behavior.
129 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
130 continue;
131
132 if (MRB & MRI_Mod)
133 // Writes non-local memory. Give up.
134 return MAK_MayWrite;
135 if (MRB & MRI_Ref)
136 // Ok, it reads non-local memory.
137 ReadsMemory = true;
138 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000139 continue;
140 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
141 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
142 if (!LI->isVolatile()) {
143 MemoryLocation Loc = MemoryLocation::get(LI);
144 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
145 continue;
146 }
147 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
148 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
149 if (!SI->isVolatile()) {
150 MemoryLocation Loc = MemoryLocation::get(SI);
151 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
152 continue;
153 }
154 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
155 // Ignore vaargs on local memory.
156 MemoryLocation Loc = MemoryLocation::get(VI);
157 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
158 continue;
159 }
160
161 // Any remaining instructions need to be taken seriously! Check if they
162 // read or write memory.
163 if (I->mayWriteToMemory())
164 // Writes memory. Just give up.
165 return MAK_MayWrite;
166
167 // If this instruction may read memory, remember that.
168 ReadsMemory |= I->mayReadFromMemory();
169 }
170
171 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
172}
173
Chandler Carrutha632fb92015-09-13 06:57:25 +0000174/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000175template <typename AARGetterT>
176static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000177 // Check if any of the functions in the SCC read or write memory. If they
178 // write memory then they can't be marked readnone or readonly.
179 bool ReadsMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000180 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000181 // Call the callable parameter to look up AA results for this function.
182 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000183
Chandler Carruth7542d372015-09-21 17:39:41 +0000184 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
185 case MAK_MayWrite:
186 return false;
187 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000188 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000189 break;
190 case MAK_ReadNone:
191 // Nothing to do!
192 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000193 }
194 }
195
196 // Success! Functions in this SCC do not access memory, or only read memory.
197 // Give them the appropriate attribute.
198 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000199 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000200 if (F->doesNotAccessMemory())
201 // Already perfect!
202 continue;
203
204 if (F->onlyReadsMemory() && ReadsMemory)
205 // No change.
206 continue;
207
208 MadeChange = true;
209
210 // Clear out any existing attributes.
Bill Wendling50d27842012-10-15 20:35:56 +0000211 AttrBuilder B;
Chandler Carruth63559d72015-09-13 06:47:20 +0000212 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
213 F->removeAttributes(
214 AttributeSet::FunctionIndex,
215 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
Duncan Sands44c8cd92008-12-31 16:14:43 +0000216
217 // Add in the new attribute.
Bill Wendlinge94d8432012-12-07 23:16:57 +0000218 F->addAttribute(AttributeSet::FunctionIndex,
Bill Wendlingc0e2a1f2013-01-23 00:20:53 +0000219 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000220
221 if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000222 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000223 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000224 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000225 }
226
227 return MadeChange;
228}
229
Nick Lewycky4c378a42011-12-28 23:24:21 +0000230namespace {
Chandler Carrutha632fb92015-09-13 06:57:25 +0000231/// For a given pointer Argument, this retains a list of Arguments of functions
232/// in the same SCC that the pointer data flows into. We use this to build an
233/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000234struct ArgumentGraphNode {
235 Argument *Definition;
236 SmallVector<ArgumentGraphNode *, 4> Uses;
237};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000238
Chandler Carruth63559d72015-09-13 06:47:20 +0000239class ArgumentGraph {
240 // We store pointers to ArgumentGraphNode objects, so it's important that
241 // that they not move around upon insert.
242 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000243
Chandler Carruth63559d72015-09-13 06:47:20 +0000244 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000245
Chandler Carruth63559d72015-09-13 06:47:20 +0000246 // There is no root node for the argument graph, in fact:
247 // void f(int *x, int *y) { if (...) f(x, y); }
248 // is an example where the graph is disconnected. The SCCIterator requires a
249 // single entry point, so we maintain a fake ("synthetic") root node that
250 // uses every node. Because the graph is directed and nothing points into
251 // the root, it will not participate in any SCCs (except for its own).
252 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000253
Chandler Carruth63559d72015-09-13 06:47:20 +0000254public:
255 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000256
Chandler Carruth63559d72015-09-13 06:47:20 +0000257 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000258
Chandler Carruth63559d72015-09-13 06:47:20 +0000259 iterator begin() { return SyntheticRoot.Uses.begin(); }
260 iterator end() { return SyntheticRoot.Uses.end(); }
261 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000262
Chandler Carruth63559d72015-09-13 06:47:20 +0000263 ArgumentGraphNode *operator[](Argument *A) {
264 ArgumentGraphNode &Node = ArgumentMap[A];
265 Node.Definition = A;
266 SyntheticRoot.Uses.push_back(&Node);
267 return &Node;
268 }
269};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000270
Chandler Carrutha632fb92015-09-13 06:57:25 +0000271/// This tracker checks whether callees are in the SCC, and if so it does not
272/// consider that a capture, instead adding it to the "Uses" list and
273/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000274struct ArgumentUsesTracker : public CaptureTracker {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000275 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
Nick Lewycky4c378a42011-12-28 23:24:21 +0000276 : Captured(false), SCCNodes(SCCNodes) {}
277
Chandler Carruth63559d72015-09-13 06:47:20 +0000278 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000279
Chandler Carruth63559d72015-09-13 06:47:20 +0000280 bool captured(const Use *U) override {
281 CallSite CS(U->getUser());
282 if (!CS.getInstruction()) {
283 Captured = true;
284 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000285 }
286
Chandler Carruth63559d72015-09-13 06:47:20 +0000287 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000288 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000289 Captured = true;
290 return true;
291 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000292
Sanjoy Das98bfe262015-11-05 03:04:40 +0000293 // Note: the callee and the two successor blocks *follow* the argument
294 // operands. This means there is no need to adjust UseIndex to account for
295 // these.
296
297 unsigned UseIndex =
298 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
299
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000300 assert(UseIndex < CS.data_operands_size() &&
301 "Indirect function calls should have been filtered above!");
302
303 if (UseIndex >= CS.getNumArgOperands()) {
304 // Data operand, but not a argument operand -- must be a bundle operand
305 assert(CS.hasOperandBundles() && "Must be!");
306
307 // CaptureTracking told us that we're being captured by an operand bundle
308 // use. In this case it does not matter if the callee is within our SCC
309 // or not -- we've been captured in some unknown way, and we have to be
310 // conservative.
311 Captured = true;
312 return true;
313 }
314
Sanjoy Das98bfe262015-11-05 03:04:40 +0000315 if (UseIndex >= F->arg_size()) {
316 assert(F->isVarArg() && "More params than args in non-varargs call");
317 Captured = true;
318 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000319 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000320
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000321 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000322 return false;
323 }
324
325 bool Captured; // True only if certainly captured (used outside our SCC).
326 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
327
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000328 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000329};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000330}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000331
332namespace llvm {
Chandler Carruth63559d72015-09-13 06:47:20 +0000333template <> struct GraphTraits<ArgumentGraphNode *> {
334 typedef ArgumentGraphNode NodeType;
335 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000336
Chandler Carruth63559d72015-09-13 06:47:20 +0000337 static inline NodeType *getEntryNode(NodeType *A) { return A; }
338 static inline ChildIteratorType child_begin(NodeType *N) {
339 return N->Uses.begin();
340 }
341 static inline ChildIteratorType child_end(NodeType *N) {
342 return N->Uses.end();
343 }
344};
345template <>
346struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
347 static NodeType *getEntryNode(ArgumentGraph *AG) {
348 return AG->getEntryNode();
349 }
350 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
351 return AG->begin();
352 }
353 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
354};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000355}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000356
Chandler Carrutha632fb92015-09-13 06:57:25 +0000357/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000358static Attribute::AttrKind
359determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000360 const SmallPtrSet<Argument *, 8> &SCCNodes) {
361
362 SmallVector<Use *, 32> Worklist;
363 SmallSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000364
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000365 // inalloca arguments are always clobbered by the call.
366 if (A->hasInAllocaAttr())
367 return Attribute::None;
368
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000369 bool IsRead = false;
370 // We don't need to track IsWritten. If A is written to, return immediately.
371
Chandler Carruthcdf47882014-03-09 03:16:01 +0000372 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000373 Visited.insert(&U);
374 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000375 }
376
377 while (!Worklist.empty()) {
378 Use *U = Worklist.pop_back_val();
379 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000380
381 switch (I->getOpcode()) {
382 case Instruction::BitCast:
383 case Instruction::GetElementPtr:
384 case Instruction::PHI:
385 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000386 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000387 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000388 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000389 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000390 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000391 break;
392
393 case Instruction::Call:
394 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000395 bool Captures = true;
396
397 if (I->getType()->isVoidTy())
398 Captures = false;
399
400 auto AddUsersToWorklistIfCapturing = [&] {
401 if (Captures)
402 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000403 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000404 Worklist.push_back(&UU);
405 };
406
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000407 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000408 if (CS.doesNotAccessMemory()) {
409 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000410 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000411 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000412
413 Function *F = CS.getCalledFunction();
414 if (!F) {
415 if (CS.onlyReadsMemory()) {
416 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000417 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000418 continue;
419 }
420 return Attribute::None;
421 }
422
Sanjoy Das436e2392015-11-07 01:55:53 +0000423 // Note: the callee and the two successor blocks *follow* the argument
424 // operands. This means there is no need to adjust UseIndex to account
425 // for these.
426
427 unsigned UseIndex = std::distance(CS.arg_begin(), U);
428
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000429 // U cannot be the callee operand use: since we're exploring the
430 // transitive uses of an Argument, having such a use be a callee would
431 // imply the CallSite is an indirect call or invoke; and we'd take the
432 // early exit above.
433 assert(UseIndex < CS.data_operands_size() &&
434 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000435
436 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
437
438 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000439 assert(F->isVarArg() && "More params than args in non-varargs call");
440 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000441 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000442
Tilmann Scheller925b1932015-11-20 19:17:10 +0000443 Captures &= !CS.doesNotCapture(UseIndex);
444
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000445 // Since the optimizer (by design) cannot see the data flow corresponding
446 // to a operand bundle use, these cannot participate in the optimistic SCC
447 // analysis. Instead, we model the operand bundle uses as arguments in
448 // call to a function external to the SCC.
Sanjoy Das76dd2432015-11-07 02:26:53 +0000449 if (!SCCNodes.count(&*std::next(F->arg_begin(), UseIndex)) ||
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000450 IsOperandBundleUse) {
451
452 // The accessors used on CallSite here do the right thing for calls and
453 // invokes with operand bundles.
454
Sanjoy Das436e2392015-11-07 01:55:53 +0000455 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
456 return Attribute::None;
457 if (!CS.doesNotAccessMemory(UseIndex))
458 IsRead = true;
459 }
460
Nick Lewycky59633cb2014-05-30 02:31:27 +0000461 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000462 break;
463 }
464
465 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000466 // A volatile load has side effects beyond what readonly can be relied
467 // upon.
468 if (cast<LoadInst>(I)->isVolatile())
469 return Attribute::None;
470
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000471 IsRead = true;
472 break;
473
474 case Instruction::ICmp:
475 case Instruction::Ret:
476 break;
477
478 default:
479 return Attribute::None;
480 }
481 }
482
483 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
484}
485
Chandler Carrutha632fb92015-09-13 06:57:25 +0000486/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000487static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000488 bool Changed = false;
489
Nick Lewycky4c378a42011-12-28 23:24:21 +0000490 ArgumentGraph AG;
491
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000492 AttrBuilder B;
493 B.addAttribute(Attribute::NoCapture);
494
Duncan Sands44c8cd92008-12-31 16:14:43 +0000495 // Check each function in turn, determining which pointer arguments are not
496 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000497 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000498 // We can infer and propagate function attributes only when we know that the
499 // definition we'll get at link time is *exactly* the definition we see now.
500 // For more details, see GlobalValue::mayBeDerefined.
501 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000502 continue;
503
Nick Lewycky4c378a42011-12-28 23:24:21 +0000504 // Functions that are readonly (or readnone) and nounwind and don't return
505 // a value can't capture arguments. Don't analyze them.
506 if (F->onlyReadsMemory() && F->doesNotThrow() &&
507 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000508 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
509 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000510 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
511 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
512 ++NumNoCapture;
513 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000514 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000515 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000516 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000517 }
518
Chandler Carruth63559d72015-09-13 06:47:20 +0000519 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
520 ++A) {
521 if (!A->getType()->isPointerTy())
522 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000523 bool HasNonLocalUses = false;
524 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000525 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000526 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000527 if (!Tracker.Captured) {
528 if (Tracker.Uses.empty()) {
529 // If it's trivially not captured, mark it nocapture now.
Chandler Carruth63559d72015-09-13 06:47:20 +0000530 A->addAttr(
531 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000532 ++NumNoCapture;
533 Changed = true;
534 } else {
535 // If it's not trivially captured and not trivially not captured,
536 // then it must be calling into another function in our SCC. Save
537 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000538 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000539 for (Argument *Use : Tracker.Uses) {
540 Node->Uses.push_back(AG[Use]);
541 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000542 HasNonLocalUses = true;
543 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000544 }
545 }
546 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
547 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000548 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
549 // Can we determine that it's readonly/readnone without doing an SCC?
550 // Note that we don't allow any calls at all here, or else our result
551 // will be dependent on the iteration order through the functions in the
552 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000553 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000554 Self.insert(&*A);
555 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000556 if (R != Attribute::None) {
557 AttrBuilder B;
558 B.addAttribute(R);
559 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
560 Changed = true;
561 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
562 }
563 }
564 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000565 }
566
567 // The graph we've collected is partial because we stopped scanning for
568 // argument uses once we solved the argument trivially. These partial nodes
569 // show up as ArgumentGraphNode objects with an empty Uses list, and for
570 // these nodes the final decision about whether they capture has already been
571 // made. If the definition doesn't have a 'nocapture' attribute by now, it
572 // captures.
573
Chandler Carruth63559d72015-09-13 06:47:20 +0000574 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000575 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000576 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000577 if (!ArgumentSCC[0]->Definition)
578 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000579
580 // eg. "void f(int* x) { if (...) f(x); }"
581 if (ArgumentSCC[0]->Uses.size() == 1 &&
582 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000583 Argument *A = ArgumentSCC[0]->Definition;
584 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky7e820552009-01-02 03:46:56 +0000585 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000586 Changed = true;
587 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000588 continue;
589 }
590
591 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000592 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
593 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000594 ArgumentGraphNode *Node = *I;
595 if (Node->Uses.empty()) {
596 if (!Node->Definition->hasNoCaptureAttr())
597 SCCCaptured = true;
598 }
599 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000600 if (SCCCaptured)
601 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000602
Chandler Carruth63559d72015-09-13 06:47:20 +0000603 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000604 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
605 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000606 for (ArgumentGraphNode *I : ArgumentSCC) {
607 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000608 }
609
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000610 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
611 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000612 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000613 for (ArgumentGraphNode *Use : N->Uses) {
614 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000615 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
616 continue;
617 SCCCaptured = true;
618 break;
619 }
620 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000621 if (SCCCaptured)
622 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000623
Nick Lewyckyf740db32012-01-05 22:21:45 +0000624 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000625 Argument *A = ArgumentSCC[i]->Definition;
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000626 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
Nick Lewycky4c378a42011-12-28 23:24:21 +0000627 ++NumNoCapture;
628 Changed = true;
629 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000630
631 // We also want to compute readonly/readnone. With a small number of false
632 // negatives, we can assume that any pointer which is captured isn't going
633 // to be provably readonly or readnone, since by definition we can't
634 // analyze all uses of a captured pointer.
635 //
636 // The false negatives happen when the pointer is captured by a function
637 // that promises readonly/readnone behaviour on the pointer, then the
638 // pointer's lifetime ends before anything that writes to arbitrary memory.
639 // Also, a readonly/readnone pointer may be returned, but returning a
640 // pointer is capturing it.
641
642 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
643 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
644 Argument *A = ArgumentSCC[i]->Definition;
645 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
646 if (K == Attribute::ReadNone)
647 continue;
648 if (K == Attribute::ReadOnly) {
649 ReadAttr = Attribute::ReadOnly;
650 continue;
651 }
652 ReadAttr = K;
653 break;
654 }
655
656 if (ReadAttr != Attribute::None) {
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000657 AttrBuilder B, R;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000658 B.addAttribute(ReadAttr);
Chandler Carruth63559d72015-09-13 06:47:20 +0000659 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000660 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
661 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000662 // Clear out existing readonly/readnone attributes
663 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000664 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
665 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
666 Changed = true;
667 }
668 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000669 }
670
671 return Changed;
672}
673
Chandler Carrutha632fb92015-09-13 06:57:25 +0000674/// Tests whether a function is "malloc-like".
675///
676/// A function is "malloc-like" if it returns either null or a pointer that
677/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000678static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000679 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000680 for (BasicBlock &BB : *F)
681 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000682 FlowsToReturn.insert(Ret->getReturnValue());
683
684 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000685 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000686
687 if (Constant *C = dyn_cast<Constant>(RetVal)) {
688 if (!C->isNullValue() && !isa<UndefValue>(C))
689 return false;
690
691 continue;
692 }
693
694 if (isa<Argument>(RetVal))
695 return false;
696
697 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
698 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000699 // Extend the analysis by looking upwards.
700 case Instruction::BitCast:
701 case Instruction::GetElementPtr:
702 case Instruction::AddrSpaceCast:
703 FlowsToReturn.insert(RVI->getOperand(0));
704 continue;
705 case Instruction::Select: {
706 SelectInst *SI = cast<SelectInst>(RVI);
707 FlowsToReturn.insert(SI->getTrueValue());
708 FlowsToReturn.insert(SI->getFalseValue());
709 continue;
710 }
711 case Instruction::PHI: {
712 PHINode *PN = cast<PHINode>(RVI);
713 for (Value *IncValue : PN->incoming_values())
714 FlowsToReturn.insert(IncValue);
715 continue;
716 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000717
Chandler Carruth63559d72015-09-13 06:47:20 +0000718 // Check whether the pointer came from an allocation.
719 case Instruction::Alloca:
720 break;
721 case Instruction::Call:
722 case Instruction::Invoke: {
723 CallSite CS(RVI);
724 if (CS.paramHasAttr(0, Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000725 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000726 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
727 break;
728 } // fall-through
729 default:
730 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000731 }
732
Dan Gohman94e61762009-11-19 21:57:48 +0000733 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000734 return false;
735 }
736
737 return true;
738}
739
Chandler Carrutha632fb92015-09-13 06:57:25 +0000740/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000741static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000742 // Check each function in turn, determining which functions return noalias
743 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000744 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000745 // Already noalias.
746 if (F->doesNotAlias(0))
747 continue;
748
Sanjoy Das5ce32722016-04-08 00:48:30 +0000749 // We can infer and propagate function attributes only when we know that the
750 // definition we'll get at link time is *exactly* the definition we see now.
751 // For more details, see GlobalValue::mayBeDerefined.
752 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000753 return false;
754
Chandler Carruth63559d72015-09-13 06:47:20 +0000755 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000756 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000757 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000758 continue;
759
Chandler Carruth3824f852015-09-13 08:23:27 +0000760 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000761 return false;
762 }
763
764 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000765 for (Function *F : SCCNodes) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000766 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000767 continue;
768
769 F->setDoesNotAlias(0);
770 ++NumNoAlias;
771 MadeChange = true;
772 }
773
774 return MadeChange;
775}
776
Chandler Carrutha632fb92015-09-13 06:57:25 +0000777/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000778///
779/// Requires that the function returns a pointer.
780///
781/// Returns true if it believes the function will not return a null, and sets
782/// \p Speculative based on whether the returned conclusion is a speculative
783/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000784static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000785 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000786 assert(F->getReturnType()->isPointerTy() &&
787 "nonnull only meaningful on pointer types");
788 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000789
Philip Reamesa88caea2015-08-31 19:44:38 +0000790 SmallSetVector<Value *, 8> FlowsToReturn;
791 for (BasicBlock &BB : *F)
792 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
793 FlowsToReturn.insert(Ret->getReturnValue());
794
795 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
796 Value *RetVal = FlowsToReturn[i];
797
798 // If this value is locally known to be non-null, we're good
Sean Silva45835e72016-07-02 23:47:27 +0000799 if (isKnownNonNull(RetVal))
Philip Reamesa88caea2015-08-31 19:44:38 +0000800 continue;
801
802 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000803 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000804 Instruction *RVI = dyn_cast<Instruction>(RetVal);
805 if (!RVI)
806 return false;
807 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000808 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000809 case Instruction::BitCast:
810 case Instruction::GetElementPtr:
811 case Instruction::AddrSpaceCast:
812 FlowsToReturn.insert(RVI->getOperand(0));
813 continue;
814 case Instruction::Select: {
815 SelectInst *SI = cast<SelectInst>(RVI);
816 FlowsToReturn.insert(SI->getTrueValue());
817 FlowsToReturn.insert(SI->getFalseValue());
818 continue;
819 }
820 case Instruction::PHI: {
821 PHINode *PN = cast<PHINode>(RVI);
822 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
823 FlowsToReturn.insert(PN->getIncomingValue(i));
824 continue;
825 }
826 case Instruction::Call:
827 case Instruction::Invoke: {
828 CallSite CS(RVI);
829 Function *Callee = CS.getCalledFunction();
830 // A call to a node within the SCC is assumed to return null until
831 // proven otherwise
832 if (Callee && SCCNodes.count(Callee)) {
833 Speculative = true;
834 continue;
835 }
836 return false;
837 }
838 default:
Chandler Carruth63559d72015-09-13 06:47:20 +0000839 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +0000840 };
841 llvm_unreachable("should have either continued or returned");
842 }
843
844 return true;
845}
846
Chandler Carrutha632fb92015-09-13 06:57:25 +0000847/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +0000848static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000849 // Speculative that all functions in the SCC return only nonnull
850 // pointers. We may refute this as we analyze functions.
851 bool SCCReturnsNonNull = true;
852
853 bool MadeChange = false;
854
855 // Check each function in turn, determining which functions return nonnull
856 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000857 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000858 // Already nonnull.
859 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
860 Attribute::NonNull))
861 continue;
862
Sanjoy Das5ce32722016-04-08 00:48:30 +0000863 // We can infer and propagate function attributes only when we know that the
864 // definition we'll get at link time is *exactly* the definition we see now.
865 // For more details, see GlobalValue::mayBeDerefined.
866 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +0000867 return false;
868
Chandler Carruth63559d72015-09-13 06:47:20 +0000869 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +0000870 // pointer types.
871 if (!F->getReturnType()->isPointerTy())
872 continue;
873
874 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +0000875 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000876 if (!Speculative) {
877 // Mark the function eagerly since we may discover a function
878 // which prevents us from speculating about the entire SCC
879 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
880 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
881 ++NumNonNullReturn;
882 MadeChange = true;
883 }
884 continue;
885 }
886 // At least one function returns something which could be null, can't
887 // speculate any more.
888 SCCReturnsNonNull = false;
889 }
890
891 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000892 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000893 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
894 Attribute::NonNull) ||
895 !F->getReturnType()->isPointerTy())
896 continue;
897
898 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
899 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
900 ++NumNonNullReturn;
901 MadeChange = true;
902 }
903 }
904
905 return MadeChange;
906}
907
Justin Lebar9d943972016-03-14 20:18:54 +0000908/// Remove the convergent attribute from all functions in the SCC if every
909/// callsite within the SCC is not convergent (except for calls to functions
910/// within the SCC). Returns true if changes were made.
Chandler Carruth3937bc72016-02-12 09:47:49 +0000911static bool removeConvergentAttrs(const SCCNodeSet &SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +0000912 // For every function in SCC, ensure that either
913 // * it is not convergent, or
914 // * we can remove its convergent attribute.
915 bool HasConvergentFn = false;
Chandler Carruth3937bc72016-02-12 09:47:49 +0000916 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +0000917 if (!F->isConvergent()) continue;
918 HasConvergentFn = true;
919
920 // Can't remove convergent from function declarations.
921 if (F->isDeclaration()) return false;
922
923 // Can't remove convergent if any of our functions has a convergent call to a
924 // function not in the SCC.
925 for (Instruction &I : instructions(*F)) {
926 CallSite CS(&I);
927 // Bail if CS is a convergent call to a function not in the SCC.
928 if (CS && CS.isConvergent() &&
929 SCCNodes.count(CS.getCalledFunction()) == 0)
930 return false;
931 }
932 }
933
934 // If the SCC doesn't have any convergent functions, we have nothing to do.
935 if (!HasConvergentFn) return false;
936
937 // If we got here, all of the calls the SCC makes to functions not in the SCC
938 // are non-convergent. Therefore all of the SCC's functions can also be made
939 // non-convergent. We'll remove the attr from the callsites in
940 // InstCombineCalls.
941 for (Function *F : SCCNodes) {
942 if (!F->isConvergent()) continue;
943
944 DEBUG(dbgs() << "Removing convergent attr from fn " << F->getName()
945 << "\n");
Chandler Carruth3937bc72016-02-12 09:47:49 +0000946 F->setNotConvergent();
947 }
Justin Lebar260854b2016-02-09 23:03:22 +0000948 return true;
949}
950
James Molloy7e9bdd52015-11-12 10:55:20 +0000951static bool setDoesNotRecurse(Function &F) {
952 if (F.doesNotRecurse())
953 return false;
954 F.setDoesNotRecurse();
955 ++NumNoRecurse;
956 return true;
957}
958
Chandler Carruth632d2082016-02-13 08:47:51 +0000959static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +0000960 // Try and identify functions that do not recurse.
961
962 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +0000963 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +0000964 return false;
965
Chandler Carruth632d2082016-02-13 08:47:51 +0000966 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +0000967 if (!F || F->isDeclaration() || F->doesNotRecurse())
968 return false;
969
970 // If all of the calls in F are identifiable and are to norecurse functions, F
971 // is norecurse. This check also detects self-recursion as F is not currently
972 // marked norecurse, so any called from F to F will not be marked norecurse.
Chandler Carruth632d2082016-02-13 08:47:51 +0000973 for (Instruction &I : instructions(*F))
974 if (auto CS = CallSite(&I)) {
975 Function *Callee = CS.getCalledFunction();
976 if (!Callee || Callee == F || !Callee->doesNotRecurse())
977 // Function calls a potentially recursive function.
978 return false;
979 }
James Molloy7e9bdd52015-11-12 10:55:20 +0000980
Chandler Carruth632d2082016-02-13 08:47:51 +0000981 // Every call was to a non-recursive function other than this function, and
982 // we have no indirect recursion as the SCC size is one. This function cannot
983 // recurse.
984 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +0000985}
986
Chandler Carruthb47f8012016-03-11 11:05:24 +0000987PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
988 CGSCCAnalysisManager &AM) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +0000989 FunctionAnalysisManager &FAM =
Chandler Carruthb47f8012016-03-11 11:05:24 +0000990 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +0000991
Chandler Carruth9c4ed172016-02-18 11:03:11 +0000992 // We pass a lambda into functions to wire them up to the analysis manager
993 // for getting function analyses.
994 auto AARGetter = [&](Function &F) -> AAResults & {
995 return FAM.getResult<AAManager>(F);
996 };
997
998 // Fill SCCNodes with the elements of the SCC. Also track whether there are
999 // any external or opt-none nodes that will prevent us from optimizing any
1000 // part of the SCC.
1001 SCCNodeSet SCCNodes;
1002 bool HasUnknownCall = false;
1003 for (LazyCallGraph::Node &N : C) {
1004 Function &F = N.getFunction();
1005 if (F.hasFnAttribute(Attribute::OptimizeNone)) {
1006 // Treat any function we're trying not to optimize as if it were an
1007 // indirect call and omit it from the node set used below.
1008 HasUnknownCall = true;
1009 continue;
1010 }
1011 // Track whether any functions in this SCC have an unknown call edge.
1012 // Note: if this is ever a performance hit, we can common it with
1013 // subsequent routines which also do scans over the instructions of the
1014 // function.
1015 if (!HasUnknownCall)
1016 for (Instruction &I : instructions(F))
1017 if (auto CS = CallSite(&I))
1018 if (!CS.getCalledFunction()) {
1019 HasUnknownCall = true;
1020 break;
1021 }
1022
1023 SCCNodes.insert(&F);
1024 }
1025
1026 bool Changed = false;
1027 Changed |= addReadAttrs(SCCNodes, AARGetter);
1028 Changed |= addArgumentAttrs(SCCNodes);
1029
1030 // If we have no external nodes participating in the SCC, we can deduce some
1031 // more precise attributes as well.
1032 if (!HasUnknownCall) {
1033 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001034 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001035 Changed |= removeConvergentAttrs(SCCNodes);
1036 Changed |= addNoRecurseAttrs(SCCNodes);
1037 }
1038
1039 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1040}
1041
1042namespace {
1043struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1044 static char ID; // Pass identification, replacement for typeid
1045 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
1046 initializePostOrderFunctionAttrsLegacyPassPass(*PassRegistry::getPassRegistry());
1047 }
1048
1049 bool runOnSCC(CallGraphSCC &SCC) override;
1050
1051 void getAnalysisUsage(AnalysisUsage &AU) const override {
1052 AU.setPreservesCFG();
1053 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001054 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001055 CallGraphSCCPass::getAnalysisUsage(AU);
1056 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001057};
1058}
1059
1060char PostOrderFunctionAttrsLegacyPass::ID = 0;
1061INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1062 "Deduce function attributes", false, false)
1063INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1064INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001065INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1066 "Deduce function attributes", false, false)
1067
1068Pass *llvm::createPostOrderFunctionAttrsLegacyPass() { return new PostOrderFunctionAttrsLegacyPass(); }
1069
1070bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001071 if (skipSCC(SCC))
1072 return false;
Chandler Carruthcada2d82015-10-31 00:28:37 +00001073 bool Changed = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001074
Chandler Carrutha8125352015-10-30 16:48:08 +00001075 // We compute dedicated AA results for each function in the SCC as needed. We
1076 // use a lambda referencing external objects so that they live long enough to
1077 // be queried, but we re-use them each time.
1078 Optional<BasicAAResult> BAR;
1079 Optional<AAResults> AAR;
1080 auto AARGetter = [&](Function &F) -> AAResults & {
1081 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1082 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1083 return *AAR;
1084 };
1085
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001086 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1087 // whether a given CallGraphNode is in this SCC. Also track whether there are
1088 // any external or opt-none nodes that will prevent us from optimizing any
1089 // part of the SCC.
1090 SCCNodeSet SCCNodes;
1091 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001092 for (CallGraphNode *I : SCC) {
1093 Function *F = I->getFunction();
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001094 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1095 // External node or function we're trying not to optimize - we both avoid
1096 // transform them and avoid leveraging information they provide.
1097 ExternalNode = true;
1098 continue;
1099 }
1100
1101 SCCNodes.insert(F);
1102 }
1103
Chandler Carrutha8125352015-10-30 16:48:08 +00001104 Changed |= addReadAttrs(SCCNodes, AARGetter);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001105 Changed |= addArgumentAttrs(SCCNodes);
1106
Chandler Carruth3a040e62015-12-27 08:41:34 +00001107 // If we have no external nodes participating in the SCC, we can deduce some
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001108 // more precise attributes as well.
1109 if (!ExternalNode) {
1110 Changed |= addNoAliasAttrs(SCCNodes);
Sean Silva45835e72016-07-02 23:47:27 +00001111 Changed |= addNonNullAttrs(SCCNodes);
Chandler Carruth3937bc72016-02-12 09:47:49 +00001112 Changed |= removeConvergentAttrs(SCCNodes);
Chandler Carruth632d2082016-02-13 08:47:51 +00001113 Changed |= addNoRecurseAttrs(SCCNodes);
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001114 }
Chandler Carruth1926b702016-01-08 10:55:52 +00001115
James Molloy7e9bdd52015-11-12 10:55:20 +00001116 return Changed;
1117}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001118
Chandler Carruth1926b702016-01-08 10:55:52 +00001119namespace {
Sean Silvaf5080192016-06-12 07:48:51 +00001120struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Chandler Carruth1926b702016-01-08 10:55:52 +00001121 static char ID; // Pass identification, replacement for typeid
Sean Silvaf5080192016-06-12 07:48:51 +00001122 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
1123 initializeReversePostOrderFunctionAttrsLegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001124 }
1125
1126 bool runOnModule(Module &M) override;
1127
1128 void getAnalysisUsage(AnalysisUsage &AU) const override {
1129 AU.setPreservesCFG();
1130 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001131 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001132 }
1133};
1134}
1135
Sean Silvaf5080192016-06-12 07:48:51 +00001136char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1137INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001138 "Deduce function attributes in RPO", false, false)
1139INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001140INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001141 "Deduce function attributes in RPO", false, false)
1142
1143Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001144 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001145}
1146
1147static bool addNoRecurseAttrsTopDown(Function &F) {
1148 // We check the preconditions for the function prior to calling this to avoid
1149 // the cost of building up a reversible post-order list. We assert them here
1150 // to make sure none of the invariants this relies on were violated.
1151 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1152 assert(!F.doesNotRecurse() &&
1153 "This function has already been deduced as norecurs!");
1154 assert(F.hasInternalLinkage() &&
1155 "Can only do top-down deduction for internal linkage functions!");
1156
1157 // If F is internal and all of its uses are calls from a non-recursive
1158 // functions, then none of its calls could in fact recurse without going
1159 // through a function marked norecurse, and so we can mark this function too
1160 // as norecurse. Note that the uses must actually be calls -- otherwise
1161 // a pointer to this function could be returned from a norecurse function but
1162 // this function could be recursively (indirectly) called. Note that this
1163 // also detects if F is directly recursive as F is not yet marked as
1164 // a norecurse function.
1165 for (auto *U : F.users()) {
1166 auto *I = dyn_cast<Instruction>(U);
1167 if (!I)
1168 return false;
1169 CallSite CS(I);
1170 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1171 return false;
1172 }
1173 return setDoesNotRecurse(F);
1174}
1175
Sean Silvaadc79392016-06-12 05:44:51 +00001176static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001177 // We only have a post-order SCC traversal (because SCCs are inherently
1178 // discovered in post-order), so we accumulate them in a vector and then walk
1179 // it in reverse. This is simpler than using the RPO iterator infrastructure
1180 // because we need to combine SCC detection and the PO walk of the call
1181 // graph. We can also cheat egregiously because we're primarily interested in
1182 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1183 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001184 SmallVector<Function *, 16> Worklist;
1185 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1186 if (I->size() != 1)
1187 continue;
1188
1189 Function *F = I->front()->getFunction();
1190 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1191 F->hasInternalLinkage())
1192 Worklist.push_back(F);
1193 }
1194
James Molloy7e9bdd52015-11-12 10:55:20 +00001195 bool Changed = false;
Chandler Carruth1926b702016-01-08 10:55:52 +00001196 for (auto *F : reverse(Worklist))
1197 Changed |= addNoRecurseAttrsTopDown(*F);
1198
Duncan Sands44c8cd92008-12-31 16:14:43 +00001199 return Changed;
1200}
Sean Silvaadc79392016-06-12 05:44:51 +00001201
Sean Silvaf5080192016-06-12 07:48:51 +00001202bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001203 if (skipModule(M))
1204 return false;
1205
1206 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1207
1208 return deduceFunctionAttributeInRPO(M, CG);
1209}
Sean Silvaf5080192016-06-12 07:48:51 +00001210
1211PreservedAnalyses
1212ReversePostOrderFunctionAttrsPass::run(Module &M, AnalysisManager<Module> &AM) {
1213 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1214
1215 bool Changed = deduceFunctionAttributeInRPO(M, CG);
1216 if (!Changed)
1217 return PreservedAnalyses::all();
1218 PreservedAnalyses PA;
1219 PA.preserve<CallGraphAnalysis>();
1220 return PA;
1221}