blob: d40ee30f453eed0bdede6f96f3f3e34a3a64d3a2 [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//===----------------------------------------------------------------------===//
Eugene Zelenkof27d1612017-10-19 21:21:30 +00009//
Chandler Carruth1926b702016-01-08 10:55:52 +000010/// \file
11/// This file implements interprocedural passes which walk the
12/// call-graph deducing and/or propagating function attributes.
Eugene Zelenkof27d1612017-10-19 21:21:30 +000013//
Duncan Sands44c8cd92008-12-31 16:14:43 +000014//===----------------------------------------------------------------------===//
15
Chandler Carruth9c4ed172016-02-18 11:03:11 +000016#include "llvm/Transforms/IPO/FunctionAttrs.h"
Nick Lewycky4c378a42011-12-28 23:24:21 +000017#include "llvm/ADT/SCCIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000018#include "llvm/ADT/STLExtras.h"
Benjamin Kramer15591272012-10-31 13:45:49 +000019#include "llvm/ADT/SetVector.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000020#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000021#include "llvm/ADT/SmallVector.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000024#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000025#include "llvm/Analysis/BasicAliasAnalysis.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000026#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000028#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Analysis/CaptureTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000030#include "llvm/Analysis/LazyCallGraph.h"
31#include "llvm/Analysis/MemoryLocation.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000032#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000033#include "llvm/IR/Argument.h"
34#include "llvm/IR/Attributes.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/CallSite.h"
37#include "llvm/IR/Constant.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000040#include "llvm/IR/InstIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000041#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/Metadata.h"
45#include "llvm/IR/PassManager.h"
46#include "llvm/IR/Type.h"
47#include "llvm/IR/Use.h"
48#include "llvm/IR/User.h"
49#include "llvm/IR/Value.h"
50#include "llvm/Pass.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000054#include "llvm/Support/Debug.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000055#include "llvm/Support/ErrorHandling.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000056#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000057#include "llvm/Transforms/IPO.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000058#include <cassert>
59#include <iterator>
60#include <map>
61#include <vector>
62
Duncan Sands44c8cd92008-12-31 16:14:43 +000063using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "functionattrs"
66
Duncan Sands44c8cd92008-12-31 16:14:43 +000067STATISTIC(NumReadNone, "Number of functions marked readnone");
68STATISTIC(NumReadOnly, "Number of functions marked readonly");
Brian Homerding3ecabd72018-08-23 15:05:22 +000069STATISTIC(NumWriteOnly, "Number of functions marked writeonly");
Duncan Sands44c8cd92008-12-31 16:14:43 +000070STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
David Majnemer5246e0b2016-07-19 18:50:26 +000071STATISTIC(NumReturned, "Number of arguments marked returned");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000072STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
73STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000074STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000075STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000076STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Fedor Sergeev6660fd02018-03-23 21:46:16 +000077STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
Duncan Sands44c8cd92008-12-31 16:14:43 +000078
Sanjay Patel4f742162017-02-13 23:10:51 +000079// FIXME: This is disabled by default to avoid exposing security vulnerabilities
80// in C/C++ code compiled by clang:
81// http://lists.llvm.org/pipermail/cfe-dev/2017-January/052066.html
82static cl::opt<bool> EnableNonnullArgPropagation(
83 "enable-nonnull-arg-prop", cl::Hidden,
84 cl::desc("Try to propagate nonnull argument attributes from callsites to "
85 "caller functions."));
86
Fedor Sergeev6660fd02018-03-23 21:46:16 +000087static cl::opt<bool> DisableNoUnwindInference(
88 "disable-nounwind-inference", cl::Hidden,
89 cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
90
Duncan Sands44c8cd92008-12-31 16:14:43 +000091namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +000092
93using SCCNodeSet = SmallSetVector<Function *, 8>;
94
95} // end anonymous namespace
Chandler Carruthc518ebd2015-10-29 18:29:15 +000096
Peter Collingbournec45f7f32017-02-14 00:28:13 +000097/// Returns the memory access attribute for function F using AAR for AA results,
98/// where SCCNodes is the current SCC.
99///
100/// If ThisBody is true, this function may examine the function body and will
101/// return a result pertaining to this copy of the function. If it is false, the
102/// result will be based only on AA results for the function declaration; it
103/// will be assumed that some other (perhaps less optimized) version of the
104/// function may be selected at link time.
105static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
106 AAResults &AAR,
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000107 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000108 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
109 if (MRB == FMRB_DoesNotAccessMemory)
110 // Already perfect!
111 return MAK_ReadNone;
112
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000113 if (!ThisBody) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000114 if (AliasAnalysis::onlyReadsMemory(MRB))
115 return MAK_ReadOnly;
116
Brian Homerding3ecabd72018-08-23 15:05:22 +0000117 if (AliasAnalysis::doesNotReadMemory(MRB))
118 return MAK_WriteOnly;
119
120 // Conservatively assume it reads and writes to memory.
Chandler Carruth7542d372015-09-21 17:39:41 +0000121 return MAK_MayWrite;
122 }
123
124 // Scan the function body for instructions that may read or write memory.
125 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000126 bool WritesMemory = false;
Chandler Carruth7542d372015-09-21 17:39:41 +0000127 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
128 Instruction *I = &*II;
129
130 // Some instructions can be ignored even if they read or write memory.
131 // Detect these now, skipping to the next instruction if one is found.
132 CallSite CS(cast<Value>(I));
133 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000134 // Ignore calls to functions in the same SCC, as long as the call sites
135 // don't have operand bundles. Calls with operand bundles are allowed to
136 // have memory effects not described by the memory effects of the call
137 // target.
138 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
139 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000140 continue;
141 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000142 ModRefInfo MRI = createModRefInfo(MRB);
Chandler Carruth7542d372015-09-21 17:39:41 +0000143
Chandler Carruth69798fb2015-10-27 01:41:43 +0000144 // If the call doesn't access memory, we're done.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000145 if (isNoModRef(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000146 continue;
147
148 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
Brian Homerding3ecabd72018-08-23 15:05:22 +0000149 // The call could access any memory. If that includes writes, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000150 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000151 WritesMemory = true;
Chandler Carruth69798fb2015-10-27 01:41:43 +0000152 // If it reads, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000153 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000154 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000155 continue;
156 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000157
158 // Check whether all pointer arguments point to local memory, and
159 // ignore calls that only access local memory.
160 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
161 CI != CE; ++CI) {
162 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000163 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000164 continue;
165
166 AAMDNodes AAInfo;
167 I->getAAMetadata(AAInfo);
168 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
169
170 // Skip accesses to local or constant memory as they don't impact the
171 // externally visible mod/ref behavior.
172 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
173 continue;
174
Alina Sbirlea63d22502017-12-05 20:12:23 +0000175 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000176 // Writes non-local memory.
177 WritesMemory = true;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000178 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000179 // Ok, it reads non-local memory.
180 ReadsMemory = true;
181 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000182 continue;
183 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
184 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
185 if (!LI->isVolatile()) {
186 MemoryLocation Loc = MemoryLocation::get(LI);
187 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
188 continue;
189 }
190 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
191 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
192 if (!SI->isVolatile()) {
193 MemoryLocation Loc = MemoryLocation::get(SI);
194 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
195 continue;
196 }
197 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
198 // Ignore vaargs on local memory.
199 MemoryLocation Loc = MemoryLocation::get(VI);
200 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
201 continue;
202 }
203
204 // Any remaining instructions need to be taken seriously! Check if they
205 // read or write memory.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000206 //
207 // Writes memory, remember that.
208 WritesMemory |= I->mayWriteToMemory();
Chandler Carruth7542d372015-09-21 17:39:41 +0000209
210 // If this instruction may read memory, remember that.
211 ReadsMemory |= I->mayReadFromMemory();
212 }
213
Brian Homerding3ecabd72018-08-23 15:05:22 +0000214 if (WritesMemory) {
215 if (!ReadsMemory)
216 return MAK_WriteOnly;
217 else
218 return MAK_MayWrite;
219 }
220
Chandler Carruth7542d372015-09-21 17:39:41 +0000221 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
222}
223
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000224MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
225 AAResults &AAR) {
226 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
227}
228
Chandler Carrutha632fb92015-09-13 06:57:25 +0000229/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000230template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000231static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000232 // Check if any of the functions in the SCC read or write memory. If they
233 // write memory then they can't be marked readnone or readonly.
234 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000235 bool WritesMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000236 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000237 // Call the callable parameter to look up AA results for this function.
238 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000239
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000240 // Non-exact function definitions may not be selected at link time, and an
241 // alternative version that writes to memory may be selected. See the
242 // comment on GlobalValue::isDefinitionExact for more details.
243 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
244 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000245 case MAK_MayWrite:
246 return false;
247 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000248 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000249 break;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000250 case MAK_WriteOnly:
251 WritesMemory = true;
252 break;
Chandler Carruth7542d372015-09-21 17:39:41 +0000253 case MAK_ReadNone:
254 // Nothing to do!
255 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000256 }
257 }
258
259 // Success! Functions in this SCC do not access memory, or only read memory.
260 // Give them the appropriate attribute.
261 bool MadeChange = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000262
263 assert(!(ReadsMemory && WritesMemory) &&
264 "Function marked read-only and write-only");
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000265 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000266 if (F->doesNotAccessMemory())
267 // Already perfect!
268 continue;
269
270 if (F->onlyReadsMemory() && ReadsMemory)
271 // No change.
272 continue;
273
Brian Homerding3ecabd72018-08-23 15:05:22 +0000274 if (F->doesNotReadMemory() && WritesMemory)
275 continue;
276
Duncan Sands44c8cd92008-12-31 16:14:43 +0000277 MadeChange = true;
278
279 // Clear out any existing attributes.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000280 F->removeFnAttr(Attribute::ReadOnly);
281 F->removeFnAttr(Attribute::ReadNone);
Brian Homerding3ecabd72018-08-23 15:05:22 +0000282 F->removeFnAttr(Attribute::WriteOnly);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000283
284 // Add in the new attribute.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000285 if (WritesMemory && !ReadsMemory)
286 F->addFnAttr(Attribute::WriteOnly);
287 else
288 F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000289
Brian Homerding3ecabd72018-08-23 15:05:22 +0000290 if (WritesMemory && !ReadsMemory)
291 ++NumWriteOnly;
292 else if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000293 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000294 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000295 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000296 }
297
298 return MadeChange;
299}
300
Nick Lewycky4c378a42011-12-28 23:24:21 +0000301namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000302
Chandler Carrutha632fb92015-09-13 06:57:25 +0000303/// For a given pointer Argument, this retains a list of Arguments of functions
304/// in the same SCC that the pointer data flows into. We use this to build an
305/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000306struct ArgumentGraphNode {
307 Argument *Definition;
308 SmallVector<ArgumentGraphNode *, 4> Uses;
309};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000310
Chandler Carruth63559d72015-09-13 06:47:20 +0000311class ArgumentGraph {
312 // We store pointers to ArgumentGraphNode objects, so it's important that
313 // that they not move around upon insert.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000314 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000315
Chandler Carruth63559d72015-09-13 06:47:20 +0000316 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000317
Chandler Carruth63559d72015-09-13 06:47:20 +0000318 // There is no root node for the argument graph, in fact:
319 // void f(int *x, int *y) { if (...) f(x, y); }
320 // is an example where the graph is disconnected. The SCCIterator requires a
321 // single entry point, so we maintain a fake ("synthetic") root node that
322 // uses every node. Because the graph is directed and nothing points into
323 // the root, it will not participate in any SCCs (except for its own).
324 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000325
Chandler Carruth63559d72015-09-13 06:47:20 +0000326public:
327 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000328
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000329 using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000330
Chandler Carruth63559d72015-09-13 06:47:20 +0000331 iterator begin() { return SyntheticRoot.Uses.begin(); }
332 iterator end() { return SyntheticRoot.Uses.end(); }
333 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000334
Chandler Carruth63559d72015-09-13 06:47:20 +0000335 ArgumentGraphNode *operator[](Argument *A) {
336 ArgumentGraphNode &Node = ArgumentMap[A];
337 Node.Definition = A;
338 SyntheticRoot.Uses.push_back(&Node);
339 return &Node;
340 }
341};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000342
Chandler Carrutha632fb92015-09-13 06:57:25 +0000343/// This tracker checks whether callees are in the SCC, and if so it does not
344/// consider that a capture, instead adding it to the "Uses" list and
345/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000346struct ArgumentUsesTracker : public CaptureTracker {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000347 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000348
Chandler Carruth63559d72015-09-13 06:47:20 +0000349 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000350
Chandler Carruth63559d72015-09-13 06:47:20 +0000351 bool captured(const Use *U) override {
352 CallSite CS(U->getUser());
353 if (!CS.getInstruction()) {
354 Captured = true;
355 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000356 }
357
Chandler Carruth63559d72015-09-13 06:47:20 +0000358 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000359 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000360 Captured = true;
361 return true;
362 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000363
Sanjoy Das98bfe262015-11-05 03:04:40 +0000364 // Note: the callee and the two successor blocks *follow* the argument
365 // operands. This means there is no need to adjust UseIndex to account for
366 // these.
367
368 unsigned UseIndex =
369 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
370
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000371 assert(UseIndex < CS.data_operands_size() &&
372 "Indirect function calls should have been filtered above!");
373
374 if (UseIndex >= CS.getNumArgOperands()) {
375 // Data operand, but not a argument operand -- must be a bundle operand
376 assert(CS.hasOperandBundles() && "Must be!");
377
378 // CaptureTracking told us that we're being captured by an operand bundle
379 // use. In this case it does not matter if the callee is within our SCC
380 // or not -- we've been captured in some unknown way, and we have to be
381 // conservative.
382 Captured = true;
383 return true;
384 }
385
Sanjoy Das98bfe262015-11-05 03:04:40 +0000386 if (UseIndex >= F->arg_size()) {
387 assert(F->isVarArg() && "More params than args in non-varargs call");
388 Captured = true;
389 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000390 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000391
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000392 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000393 return false;
394 }
395
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000396 // True only if certainly captured (used outside our SCC).
397 bool Captured = false;
398
399 // Uses within our SCC.
400 SmallVector<Argument *, 4> Uses;
Chandler Carruth63559d72015-09-13 06:47:20 +0000401
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000402 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000403};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000404
405} // end anonymous namespace
Nick Lewycky4c378a42011-12-28 23:24:21 +0000406
407namespace llvm {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000408
Chandler Carruth63559d72015-09-13 06:47:20 +0000409template <> struct GraphTraits<ArgumentGraphNode *> {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000410 using NodeRef = ArgumentGraphNode *;
411 using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000412
Tim Shen48f814e2016-08-31 16:48:13 +0000413 static NodeRef getEntryNode(NodeRef A) { return A; }
414 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
415 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000416};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000417
Chandler Carruth63559d72015-09-13 06:47:20 +0000418template <>
419struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000420 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000421
Chandler Carruth63559d72015-09-13 06:47:20 +0000422 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
423 return AG->begin();
424 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000425
Chandler Carruth63559d72015-09-13 06:47:20 +0000426 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
427};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000428
429} // end namespace llvm
Nick Lewycky4c378a42011-12-28 23:24:21 +0000430
Chandler Carrutha632fb92015-09-13 06:57:25 +0000431/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000432static Attribute::AttrKind
433determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000434 const SmallPtrSet<Argument *, 8> &SCCNodes) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000435 SmallVector<Use *, 32> Worklist;
Florian Hahna1cc8482018-06-12 11:16:56 +0000436 SmallPtrSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000437
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000438 // inalloca arguments are always clobbered by the call.
439 if (A->hasInAllocaAttr())
440 return Attribute::None;
441
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000442 bool IsRead = false;
443 // We don't need to track IsWritten. If A is written to, return immediately.
444
Chandler Carruthcdf47882014-03-09 03:16:01 +0000445 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000446 Visited.insert(&U);
447 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000448 }
449
450 while (!Worklist.empty()) {
451 Use *U = Worklist.pop_back_val();
452 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000453
454 switch (I->getOpcode()) {
455 case Instruction::BitCast:
456 case Instruction::GetElementPtr:
457 case Instruction::PHI:
458 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000459 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000460 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000461 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000462 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000463 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000464 break;
465
466 case Instruction::Call:
467 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000468 bool Captures = true;
469
470 if (I->getType()->isVoidTy())
471 Captures = false;
472
473 auto AddUsersToWorklistIfCapturing = [&] {
474 if (Captures)
475 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000476 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000477 Worklist.push_back(&UU);
478 };
479
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000480 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000481 if (CS.doesNotAccessMemory()) {
482 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000483 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000484 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000485
486 Function *F = CS.getCalledFunction();
487 if (!F) {
488 if (CS.onlyReadsMemory()) {
489 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000490 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000491 continue;
492 }
493 return Attribute::None;
494 }
495
Sanjoy Das436e2392015-11-07 01:55:53 +0000496 // Note: the callee and the two successor blocks *follow* the argument
497 // operands. This means there is no need to adjust UseIndex to account
498 // for these.
499
500 unsigned UseIndex = std::distance(CS.arg_begin(), U);
501
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000502 // U cannot be the callee operand use: since we're exploring the
503 // transitive uses of an Argument, having such a use be a callee would
504 // imply the CallSite is an indirect call or invoke; and we'd take the
505 // early exit above.
506 assert(UseIndex < CS.data_operands_size() &&
507 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000508
509 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
510
511 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000512 assert(F->isVarArg() && "More params than args in non-varargs call");
513 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000514 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000515
Tilmann Scheller925b1932015-11-20 19:17:10 +0000516 Captures &= !CS.doesNotCapture(UseIndex);
517
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000518 // Since the optimizer (by design) cannot see the data flow corresponding
519 // to a operand bundle use, these cannot participate in the optimistic SCC
520 // analysis. Instead, we model the operand bundle uses as arguments in
521 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000522 if (IsOperandBundleUse ||
523 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000524
525 // The accessors used on CallSite here do the right thing for calls and
526 // invokes with operand bundles.
527
Sanjoy Das436e2392015-11-07 01:55:53 +0000528 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
529 return Attribute::None;
530 if (!CS.doesNotAccessMemory(UseIndex))
531 IsRead = true;
532 }
533
Nick Lewycky59633cb2014-05-30 02:31:27 +0000534 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000535 break;
536 }
537
538 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000539 // A volatile load has side effects beyond what readonly can be relied
540 // upon.
541 if (cast<LoadInst>(I)->isVolatile())
542 return Attribute::None;
543
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000544 IsRead = true;
545 break;
546
547 case Instruction::ICmp:
548 case Instruction::Ret:
549 break;
550
551 default:
552 return Attribute::None;
553 }
554 }
555
556 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
557}
558
David Majnemer5246e0b2016-07-19 18:50:26 +0000559/// Deduce returned attributes for the SCC.
560static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
561 bool Changed = false;
562
David Majnemer5246e0b2016-07-19 18:50:26 +0000563 // Check each function in turn, determining if an argument is always returned.
564 for (Function *F : SCCNodes) {
565 // We can infer and propagate function attributes only when we know that the
566 // definition we'll get at link time is *exactly* the definition we see now.
567 // For more details, see GlobalValue::mayBeDerefined.
568 if (!F->hasExactDefinition())
569 continue;
570
571 if (F->getReturnType()->isVoidTy())
572 continue;
573
David Majnemerc83044d2016-09-12 16:04:59 +0000574 // There is nothing to do if an argument is already marked as 'returned'.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000575 if (llvm::any_of(F->args(),
576 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
David Majnemerc83044d2016-09-12 16:04:59 +0000577 continue;
578
David Majnemer5246e0b2016-07-19 18:50:26 +0000579 auto FindRetArg = [&]() -> Value * {
580 Value *RetArg = nullptr;
581 for (BasicBlock &BB : *F)
582 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
583 // Note that stripPointerCasts should look through functions with
584 // returned arguments.
585 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
586 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
587 return nullptr;
588
589 if (!RetArg)
590 RetArg = RetVal;
591 else if (RetArg != RetVal)
592 return nullptr;
593 }
594
595 return RetArg;
596 };
597
598 if (Value *RetArg = FindRetArg()) {
599 auto *A = cast<Argument>(RetArg);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000600 A->addAttr(Attribute::Returned);
David Majnemer5246e0b2016-07-19 18:50:26 +0000601 ++NumReturned;
602 Changed = true;
603 }
604 }
605
606 return Changed;
607}
608
Sanjay Patel4f742162017-02-13 23:10:51 +0000609/// If a callsite has arguments that are also arguments to the parent function,
610/// try to propagate attributes from the callsite's arguments to the parent's
611/// arguments. This may be important because inlining can cause information loss
612/// when attribute knowledge disappears with the inlined call.
613static bool addArgumentAttrsFromCallsites(Function &F) {
614 if (!EnableNonnullArgPropagation)
615 return false;
616
617 bool Changed = false;
618
619 // For an argument attribute to transfer from a callsite to the parent, the
620 // call must be guaranteed to execute every time the parent is called.
621 // Conservatively, just check for calls in the entry block that are guaranteed
622 // to execute.
623 // TODO: This could be enhanced by testing if the callsite post-dominates the
624 // entry block or by doing simple forward walks or backward walks to the
625 // callsite.
626 BasicBlock &Entry = F.getEntryBlock();
627 for (Instruction &I : Entry) {
628 if (auto CS = CallSite(&I)) {
629 if (auto *CalledFunc = CS.getCalledFunction()) {
630 for (auto &CSArg : CalledFunc->args()) {
631 if (!CSArg.hasNonNullAttr())
632 continue;
633
634 // If the non-null callsite argument operand is an argument to 'F'
635 // (the caller) and the call is guaranteed to execute, then the value
636 // must be non-null throughout 'F'.
637 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
638 if (FArg && !FArg->hasNonNullAttr()) {
639 FArg->addAttr(Attribute::NonNull);
640 Changed = true;
641 }
642 }
643 }
644 }
645 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
646 break;
647 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000648
Sanjay Patel4f742162017-02-13 23:10:51 +0000649 return Changed;
650}
651
Chandler Carrutha632fb92015-09-13 06:57:25 +0000652/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000653static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000654 bool Changed = false;
655
Nick Lewycky4c378a42011-12-28 23:24:21 +0000656 ArgumentGraph AG;
657
Duncan Sands44c8cd92008-12-31 16:14:43 +0000658 // Check each function in turn, determining which pointer arguments are not
659 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000660 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000661 // We can infer and propagate function attributes only when we know that the
662 // definition we'll get at link time is *exactly* the definition we see now.
663 // For more details, see GlobalValue::mayBeDerefined.
664 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000665 continue;
666
Sanjay Patel4f742162017-02-13 23:10:51 +0000667 Changed |= addArgumentAttrsFromCallsites(*F);
668
Nick Lewycky4c378a42011-12-28 23:24:21 +0000669 // Functions that are readonly (or readnone) and nounwind and don't return
670 // a value can't capture arguments. Don't analyze them.
671 if (F->onlyReadsMemory() && F->doesNotThrow() &&
672 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000673 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
674 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000675 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000676 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000677 ++NumNoCapture;
678 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000679 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000680 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000681 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000682 }
683
Chandler Carruth63559d72015-09-13 06:47:20 +0000684 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
685 ++A) {
686 if (!A->getType()->isPointerTy())
687 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000688 bool HasNonLocalUses = false;
689 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000690 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000691 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000692 if (!Tracker.Captured) {
693 if (Tracker.Uses.empty()) {
694 // If it's trivially not captured, mark it nocapture now.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000695 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000696 ++NumNoCapture;
697 Changed = true;
698 } else {
699 // If it's not trivially captured and not trivially not captured,
700 // then it must be calling into another function in our SCC. Save
701 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000702 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000703 for (Argument *Use : Tracker.Uses) {
704 Node->Uses.push_back(AG[Use]);
705 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000706 HasNonLocalUses = true;
707 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000708 }
709 }
710 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
711 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000712 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
713 // Can we determine that it's readonly/readnone without doing an SCC?
714 // Note that we don't allow any calls at all here, or else our result
715 // will be dependent on the iteration order through the functions in the
716 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000717 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000718 Self.insert(&*A);
719 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000720 if (R != Attribute::None) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000721 A->addAttr(R);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000722 Changed = true;
723 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
724 }
725 }
726 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000727 }
728
729 // The graph we've collected is partial because we stopped scanning for
730 // argument uses once we solved the argument trivially. These partial nodes
731 // show up as ArgumentGraphNode objects with an empty Uses list, and for
732 // these nodes the final decision about whether they capture has already been
733 // made. If the definition doesn't have a 'nocapture' attribute by now, it
734 // captures.
735
Chandler Carruth63559d72015-09-13 06:47:20 +0000736 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000737 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000738 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000739 if (!ArgumentSCC[0]->Definition)
740 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000741
742 // eg. "void f(int* x) { if (...) f(x); }"
743 if (ArgumentSCC[0]->Uses.size() == 1 &&
744 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000745 Argument *A = ArgumentSCC[0]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000746 A->addAttr(Attribute::NoCapture);
Nick Lewycky7e820552009-01-02 03:46:56 +0000747 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000748 Changed = true;
749 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000750 continue;
751 }
752
753 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000754 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
755 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000756 ArgumentGraphNode *Node = *I;
757 if (Node->Uses.empty()) {
758 if (!Node->Definition->hasNoCaptureAttr())
759 SCCCaptured = true;
760 }
761 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000762 if (SCCCaptured)
763 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000764
Chandler Carruth63559d72015-09-13 06:47:20 +0000765 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000766 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
767 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000768 for (ArgumentGraphNode *I : ArgumentSCC) {
769 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000770 }
771
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000772 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
773 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000774 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000775 for (ArgumentGraphNode *Use : N->Uses) {
776 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000777 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
778 continue;
779 SCCCaptured = true;
780 break;
781 }
782 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000783 if (SCCCaptured)
784 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000785
Nick Lewyckyf740db32012-01-05 22:21:45 +0000786 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000787 Argument *A = ArgumentSCC[i]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000788 A->addAttr(Attribute::NoCapture);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000789 ++NumNoCapture;
790 Changed = true;
791 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000792
793 // We also want to compute readonly/readnone. With a small number of false
794 // negatives, we can assume that any pointer which is captured isn't going
795 // to be provably readonly or readnone, since by definition we can't
796 // analyze all uses of a captured pointer.
797 //
798 // The false negatives happen when the pointer is captured by a function
799 // that promises readonly/readnone behaviour on the pointer, then the
800 // pointer's lifetime ends before anything that writes to arbitrary memory.
801 // Also, a readonly/readnone pointer may be returned, but returning a
802 // pointer is capturing it.
803
804 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
805 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
806 Argument *A = ArgumentSCC[i]->Definition;
807 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
808 if (K == Attribute::ReadNone)
809 continue;
810 if (K == Attribute::ReadOnly) {
811 ReadAttr = Attribute::ReadOnly;
812 continue;
813 }
814 ReadAttr = K;
815 break;
816 }
817
818 if (ReadAttr != Attribute::None) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000819 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
820 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000821 // Clear out existing readonly/readnone attributes
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000822 A->removeAttr(Attribute::ReadOnly);
823 A->removeAttr(Attribute::ReadNone);
824 A->addAttr(ReadAttr);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000825 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
826 Changed = true;
827 }
828 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000829 }
830
831 return Changed;
832}
833
Chandler Carrutha632fb92015-09-13 06:57:25 +0000834/// Tests whether a function is "malloc-like".
835///
836/// A function is "malloc-like" if it returns either null or a pointer that
837/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000838static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000839 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000840 for (BasicBlock &BB : *F)
841 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000842 FlowsToReturn.insert(Ret->getReturnValue());
843
844 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000845 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000846
847 if (Constant *C = dyn_cast<Constant>(RetVal)) {
848 if (!C->isNullValue() && !isa<UndefValue>(C))
849 return false;
850
851 continue;
852 }
853
854 if (isa<Argument>(RetVal))
855 return false;
856
857 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
858 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000859 // Extend the analysis by looking upwards.
860 case Instruction::BitCast:
861 case Instruction::GetElementPtr:
862 case Instruction::AddrSpaceCast:
863 FlowsToReturn.insert(RVI->getOperand(0));
864 continue;
865 case Instruction::Select: {
866 SelectInst *SI = cast<SelectInst>(RVI);
867 FlowsToReturn.insert(SI->getTrueValue());
868 FlowsToReturn.insert(SI->getFalseValue());
869 continue;
870 }
871 case Instruction::PHI: {
872 PHINode *PN = cast<PHINode>(RVI);
873 for (Value *IncValue : PN->incoming_values())
874 FlowsToReturn.insert(IncValue);
875 continue;
876 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000877
Chandler Carruth63559d72015-09-13 06:47:20 +0000878 // Check whether the pointer came from an allocation.
879 case Instruction::Alloca:
880 break;
881 case Instruction::Call:
882 case Instruction::Invoke: {
883 CallSite CS(RVI);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000884 if (CS.hasRetAttr(Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000885 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000886 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
887 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000888 LLVM_FALLTHROUGH;
889 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000890 default:
891 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000892 }
893
Dan Gohman94e61762009-11-19 21:57:48 +0000894 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000895 return false;
896 }
897
898 return true;
899}
900
Chandler Carrutha632fb92015-09-13 06:57:25 +0000901/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000902static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000903 // Check each function in turn, determining which functions return noalias
904 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000905 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000906 // Already noalias.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000907 if (F->returnDoesNotAlias())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000908 continue;
909
Sanjoy Das5ce32722016-04-08 00:48:30 +0000910 // We can infer and propagate function attributes only when we know that the
911 // definition we'll get at link time is *exactly* the definition we see now.
912 // For more details, see GlobalValue::mayBeDerefined.
913 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000914 return false;
915
Chandler Carruth63559d72015-09-13 06:47:20 +0000916 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000917 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000918 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000919 continue;
920
Chandler Carruth3824f852015-09-13 08:23:27 +0000921 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000922 return false;
923 }
924
925 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000926 for (Function *F : SCCNodes) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000927 if (F->returnDoesNotAlias() ||
Reid Kleckner6652a522017-04-28 18:37:16 +0000928 !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000929 continue;
930
Reid Klecknera0b45f42017-05-03 18:17:31 +0000931 F->setReturnDoesNotAlias();
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000932 ++NumNoAlias;
933 MadeChange = true;
934 }
935
936 return MadeChange;
937}
938
Chandler Carrutha632fb92015-09-13 06:57:25 +0000939/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000940///
941/// Requires that the function returns a pointer.
942///
943/// Returns true if it believes the function will not return a null, and sets
944/// \p Speculative based on whether the returned conclusion is a speculative
945/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000946static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000947 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000948 assert(F->getReturnType()->isPointerTy() &&
949 "nonnull only meaningful on pointer types");
950 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000951
Philip Reamesa88caea2015-08-31 19:44:38 +0000952 SmallSetVector<Value *, 8> FlowsToReturn;
953 for (BasicBlock &BB : *F)
954 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
955 FlowsToReturn.insert(Ret->getReturnValue());
956
Nuno Lopes404f1062017-09-09 18:23:11 +0000957 auto &DL = F->getParent()->getDataLayout();
958
Philip Reamesa88caea2015-08-31 19:44:38 +0000959 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
960 Value *RetVal = FlowsToReturn[i];
961
962 // If this value is locally known to be non-null, we're good
Nuno Lopes404f1062017-09-09 18:23:11 +0000963 if (isKnownNonZero(RetVal, DL))
Philip Reamesa88caea2015-08-31 19:44:38 +0000964 continue;
965
966 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000967 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000968 Instruction *RVI = dyn_cast<Instruction>(RetVal);
969 if (!RVI)
970 return false;
971 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000972 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000973 case Instruction::BitCast:
974 case Instruction::GetElementPtr:
975 case Instruction::AddrSpaceCast:
976 FlowsToReturn.insert(RVI->getOperand(0));
977 continue;
978 case Instruction::Select: {
979 SelectInst *SI = cast<SelectInst>(RVI);
980 FlowsToReturn.insert(SI->getTrueValue());
981 FlowsToReturn.insert(SI->getFalseValue());
982 continue;
983 }
984 case Instruction::PHI: {
985 PHINode *PN = cast<PHINode>(RVI);
986 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
987 FlowsToReturn.insert(PN->getIncomingValue(i));
988 continue;
989 }
990 case Instruction::Call:
991 case Instruction::Invoke: {
992 CallSite CS(RVI);
993 Function *Callee = CS.getCalledFunction();
994 // A call to a node within the SCC is assumed to return null until
995 // proven otherwise
996 if (Callee && SCCNodes.count(Callee)) {
997 Speculative = true;
998 continue;
999 }
1000 return false;
1001 }
1002 default:
Chandler Carruth63559d72015-09-13 06:47:20 +00001003 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +00001004 };
1005 llvm_unreachable("should have either continued or returned");
1006 }
1007
1008 return true;
1009}
1010
Chandler Carrutha632fb92015-09-13 06:57:25 +00001011/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +00001012static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001013 // Speculative that all functions in the SCC return only nonnull
1014 // pointers. We may refute this as we analyze functions.
1015 bool SCCReturnsNonNull = true;
1016
1017 bool MadeChange = false;
1018
1019 // Check each function in turn, determining which functions return nonnull
1020 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001021 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001022 // Already nonnull.
Reid Klecknerb5180542017-03-21 16:57:19 +00001023 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001024 Attribute::NonNull))
1025 continue;
1026
Sanjoy Das5ce32722016-04-08 00:48:30 +00001027 // We can infer and propagate function attributes only when we know that the
1028 // definition we'll get at link time is *exactly* the definition we see now.
1029 // For more details, see GlobalValue::mayBeDerefined.
1030 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +00001031 return false;
1032
Chandler Carruth63559d72015-09-13 06:47:20 +00001033 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +00001034 // pointer types.
1035 if (!F->getReturnType()->isPointerTy())
1036 continue;
1037
1038 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +00001039 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001040 if (!Speculative) {
1041 // Mark the function eagerly since we may discover a function
1042 // which prevents us from speculating about the entire SCC
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001043 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1044 << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001045 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001046 ++NumNonNullReturn;
1047 MadeChange = true;
1048 }
1049 continue;
1050 }
1051 // At least one function returns something which could be null, can't
1052 // speculate any more.
1053 SCCReturnsNonNull = false;
1054 }
1055
1056 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001057 for (Function *F : SCCNodes) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001058 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001059 Attribute::NonNull) ||
1060 !F->getReturnType()->isPointerTy())
1061 continue;
1062
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001063 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001064 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001065 ++NumNonNullReturn;
1066 MadeChange = true;
1067 }
1068 }
1069
1070 return MadeChange;
1071}
1072
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001073namespace {
1074
1075/// Collects a set of attribute inference requests and performs them all in one
1076/// go on a single SCC Node. Inference involves scanning function bodies
1077/// looking for instructions that violate attribute assumptions.
1078/// As soon as all the bodies are fine we are free to set the attribute.
1079/// Customization of inference for individual attributes is performed by
1080/// providing a handful of predicates for each attribute.
1081class AttributeInferer {
1082public:
1083 /// Describes a request for inference of a single attribute.
1084 struct InferenceDescriptor {
1085
1086 /// Returns true if this function does not have to be handled.
1087 /// General intent for this predicate is to provide an optimization
1088 /// for functions that do not need this attribute inference at all
1089 /// (say, for functions that already have the attribute).
1090 std::function<bool(const Function &)> SkipFunction;
1091
1092 /// Returns true if this instruction violates attribute assumptions.
1093 std::function<bool(Instruction &)> InstrBreaksAttribute;
1094
1095 /// Sets the inferred attribute for this function.
1096 std::function<void(Function &)> SetAttribute;
1097
1098 /// Attribute we derive.
1099 Attribute::AttrKind AKind;
1100
1101 /// If true, only "exact" definitions can be used to infer this attribute.
1102 /// See GlobalValue::isDefinitionExact.
1103 bool RequiresExactDefinition;
1104
1105 InferenceDescriptor(Attribute::AttrKind AK,
1106 std::function<bool(const Function &)> SkipFunc,
1107 std::function<bool(Instruction &)> InstrScan,
1108 std::function<void(Function &)> SetAttr,
1109 bool ReqExactDef)
1110 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1111 SetAttribute(SetAttr), AKind(AK),
1112 RequiresExactDefinition(ReqExactDef) {}
1113 };
1114
1115private:
1116 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1117
1118public:
1119 void registerAttrInference(InferenceDescriptor AttrInference) {
1120 InferenceDescriptors.push_back(AttrInference);
1121 }
1122
1123 bool run(const SCCNodeSet &SCCNodes);
1124};
1125
1126/// Perform all the requested attribute inference actions according to the
1127/// attribute predicates stored before.
1128bool AttributeInferer::run(const SCCNodeSet &SCCNodes) {
1129 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1130 // Go through all the functions in SCC and check corresponding attribute
1131 // assumptions for each of them. Attributes that are invalid for this SCC
1132 // will be removed from InferInSCC.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001133 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001134
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001135 // No attributes whose assumptions are still valid - done.
1136 if (InferInSCC.empty())
1137 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001138
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001139 // Check if our attributes ever need scanning/can be scanned.
1140 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1141 if (ID.SkipFunction(*F))
Justin Lebar9d943972016-03-14 20:18:54 +00001142 return false;
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001143
1144 // Remove from further inference (invalidate) when visiting a function
1145 // that has no instructions to scan/has an unsuitable definition.
1146 return F->isDeclaration() ||
1147 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1148 });
1149
1150 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1151 // set up the F instructions scan to verify assumptions of the attribute.
1152 SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1153 llvm::copy_if(
1154 InferInSCC, std::back_inserter(InferInThisFunc),
1155 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1156
1157 if (InferInThisFunc.empty())
1158 continue;
1159
1160 // Start instruction scan.
1161 for (Instruction &I : instructions(*F)) {
1162 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1163 if (!ID.InstrBreaksAttribute(I))
1164 return false;
1165 // Remove attribute from further inference on any other functions
1166 // because attribute assumptions have just been violated.
1167 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1168 return D.AKind == ID.AKind;
1169 });
1170 // Remove attribute from the rest of current instruction scan.
1171 return true;
1172 });
1173
1174 if (InferInThisFunc.empty())
1175 break;
Justin Lebar9d943972016-03-14 20:18:54 +00001176 }
1177 }
1178
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001179 if (InferInSCC.empty())
1180 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001181
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001182 bool Changed = false;
1183 for (Function *F : SCCNodes)
1184 // At this point InferInSCC contains only functions that were either:
1185 // - explicitly skipped from scan/inference, or
1186 // - verified to have no instructions that break attribute assumptions.
1187 // Hence we just go and force the attribute for all non-skipped functions.
1188 for (auto &ID : InferInSCC) {
1189 if (ID.SkipFunction(*F))
1190 continue;
1191 Changed = true;
1192 ID.SetAttribute(*F);
1193 }
1194 return Changed;
1195}
Justin Lebar9d943972016-03-14 20:18:54 +00001196
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001197} // end anonymous namespace
1198
1199/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1200static bool InstrBreaksNonConvergent(Instruction &I,
1201 const SCCNodeSet &SCCNodes) {
1202 const CallSite CS(&I);
1203 // Breaks non-convergent assumption if CS is a convergent call to a function
1204 // not in the SCC.
1205 return CS && CS.isConvergent() && SCCNodes.count(CS.getCalledFunction()) == 0;
1206}
1207
1208/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1209static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1210 if (!I.mayThrow())
1211 return false;
1212 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1213 if (Function *Callee = CI->getCalledFunction()) {
1214 // I is a may-throw call to a function inside our SCC. This doesn't
1215 // invalidate our current working assumption that the SCC is no-throw; we
1216 // just have to scan that other function.
1217 if (SCCNodes.count(Callee) > 0)
1218 return false;
1219 }
Chandler Carruth3937bc72016-02-12 09:47:49 +00001220 }
Justin Lebar260854b2016-02-09 23:03:22 +00001221 return true;
1222}
1223
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001224/// Infer attributes from all functions in the SCC by scanning every
1225/// instruction for compliance to the attribute assumptions. Currently it
1226/// does:
1227/// - removal of Convergent attribute
1228/// - addition of NoUnwind attribute
1229///
1230/// Returns true if any changes to function attributes were made.
1231static bool inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes) {
1232
1233 AttributeInferer AI;
1234
1235 // Request to remove the convergent attribute from all functions in the SCC
1236 // if every callsite within the SCC is not convergent (except for calls
1237 // to functions within the SCC).
1238 // Note: Removal of the attr from the callsites will happen in
1239 // InstCombineCalls separately.
1240 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1241 Attribute::Convergent,
1242 // Skip non-convergent functions.
1243 [](const Function &F) { return !F.isConvergent(); },
1244 // Instructions that break non-convergent assumption.
1245 [SCCNodes](Instruction &I) {
1246 return InstrBreaksNonConvergent(I, SCCNodes);
1247 },
1248 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001249 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1250 << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001251 F.setNotConvergent();
1252 },
1253 /* RequiresExactDefinition= */ false});
1254
1255 if (!DisableNoUnwindInference)
1256 // Request to infer nounwind attribute for all the functions in the SCC if
1257 // every callsite within the SCC is not throwing (except for calls to
1258 // functions within the SCC). Note that nounwind attribute suffers from
1259 // derefinement - results may change depending on how functions are
1260 // optimized. Thus it can be inferred only from exact definitions.
1261 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1262 Attribute::NoUnwind,
1263 // Skip non-throwing functions.
1264 [](const Function &F) { return F.doesNotThrow(); },
1265 // Instructions that break non-throwing assumption.
1266 [SCCNodes](Instruction &I) {
1267 return InstrBreaksNonThrowing(I, SCCNodes);
1268 },
1269 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001270 LLVM_DEBUG(dbgs()
1271 << "Adding nounwind attr to fn " << F.getName() << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001272 F.setDoesNotThrow();
1273 ++NumNoUnwind;
1274 },
1275 /* RequiresExactDefinition= */ true});
1276
1277 // Perform all the requested attribute inference actions.
1278 return AI.run(SCCNodes);
1279}
1280
James Molloy7e9bdd52015-11-12 10:55:20 +00001281static bool setDoesNotRecurse(Function &F) {
1282 if (F.doesNotRecurse())
1283 return false;
1284 F.setDoesNotRecurse();
1285 ++NumNoRecurse;
1286 return true;
1287}
1288
Chandler Carruth632d2082016-02-13 08:47:51 +00001289static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001290 // Try and identify functions that do not recurse.
1291
1292 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001293 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001294 return false;
1295
Chandler Carruth632d2082016-02-13 08:47:51 +00001296 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001297 if (!F || F->isDeclaration() || F->doesNotRecurse())
1298 return false;
1299
1300 // If all of the calls in F are identifiable and are to norecurse functions, F
1301 // is norecurse. This check also detects self-recursion as F is not currently
1302 // marked norecurse, so any called from F to F will not be marked norecurse.
Chandler Carruth632d2082016-02-13 08:47:51 +00001303 for (Instruction &I : instructions(*F))
1304 if (auto CS = CallSite(&I)) {
1305 Function *Callee = CS.getCalledFunction();
1306 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1307 // Function calls a potentially recursive function.
1308 return false;
1309 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001310
Chandler Carruth632d2082016-02-13 08:47:51 +00001311 // Every call was to a non-recursive function other than this function, and
1312 // we have no indirect recursion as the SCC size is one. This function cannot
1313 // recurse.
1314 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001315}
1316
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001317template <typename AARGetterT>
1318static bool deriveAttrsInPostOrder(SCCNodeSet &SCCNodes, AARGetterT &&AARGetter,
1319 bool HasUnknownCall) {
1320 bool Changed = false;
1321
1322 // Bail if the SCC only contains optnone functions.
1323 if (SCCNodes.empty())
1324 return Changed;
1325
1326 Changed |= addArgumentReturnedAttrs(SCCNodes);
1327 Changed |= addReadAttrs(SCCNodes, AARGetter);
1328 Changed |= addArgumentAttrs(SCCNodes);
1329
1330 // If we have no external nodes participating in the SCC, we can deduce some
1331 // more precise attributes as well.
1332 if (!HasUnknownCall) {
1333 Changed |= addNoAliasAttrs(SCCNodes);
1334 Changed |= addNonNullAttrs(SCCNodes);
1335 Changed |= inferAttrsFromFunctionBodies(SCCNodes);
1336 Changed |= addNoRecurseAttrs(SCCNodes);
1337 }
1338
1339 return Changed;
1340}
1341
Chandler Carruthb47f8012016-03-11 11:05:24 +00001342PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001343 CGSCCAnalysisManager &AM,
1344 LazyCallGraph &CG,
1345 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001346 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001347 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001348
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001349 // We pass a lambda into functions to wire them up to the analysis manager
1350 // for getting function analyses.
1351 auto AARGetter = [&](Function &F) -> AAResults & {
1352 return FAM.getResult<AAManager>(F);
1353 };
1354
1355 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1356 // any external or opt-none nodes that will prevent us from optimizing any
1357 // part of the SCC.
1358 SCCNodeSet SCCNodes;
1359 bool HasUnknownCall = false;
1360 for (LazyCallGraph::Node &N : C) {
1361 Function &F = N.getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001362 if (F.hasFnAttribute(Attribute::OptimizeNone) ||
1363 F.hasFnAttribute(Attribute::Naked)) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001364 // Treat any function we're trying not to optimize as if it were an
1365 // indirect call and omit it from the node set used below.
1366 HasUnknownCall = true;
1367 continue;
1368 }
1369 // Track whether any functions in this SCC have an unknown call edge.
1370 // Note: if this is ever a performance hit, we can common it with
1371 // subsequent routines which also do scans over the instructions of the
1372 // function.
1373 if (!HasUnknownCall)
1374 for (Instruction &I : instructions(F))
1375 if (auto CS = CallSite(&I))
1376 if (!CS.getCalledFunction()) {
1377 HasUnknownCall = true;
1378 break;
1379 }
1380
1381 SCCNodes.insert(&F);
1382 }
1383
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001384 if (deriveAttrsInPostOrder(SCCNodes, AARGetter, HasUnknownCall))
1385 return PreservedAnalyses::none();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001386
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001387 return PreservedAnalyses::all();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001388}
1389
1390namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001391
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001392struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001393 // Pass identification, replacement for typeid
1394 static char ID;
1395
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001396 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001397 initializePostOrderFunctionAttrsLegacyPassPass(
1398 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001399 }
1400
1401 bool runOnSCC(CallGraphSCC &SCC) override;
1402
1403 void getAnalysisUsage(AnalysisUsage &AU) const override {
1404 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001405 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001406 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001407 CallGraphSCCPass::getAnalysisUsage(AU);
1408 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001409};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001410
1411} // end anonymous namespace
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001412
1413char PostOrderFunctionAttrsLegacyPass::ID = 0;
1414INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1415 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001416INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001417INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001418INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1419 "Deduce function attributes", false, false)
1420
Chad Rosier611b73b2016-11-07 16:28:04 +00001421Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1422 return new PostOrderFunctionAttrsLegacyPass();
1423}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001424
Sean Silva997cbea2016-07-03 03:35:03 +00001425template <typename AARGetterT>
1426static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001427
1428 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1429 // whether a given CallGraphNode is in this SCC. Also track whether there are
1430 // any external or opt-none nodes that will prevent us from optimizing any
1431 // part of the SCC.
1432 SCCNodeSet SCCNodes;
1433 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001434 for (CallGraphNode *I : SCC) {
1435 Function *F = I->getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001436 if (!F || F->hasFnAttribute(Attribute::OptimizeNone) ||
1437 F->hasFnAttribute(Attribute::Naked)) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001438 // External node or function we're trying not to optimize - we both avoid
1439 // transform them and avoid leveraging information they provide.
1440 ExternalNode = true;
1441 continue;
1442 }
1443
1444 SCCNodes.insert(F);
1445 }
1446
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001447 return deriveAttrsInPostOrder(SCCNodes, AARGetter, ExternalNode);
James Molloy7e9bdd52015-11-12 10:55:20 +00001448}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001449
Sean Silva997cbea2016-07-03 03:35:03 +00001450bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1451 if (skipSCC(SCC))
1452 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001453 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001454}
1455
Chandler Carruth1926b702016-01-08 10:55:52 +00001456namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001457
Sean Silvaf5080192016-06-12 07:48:51 +00001458struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001459 // Pass identification, replacement for typeid
1460 static char ID;
1461
Sean Silvaf5080192016-06-12 07:48:51 +00001462 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001463 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1464 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001465 }
1466
1467 bool runOnModule(Module &M) override;
1468
1469 void getAnalysisUsage(AnalysisUsage &AU) const override {
1470 AU.setPreservesCFG();
1471 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001472 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001473 }
1474};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001475
1476} // end anonymous namespace
Chandler Carruth1926b702016-01-08 10:55:52 +00001477
Sean Silvaf5080192016-06-12 07:48:51 +00001478char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001479
Sean Silvaf5080192016-06-12 07:48:51 +00001480INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001481 "Deduce function attributes in RPO", false, false)
1482INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001483INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001484 "Deduce function attributes in RPO", false, false)
1485
1486Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001487 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001488}
1489
1490static bool addNoRecurseAttrsTopDown(Function &F) {
1491 // We check the preconditions for the function prior to calling this to avoid
1492 // the cost of building up a reversible post-order list. We assert them here
1493 // to make sure none of the invariants this relies on were violated.
1494 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1495 assert(!F.doesNotRecurse() &&
1496 "This function has already been deduced as norecurs!");
1497 assert(F.hasInternalLinkage() &&
1498 "Can only do top-down deduction for internal linkage functions!");
1499
1500 // If F is internal and all of its uses are calls from a non-recursive
1501 // functions, then none of its calls could in fact recurse without going
1502 // through a function marked norecurse, and so we can mark this function too
1503 // as norecurse. Note that the uses must actually be calls -- otherwise
1504 // a pointer to this function could be returned from a norecurse function but
1505 // this function could be recursively (indirectly) called. Note that this
1506 // also detects if F is directly recursive as F is not yet marked as
1507 // a norecurse function.
1508 for (auto *U : F.users()) {
1509 auto *I = dyn_cast<Instruction>(U);
1510 if (!I)
1511 return false;
1512 CallSite CS(I);
1513 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1514 return false;
1515 }
1516 return setDoesNotRecurse(F);
1517}
1518
Sean Silvaadc79392016-06-12 05:44:51 +00001519static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001520 // We only have a post-order SCC traversal (because SCCs are inherently
1521 // discovered in post-order), so we accumulate them in a vector and then walk
1522 // it in reverse. This is simpler than using the RPO iterator infrastructure
1523 // because we need to combine SCC detection and the PO walk of the call
1524 // graph. We can also cheat egregiously because we're primarily interested in
1525 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1526 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001527 SmallVector<Function *, 16> Worklist;
1528 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1529 if (I->size() != 1)
1530 continue;
1531
1532 Function *F = I->front()->getFunction();
1533 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1534 F->hasInternalLinkage())
1535 Worklist.push_back(F);
1536 }
1537
James Molloy7e9bdd52015-11-12 10:55:20 +00001538 bool Changed = false;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001539 for (auto *F : llvm::reverse(Worklist))
Chandler Carruth1926b702016-01-08 10:55:52 +00001540 Changed |= addNoRecurseAttrsTopDown(*F);
1541
Duncan Sands44c8cd92008-12-31 16:14:43 +00001542 return Changed;
1543}
Sean Silvaadc79392016-06-12 05:44:51 +00001544
Sean Silvaf5080192016-06-12 07:48:51 +00001545bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001546 if (skipModule(M))
1547 return false;
1548
1549 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1550
1551 return deduceFunctionAttributeInRPO(M, CG);
1552}
Sean Silvaf5080192016-06-12 07:48:51 +00001553
1554PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001555ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001556 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1557
Chandler Carruth6acdca72017-01-24 12:55:57 +00001558 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001559 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001560
Sean Silvaf5080192016-06-12 07:48:51 +00001561 PreservedAnalyses PA;
1562 PA.preserve<CallGraphAnalysis>();
1563 return PA;
1564}