blob: 3a04f7a00d413b65b8ca8af08a6e246cdbb719da [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"
Christian Bruel4ead99b2018-12-05 16:48:00 +000044#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000045#include "llvm/IR/Metadata.h"
46#include "llvm/IR/PassManager.h"
47#include "llvm/IR/Type.h"
48#include "llvm/IR/Use.h"
49#include "llvm/IR/User.h"
50#include "llvm/IR/Value.h"
51#include "llvm/Pass.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000055#include "llvm/Support/Debug.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000056#include "llvm/Support/ErrorHandling.h"
Hans Wennborg043bf5b2015-08-31 21:19:18 +000057#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000058#include "llvm/Transforms/IPO.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000059#include <cassert>
60#include <iterator>
61#include <map>
62#include <vector>
63
Duncan Sands44c8cd92008-12-31 16:14:43 +000064using namespace llvm;
65
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "functionattrs"
67
Duncan Sands44c8cd92008-12-31 16:14:43 +000068STATISTIC(NumReadNone, "Number of functions marked readnone");
69STATISTIC(NumReadOnly, "Number of functions marked readonly");
Brian Homerding3ecabd72018-08-23 15:05:22 +000070STATISTIC(NumWriteOnly, "Number of functions marked writeonly");
Duncan Sands44c8cd92008-12-31 16:14:43 +000071STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
David Majnemer5246e0b2016-07-19 18:50:26 +000072STATISTIC(NumReturned, "Number of arguments marked returned");
Nick Lewyckyc2ec0722013-07-06 00:29:58 +000073STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
74STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
Nick Lewyckyfbed86a2009-03-08 06:20:47 +000075STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Philip Reamesa88caea2015-08-31 19:44:38 +000076STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
James Molloy7e9bdd52015-11-12 10:55:20 +000077STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
Fedor Sergeev6660fd02018-03-23 21:46:16 +000078STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
Duncan Sands44c8cd92008-12-31 16:14:43 +000079
Sanjay Patel4f742162017-02-13 23:10:51 +000080// FIXME: This is disabled by default to avoid exposing security vulnerabilities
81// in C/C++ code compiled by clang:
82// http://lists.llvm.org/pipermail/cfe-dev/2017-January/052066.html
83static cl::opt<bool> EnableNonnullArgPropagation(
84 "enable-nonnull-arg-prop", cl::Hidden,
85 cl::desc("Try to propagate nonnull argument attributes from callsites to "
86 "caller functions."));
87
Fedor Sergeev6660fd02018-03-23 21:46:16 +000088static cl::opt<bool> DisableNoUnwindInference(
89 "disable-nounwind-inference", cl::Hidden,
90 cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
91
Duncan Sands44c8cd92008-12-31 16:14:43 +000092namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +000093
94using SCCNodeSet = SmallSetVector<Function *, 8>;
95
96} // end anonymous namespace
Chandler Carruthc518ebd2015-10-29 18:29:15 +000097
Peter Collingbournec45f7f32017-02-14 00:28:13 +000098/// Returns the memory access attribute for function F using AAR for AA results,
99/// where SCCNodes is the current SCC.
100///
101/// If ThisBody is true, this function may examine the function body and will
102/// return a result pertaining to this copy of the function. If it is false, the
103/// result will be based only on AA results for the function declaration; it
104/// will be assumed that some other (perhaps less optimized) version of the
105/// function may be selected at link time.
106static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
107 AAResults &AAR,
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000108 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000109 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
110 if (MRB == FMRB_DoesNotAccessMemory)
111 // Already perfect!
112 return MAK_ReadNone;
113
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000114 if (!ThisBody) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000115 if (AliasAnalysis::onlyReadsMemory(MRB))
116 return MAK_ReadOnly;
117
Brian Homerding3ecabd72018-08-23 15:05:22 +0000118 if (AliasAnalysis::doesNotReadMemory(MRB))
119 return MAK_WriteOnly;
120
121 // Conservatively assume it reads and writes to memory.
Chandler Carruth7542d372015-09-21 17:39:41 +0000122 return MAK_MayWrite;
123 }
124
125 // Scan the function body for instructions that may read or write memory.
126 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000127 bool WritesMemory = false;
Chandler Carruth7542d372015-09-21 17:39:41 +0000128 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
129 Instruction *I = &*II;
130
131 // Some instructions can be ignored even if they read or write memory.
132 // Detect these now, skipping to the next instruction if one is found.
133 CallSite CS(cast<Value>(I));
134 if (CS) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000135 // Ignore calls to functions in the same SCC, as long as the call sites
136 // don't have operand bundles. Calls with operand bundles are allowed to
137 // have memory effects not described by the memory effects of the call
138 // target.
139 if (!CS.hasOperandBundles() && CS.getCalledFunction() &&
140 SCCNodes.count(CS.getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000141 continue;
142 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000143 ModRefInfo MRI = createModRefInfo(MRB);
Chandler Carruth7542d372015-09-21 17:39:41 +0000144
Chandler Carruth69798fb2015-10-27 01:41:43 +0000145 // If the call doesn't access memory, we're done.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000146 if (isNoModRef(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000147 continue;
148
149 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
Brian Homerding3ecabd72018-08-23 15:05:22 +0000150 // The call could access any memory. If that includes writes, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000151 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000152 WritesMemory = true;
Chandler Carruth69798fb2015-10-27 01:41:43 +0000153 // If it reads, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000154 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000155 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000156 continue;
157 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000158
159 // Check whether all pointer arguments point to local memory, and
160 // ignore calls that only access local memory.
161 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
162 CI != CE; ++CI) {
163 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000164 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000165 continue;
166
167 AAMDNodes AAInfo;
168 I->getAAMetadata(AAInfo);
George Burgess IV6ef80022018-10-10 21:28:44 +0000169 MemoryLocation Loc(Arg, LocationSize::unknown(), AAInfo);
Chandler Carruth69798fb2015-10-27 01:41:43 +0000170
171 // Skip accesses to local or constant memory as they don't impact the
172 // externally visible mod/ref behavior.
173 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
174 continue;
175
Alina Sbirlea63d22502017-12-05 20:12:23 +0000176 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000177 // Writes non-local memory.
178 WritesMemory = true;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000179 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000180 // Ok, it reads non-local memory.
181 ReadsMemory = true;
182 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000183 continue;
184 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
185 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
186 if (!LI->isVolatile()) {
187 MemoryLocation Loc = MemoryLocation::get(LI);
188 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
189 continue;
190 }
191 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
192 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
193 if (!SI->isVolatile()) {
194 MemoryLocation Loc = MemoryLocation::get(SI);
195 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
196 continue;
197 }
198 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
199 // Ignore vaargs on local memory.
200 MemoryLocation Loc = MemoryLocation::get(VI);
201 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
202 continue;
203 }
204
205 // Any remaining instructions need to be taken seriously! Check if they
206 // read or write memory.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000207 //
208 // Writes memory, remember that.
209 WritesMemory |= I->mayWriteToMemory();
Chandler Carruth7542d372015-09-21 17:39:41 +0000210
211 // If this instruction may read memory, remember that.
212 ReadsMemory |= I->mayReadFromMemory();
213 }
214
Brian Homerding3ecabd72018-08-23 15:05:22 +0000215 if (WritesMemory) {
216 if (!ReadsMemory)
217 return MAK_WriteOnly;
218 else
219 return MAK_MayWrite;
220 }
221
Chandler Carruth7542d372015-09-21 17:39:41 +0000222 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
223}
224
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000225MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
226 AAResults &AAR) {
227 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
228}
229
Chandler Carrutha632fb92015-09-13 06:57:25 +0000230/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000231template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000232static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000233 // Check if any of the functions in the SCC read or write memory. If they
234 // write memory then they can't be marked readnone or readonly.
235 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000236 bool WritesMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000237 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000238 // Call the callable parameter to look up AA results for this function.
239 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000240
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000241 // Non-exact function definitions may not be selected at link time, and an
242 // alternative version that writes to memory may be selected. See the
243 // comment on GlobalValue::isDefinitionExact for more details.
244 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
245 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000246 case MAK_MayWrite:
247 return false;
248 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000249 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000250 break;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000251 case MAK_WriteOnly:
252 WritesMemory = true;
253 break;
Chandler Carruth7542d372015-09-21 17:39:41 +0000254 case MAK_ReadNone:
255 // Nothing to do!
256 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000257 }
258 }
259
260 // Success! Functions in this SCC do not access memory, or only read memory.
261 // Give them the appropriate attribute.
262 bool MadeChange = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000263
264 assert(!(ReadsMemory && WritesMemory) &&
265 "Function marked read-only and write-only");
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000266 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000267 if (F->doesNotAccessMemory())
268 // Already perfect!
269 continue;
270
271 if (F->onlyReadsMemory() && ReadsMemory)
272 // No change.
273 continue;
274
Brian Homerding3ecabd72018-08-23 15:05:22 +0000275 if (F->doesNotReadMemory() && WritesMemory)
276 continue;
277
Duncan Sands44c8cd92008-12-31 16:14:43 +0000278 MadeChange = true;
279
280 // Clear out any existing attributes.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000281 F->removeFnAttr(Attribute::ReadOnly);
282 F->removeFnAttr(Attribute::ReadNone);
Brian Homerding3ecabd72018-08-23 15:05:22 +0000283 F->removeFnAttr(Attribute::WriteOnly);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000284
Johannes Doerfertae3cfeb2018-09-11 11:51:29 +0000285 if (!WritesMemory && !ReadsMemory) {
286 // Clear out any "access range attributes" if readnone was deduced.
287 F->removeFnAttr(Attribute::ArgMemOnly);
288 F->removeFnAttr(Attribute::InaccessibleMemOnly);
289 F->removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
290 }
291
Duncan Sands44c8cd92008-12-31 16:14:43 +0000292 // Add in the new attribute.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000293 if (WritesMemory && !ReadsMemory)
294 F->addFnAttr(Attribute::WriteOnly);
295 else
296 F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000297
Brian Homerding3ecabd72018-08-23 15:05:22 +0000298 if (WritesMemory && !ReadsMemory)
299 ++NumWriteOnly;
300 else if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000301 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000302 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000303 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000304 }
305
306 return MadeChange;
307}
308
Nick Lewycky4c378a42011-12-28 23:24:21 +0000309namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000310
Chandler Carrutha632fb92015-09-13 06:57:25 +0000311/// For a given pointer Argument, this retains a list of Arguments of functions
312/// in the same SCC that the pointer data flows into. We use this to build an
313/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000314struct ArgumentGraphNode {
315 Argument *Definition;
316 SmallVector<ArgumentGraphNode *, 4> Uses;
317};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000318
Chandler Carruth63559d72015-09-13 06:47:20 +0000319class ArgumentGraph {
320 // We store pointers to ArgumentGraphNode objects, so it's important that
321 // that they not move around upon insert.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000322 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000323
Chandler Carruth63559d72015-09-13 06:47:20 +0000324 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000325
Chandler Carruth63559d72015-09-13 06:47:20 +0000326 // There is no root node for the argument graph, in fact:
327 // void f(int *x, int *y) { if (...) f(x, y); }
328 // is an example where the graph is disconnected. The SCCIterator requires a
329 // single entry point, so we maintain a fake ("synthetic") root node that
330 // uses every node. Because the graph is directed and nothing points into
331 // the root, it will not participate in any SCCs (except for its own).
332 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000333
Chandler Carruth63559d72015-09-13 06:47:20 +0000334public:
335 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000336
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000337 using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000338
Chandler Carruth63559d72015-09-13 06:47:20 +0000339 iterator begin() { return SyntheticRoot.Uses.begin(); }
340 iterator end() { return SyntheticRoot.Uses.end(); }
341 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000342
Chandler Carruth63559d72015-09-13 06:47:20 +0000343 ArgumentGraphNode *operator[](Argument *A) {
344 ArgumentGraphNode &Node = ArgumentMap[A];
345 Node.Definition = A;
346 SyntheticRoot.Uses.push_back(&Node);
347 return &Node;
348 }
349};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000350
Chandler Carrutha632fb92015-09-13 06:57:25 +0000351/// This tracker checks whether callees are in the SCC, and if so it does not
352/// consider that a capture, instead adding it to the "Uses" list and
353/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000354struct ArgumentUsesTracker : public CaptureTracker {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000355 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000356
Chandler Carruth63559d72015-09-13 06:47:20 +0000357 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000358
Chandler Carruth63559d72015-09-13 06:47:20 +0000359 bool captured(const Use *U) override {
360 CallSite CS(U->getUser());
361 if (!CS.getInstruction()) {
362 Captured = true;
363 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000364 }
365
Chandler Carruth63559d72015-09-13 06:47:20 +0000366 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000367 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000368 Captured = true;
369 return true;
370 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000371
Sanjoy Das98bfe262015-11-05 03:04:40 +0000372 // Note: the callee and the two successor blocks *follow* the argument
373 // operands. This means there is no need to adjust UseIndex to account for
374 // these.
375
376 unsigned UseIndex =
377 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
378
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000379 assert(UseIndex < CS.data_operands_size() &&
380 "Indirect function calls should have been filtered above!");
381
382 if (UseIndex >= CS.getNumArgOperands()) {
383 // Data operand, but not a argument operand -- must be a bundle operand
384 assert(CS.hasOperandBundles() && "Must be!");
385
386 // CaptureTracking told us that we're being captured by an operand bundle
387 // use. In this case it does not matter if the callee is within our SCC
388 // or not -- we've been captured in some unknown way, and we have to be
389 // conservative.
390 Captured = true;
391 return true;
392 }
393
Sanjoy Das98bfe262015-11-05 03:04:40 +0000394 if (UseIndex >= F->arg_size()) {
395 assert(F->isVarArg() && "More params than args in non-varargs call");
396 Captured = true;
397 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000398 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000399
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000400 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000401 return false;
402 }
403
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000404 // True only if certainly captured (used outside our SCC).
405 bool Captured = false;
406
407 // Uses within our SCC.
408 SmallVector<Argument *, 4> Uses;
Chandler Carruth63559d72015-09-13 06:47:20 +0000409
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000410 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000411};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000412
413} // end anonymous namespace
Nick Lewycky4c378a42011-12-28 23:24:21 +0000414
415namespace llvm {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000416
Chandler Carruth63559d72015-09-13 06:47:20 +0000417template <> struct GraphTraits<ArgumentGraphNode *> {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000418 using NodeRef = ArgumentGraphNode *;
419 using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000420
Tim Shen48f814e2016-08-31 16:48:13 +0000421 static NodeRef getEntryNode(NodeRef A) { return A; }
422 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
423 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000424};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000425
Chandler Carruth63559d72015-09-13 06:47:20 +0000426template <>
427struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000428 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000429
Chandler Carruth63559d72015-09-13 06:47:20 +0000430 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
431 return AG->begin();
432 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000433
Chandler Carruth63559d72015-09-13 06:47:20 +0000434 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
435};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000436
437} // end namespace llvm
Nick Lewycky4c378a42011-12-28 23:24:21 +0000438
Chandler Carrutha632fb92015-09-13 06:57:25 +0000439/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000440static Attribute::AttrKind
441determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000442 const SmallPtrSet<Argument *, 8> &SCCNodes) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000443 SmallVector<Use *, 32> Worklist;
Florian Hahna1cc8482018-06-12 11:16:56 +0000444 SmallPtrSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000445
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000446 // inalloca arguments are always clobbered by the call.
447 if (A->hasInAllocaAttr())
448 return Attribute::None;
449
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000450 bool IsRead = false;
451 // We don't need to track IsWritten. If A is written to, return immediately.
452
Chandler Carruthcdf47882014-03-09 03:16:01 +0000453 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000454 Visited.insert(&U);
455 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000456 }
457
458 while (!Worklist.empty()) {
459 Use *U = Worklist.pop_back_val();
460 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000461
462 switch (I->getOpcode()) {
463 case Instruction::BitCast:
464 case Instruction::GetElementPtr:
465 case Instruction::PHI:
466 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000467 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000468 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000469 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000470 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000471 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000472 break;
473
474 case Instruction::Call:
475 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000476 bool Captures = true;
477
478 if (I->getType()->isVoidTy())
479 Captures = false;
480
481 auto AddUsersToWorklistIfCapturing = [&] {
482 if (Captures)
483 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000484 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000485 Worklist.push_back(&UU);
486 };
487
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000488 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000489 if (CS.doesNotAccessMemory()) {
490 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000491 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000492 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000493
494 Function *F = CS.getCalledFunction();
495 if (!F) {
496 if (CS.onlyReadsMemory()) {
497 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000498 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000499 continue;
500 }
501 return Attribute::None;
502 }
503
Sanjoy Das436e2392015-11-07 01:55:53 +0000504 // Note: the callee and the two successor blocks *follow* the argument
505 // operands. This means there is no need to adjust UseIndex to account
506 // for these.
507
508 unsigned UseIndex = std::distance(CS.arg_begin(), U);
509
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000510 // U cannot be the callee operand use: since we're exploring the
511 // transitive uses of an Argument, having such a use be a callee would
512 // imply the CallSite is an indirect call or invoke; and we'd take the
513 // early exit above.
514 assert(UseIndex < CS.data_operands_size() &&
515 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000516
517 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
518
519 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000520 assert(F->isVarArg() && "More params than args in non-varargs call");
521 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000522 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000523
Tilmann Scheller925b1932015-11-20 19:17:10 +0000524 Captures &= !CS.doesNotCapture(UseIndex);
525
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000526 // Since the optimizer (by design) cannot see the data flow corresponding
527 // to a operand bundle use, these cannot participate in the optimistic SCC
528 // analysis. Instead, we model the operand bundle uses as arguments in
529 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000530 if (IsOperandBundleUse ||
531 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000532
533 // The accessors used on CallSite here do the right thing for calls and
534 // invokes with operand bundles.
535
Sanjoy Das436e2392015-11-07 01:55:53 +0000536 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
537 return Attribute::None;
538 if (!CS.doesNotAccessMemory(UseIndex))
539 IsRead = true;
540 }
541
Nick Lewycky59633cb2014-05-30 02:31:27 +0000542 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000543 break;
544 }
545
546 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000547 // A volatile load has side effects beyond what readonly can be relied
548 // upon.
549 if (cast<LoadInst>(I)->isVolatile())
550 return Attribute::None;
551
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000552 IsRead = true;
553 break;
554
555 case Instruction::ICmp:
556 case Instruction::Ret:
557 break;
558
559 default:
560 return Attribute::None;
561 }
562 }
563
564 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
565}
566
David Majnemer5246e0b2016-07-19 18:50:26 +0000567/// Deduce returned attributes for the SCC.
568static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
569 bool Changed = false;
570
David Majnemer5246e0b2016-07-19 18:50:26 +0000571 // Check each function in turn, determining if an argument is always returned.
572 for (Function *F : SCCNodes) {
573 // We can infer and propagate function attributes only when we know that the
574 // definition we'll get at link time is *exactly* the definition we see now.
575 // For more details, see GlobalValue::mayBeDerefined.
576 if (!F->hasExactDefinition())
577 continue;
578
579 if (F->getReturnType()->isVoidTy())
580 continue;
581
David Majnemerc83044d2016-09-12 16:04:59 +0000582 // There is nothing to do if an argument is already marked as 'returned'.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000583 if (llvm::any_of(F->args(),
584 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
David Majnemerc83044d2016-09-12 16:04:59 +0000585 continue;
586
David Majnemer5246e0b2016-07-19 18:50:26 +0000587 auto FindRetArg = [&]() -> Value * {
588 Value *RetArg = nullptr;
589 for (BasicBlock &BB : *F)
590 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
591 // Note that stripPointerCasts should look through functions with
592 // returned arguments.
593 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
594 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
595 return nullptr;
596
597 if (!RetArg)
598 RetArg = RetVal;
599 else if (RetArg != RetVal)
600 return nullptr;
601 }
602
603 return RetArg;
604 };
605
606 if (Value *RetArg = FindRetArg()) {
607 auto *A = cast<Argument>(RetArg);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000608 A->addAttr(Attribute::Returned);
David Majnemer5246e0b2016-07-19 18:50:26 +0000609 ++NumReturned;
610 Changed = true;
611 }
612 }
613
614 return Changed;
615}
616
Sanjay Patel4f742162017-02-13 23:10:51 +0000617/// If a callsite has arguments that are also arguments to the parent function,
618/// try to propagate attributes from the callsite's arguments to the parent's
619/// arguments. This may be important because inlining can cause information loss
620/// when attribute knowledge disappears with the inlined call.
621static bool addArgumentAttrsFromCallsites(Function &F) {
622 if (!EnableNonnullArgPropagation)
623 return false;
624
625 bool Changed = false;
626
627 // For an argument attribute to transfer from a callsite to the parent, the
628 // call must be guaranteed to execute every time the parent is called.
629 // Conservatively, just check for calls in the entry block that are guaranteed
630 // to execute.
631 // TODO: This could be enhanced by testing if the callsite post-dominates the
632 // entry block or by doing simple forward walks or backward walks to the
633 // callsite.
634 BasicBlock &Entry = F.getEntryBlock();
635 for (Instruction &I : Entry) {
636 if (auto CS = CallSite(&I)) {
637 if (auto *CalledFunc = CS.getCalledFunction()) {
638 for (auto &CSArg : CalledFunc->args()) {
639 if (!CSArg.hasNonNullAttr())
640 continue;
641
642 // If the non-null callsite argument operand is an argument to 'F'
643 // (the caller) and the call is guaranteed to execute, then the value
644 // must be non-null throughout 'F'.
645 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
646 if (FArg && !FArg->hasNonNullAttr()) {
647 FArg->addAttr(Attribute::NonNull);
648 Changed = true;
649 }
650 }
651 }
652 }
653 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
654 break;
655 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000656
Sanjay Patel4f742162017-02-13 23:10:51 +0000657 return Changed;
658}
659
Chandler Carrutha632fb92015-09-13 06:57:25 +0000660/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000661static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000662 bool Changed = false;
663
Nick Lewycky4c378a42011-12-28 23:24:21 +0000664 ArgumentGraph AG;
665
Duncan Sands44c8cd92008-12-31 16:14:43 +0000666 // Check each function in turn, determining which pointer arguments are not
667 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000668 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000669 // We can infer and propagate function attributes only when we know that the
670 // definition we'll get at link time is *exactly* the definition we see now.
671 // For more details, see GlobalValue::mayBeDerefined.
672 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000673 continue;
674
Sanjay Patel4f742162017-02-13 23:10:51 +0000675 Changed |= addArgumentAttrsFromCallsites(*F);
676
Nick Lewycky4c378a42011-12-28 23:24:21 +0000677 // Functions that are readonly (or readnone) and nounwind and don't return
678 // a value can't capture arguments. Don't analyze them.
679 if (F->onlyReadsMemory() && F->doesNotThrow() &&
680 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000681 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
682 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000683 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000684 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000685 ++NumNoCapture;
686 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000687 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000688 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000689 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000690 }
691
Chandler Carruth63559d72015-09-13 06:47:20 +0000692 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
693 ++A) {
694 if (!A->getType()->isPointerTy())
695 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000696 bool HasNonLocalUses = false;
697 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000698 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000699 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000700 if (!Tracker.Captured) {
701 if (Tracker.Uses.empty()) {
702 // If it's trivially not captured, mark it nocapture now.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000703 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000704 ++NumNoCapture;
705 Changed = true;
706 } else {
707 // If it's not trivially captured and not trivially not captured,
708 // then it must be calling into another function in our SCC. Save
709 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000710 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000711 for (Argument *Use : Tracker.Uses) {
712 Node->Uses.push_back(AG[Use]);
713 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000714 HasNonLocalUses = true;
715 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000716 }
717 }
718 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
719 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000720 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
721 // Can we determine that it's readonly/readnone without doing an SCC?
722 // Note that we don't allow any calls at all here, or else our result
723 // will be dependent on the iteration order through the functions in the
724 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000725 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000726 Self.insert(&*A);
727 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000728 if (R != Attribute::None) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000729 A->addAttr(R);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000730 Changed = true;
731 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
732 }
733 }
734 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000735 }
736
737 // The graph we've collected is partial because we stopped scanning for
738 // argument uses once we solved the argument trivially. These partial nodes
739 // show up as ArgumentGraphNode objects with an empty Uses list, and for
740 // these nodes the final decision about whether they capture has already been
741 // made. If the definition doesn't have a 'nocapture' attribute by now, it
742 // captures.
743
Chandler Carruth63559d72015-09-13 06:47:20 +0000744 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000745 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000746 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000747 if (!ArgumentSCC[0]->Definition)
748 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000749
750 // eg. "void f(int* x) { if (...) f(x); }"
751 if (ArgumentSCC[0]->Uses.size() == 1 &&
752 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000753 Argument *A = ArgumentSCC[0]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000754 A->addAttr(Attribute::NoCapture);
Nick Lewycky7e820552009-01-02 03:46:56 +0000755 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000756 Changed = true;
757 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000758 continue;
759 }
760
761 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000762 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
763 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000764 ArgumentGraphNode *Node = *I;
765 if (Node->Uses.empty()) {
766 if (!Node->Definition->hasNoCaptureAttr())
767 SCCCaptured = true;
768 }
769 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000770 if (SCCCaptured)
771 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000772
Chandler Carruth63559d72015-09-13 06:47:20 +0000773 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000774 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
775 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000776 for (ArgumentGraphNode *I : ArgumentSCC) {
777 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000778 }
779
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000780 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
781 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000782 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000783 for (ArgumentGraphNode *Use : N->Uses) {
784 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000785 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
786 continue;
787 SCCCaptured = true;
788 break;
789 }
790 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000791 if (SCCCaptured)
792 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000793
Nick Lewyckyf740db32012-01-05 22:21:45 +0000794 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000795 Argument *A = ArgumentSCC[i]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000796 A->addAttr(Attribute::NoCapture);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000797 ++NumNoCapture;
798 Changed = true;
799 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000800
801 // We also want to compute readonly/readnone. With a small number of false
802 // negatives, we can assume that any pointer which is captured isn't going
803 // to be provably readonly or readnone, since by definition we can't
804 // analyze all uses of a captured pointer.
805 //
806 // The false negatives happen when the pointer is captured by a function
807 // that promises readonly/readnone behaviour on the pointer, then the
808 // pointer's lifetime ends before anything that writes to arbitrary memory.
809 // Also, a readonly/readnone pointer may be returned, but returning a
810 // pointer is capturing it.
811
812 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
813 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
814 Argument *A = ArgumentSCC[i]->Definition;
815 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
816 if (K == Attribute::ReadNone)
817 continue;
818 if (K == Attribute::ReadOnly) {
819 ReadAttr = Attribute::ReadOnly;
820 continue;
821 }
822 ReadAttr = K;
823 break;
824 }
825
826 if (ReadAttr != Attribute::None) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000827 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
828 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000829 // Clear out existing readonly/readnone attributes
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000830 A->removeAttr(Attribute::ReadOnly);
831 A->removeAttr(Attribute::ReadNone);
832 A->addAttr(ReadAttr);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000833 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
834 Changed = true;
835 }
836 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000837 }
838
839 return Changed;
840}
841
Chandler Carrutha632fb92015-09-13 06:57:25 +0000842/// Tests whether a function is "malloc-like".
843///
844/// A function is "malloc-like" if it returns either null or a pointer that
845/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000846static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000847 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000848 for (BasicBlock &BB : *F)
849 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000850 FlowsToReturn.insert(Ret->getReturnValue());
851
852 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000853 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000854
855 if (Constant *C = dyn_cast<Constant>(RetVal)) {
856 if (!C->isNullValue() && !isa<UndefValue>(C))
857 return false;
858
859 continue;
860 }
861
862 if (isa<Argument>(RetVal))
863 return false;
864
865 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
866 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000867 // Extend the analysis by looking upwards.
868 case Instruction::BitCast:
869 case Instruction::GetElementPtr:
870 case Instruction::AddrSpaceCast:
871 FlowsToReturn.insert(RVI->getOperand(0));
872 continue;
873 case Instruction::Select: {
874 SelectInst *SI = cast<SelectInst>(RVI);
875 FlowsToReturn.insert(SI->getTrueValue());
876 FlowsToReturn.insert(SI->getFalseValue());
877 continue;
878 }
879 case Instruction::PHI: {
880 PHINode *PN = cast<PHINode>(RVI);
881 for (Value *IncValue : PN->incoming_values())
882 FlowsToReturn.insert(IncValue);
883 continue;
884 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000885
Chandler Carruth63559d72015-09-13 06:47:20 +0000886 // Check whether the pointer came from an allocation.
887 case Instruction::Alloca:
888 break;
889 case Instruction::Call:
890 case Instruction::Invoke: {
891 CallSite CS(RVI);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000892 if (CS.hasRetAttr(Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000893 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000894 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
895 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000896 LLVM_FALLTHROUGH;
897 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000898 default:
899 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000900 }
901
Dan Gohman94e61762009-11-19 21:57:48 +0000902 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000903 return false;
904 }
905
906 return true;
907}
908
Chandler Carrutha632fb92015-09-13 06:57:25 +0000909/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000910static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000911 // Check each function in turn, determining which functions return noalias
912 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000913 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000914 // Already noalias.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000915 if (F->returnDoesNotAlias())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000916 continue;
917
Sanjoy Das5ce32722016-04-08 00:48:30 +0000918 // We can infer and propagate function attributes only when we know that the
919 // definition we'll get at link time is *exactly* the definition we see now.
920 // For more details, see GlobalValue::mayBeDerefined.
921 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000922 return false;
923
Chandler Carruth63559d72015-09-13 06:47:20 +0000924 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000925 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000926 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000927 continue;
928
Chandler Carruth3824f852015-09-13 08:23:27 +0000929 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000930 return false;
931 }
932
933 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000934 for (Function *F : SCCNodes) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000935 if (F->returnDoesNotAlias() ||
Reid Kleckner6652a522017-04-28 18:37:16 +0000936 !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000937 continue;
938
Reid Klecknera0b45f42017-05-03 18:17:31 +0000939 F->setReturnDoesNotAlias();
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000940 ++NumNoAlias;
941 MadeChange = true;
942 }
943
944 return MadeChange;
945}
946
Chandler Carrutha632fb92015-09-13 06:57:25 +0000947/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000948///
949/// Requires that the function returns a pointer.
950///
951/// Returns true if it believes the function will not return a null, and sets
952/// \p Speculative based on whether the returned conclusion is a speculative
953/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000954static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000955 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000956 assert(F->getReturnType()->isPointerTy() &&
957 "nonnull only meaningful on pointer types");
958 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000959
Philip Reamesa88caea2015-08-31 19:44:38 +0000960 SmallSetVector<Value *, 8> FlowsToReturn;
961 for (BasicBlock &BB : *F)
962 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
963 FlowsToReturn.insert(Ret->getReturnValue());
964
Nuno Lopes404f1062017-09-09 18:23:11 +0000965 auto &DL = F->getParent()->getDataLayout();
966
Philip Reamesa88caea2015-08-31 19:44:38 +0000967 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
968 Value *RetVal = FlowsToReturn[i];
969
970 // If this value is locally known to be non-null, we're good
Nuno Lopes404f1062017-09-09 18:23:11 +0000971 if (isKnownNonZero(RetVal, DL))
Philip Reamesa88caea2015-08-31 19:44:38 +0000972 continue;
973
974 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000975 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000976 Instruction *RVI = dyn_cast<Instruction>(RetVal);
977 if (!RVI)
978 return false;
979 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000980 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000981 case Instruction::BitCast:
982 case Instruction::GetElementPtr:
983 case Instruction::AddrSpaceCast:
984 FlowsToReturn.insert(RVI->getOperand(0));
985 continue;
986 case Instruction::Select: {
987 SelectInst *SI = cast<SelectInst>(RVI);
988 FlowsToReturn.insert(SI->getTrueValue());
989 FlowsToReturn.insert(SI->getFalseValue());
990 continue;
991 }
992 case Instruction::PHI: {
993 PHINode *PN = cast<PHINode>(RVI);
994 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
995 FlowsToReturn.insert(PN->getIncomingValue(i));
996 continue;
997 }
998 case Instruction::Call:
999 case Instruction::Invoke: {
1000 CallSite CS(RVI);
1001 Function *Callee = CS.getCalledFunction();
1002 // A call to a node within the SCC is assumed to return null until
1003 // proven otherwise
1004 if (Callee && SCCNodes.count(Callee)) {
1005 Speculative = true;
1006 continue;
1007 }
1008 return false;
1009 }
1010 default:
Chandler Carruth63559d72015-09-13 06:47:20 +00001011 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +00001012 };
1013 llvm_unreachable("should have either continued or returned");
1014 }
1015
1016 return true;
1017}
1018
Chandler Carrutha632fb92015-09-13 06:57:25 +00001019/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +00001020static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001021 // Speculative that all functions in the SCC return only nonnull
1022 // pointers. We may refute this as we analyze functions.
1023 bool SCCReturnsNonNull = true;
1024
1025 bool MadeChange = false;
1026
1027 // Check each function in turn, determining which functions return nonnull
1028 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001029 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001030 // Already nonnull.
Reid Klecknerb5180542017-03-21 16:57:19 +00001031 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001032 Attribute::NonNull))
1033 continue;
1034
Sanjoy Das5ce32722016-04-08 00:48:30 +00001035 // We can infer and propagate function attributes only when we know that the
1036 // definition we'll get at link time is *exactly* the definition we see now.
1037 // For more details, see GlobalValue::mayBeDerefined.
1038 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +00001039 return false;
1040
Chandler Carruth63559d72015-09-13 06:47:20 +00001041 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +00001042 // pointer types.
1043 if (!F->getReturnType()->isPointerTy())
1044 continue;
1045
1046 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +00001047 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001048 if (!Speculative) {
1049 // Mark the function eagerly since we may discover a function
1050 // which prevents us from speculating about the entire SCC
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001051 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1052 << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001053 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001054 ++NumNonNullReturn;
1055 MadeChange = true;
1056 }
1057 continue;
1058 }
1059 // At least one function returns something which could be null, can't
1060 // speculate any more.
1061 SCCReturnsNonNull = false;
1062 }
1063
1064 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001065 for (Function *F : SCCNodes) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001066 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001067 Attribute::NonNull) ||
1068 !F->getReturnType()->isPointerTy())
1069 continue;
1070
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001071 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001072 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001073 ++NumNonNullReturn;
1074 MadeChange = true;
1075 }
1076 }
1077
1078 return MadeChange;
1079}
1080
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001081namespace {
1082
1083/// Collects a set of attribute inference requests and performs them all in one
1084/// go on a single SCC Node. Inference involves scanning function bodies
1085/// looking for instructions that violate attribute assumptions.
1086/// As soon as all the bodies are fine we are free to set the attribute.
1087/// Customization of inference for individual attributes is performed by
1088/// providing a handful of predicates for each attribute.
1089class AttributeInferer {
1090public:
1091 /// Describes a request for inference of a single attribute.
1092 struct InferenceDescriptor {
1093
1094 /// Returns true if this function does not have to be handled.
1095 /// General intent for this predicate is to provide an optimization
1096 /// for functions that do not need this attribute inference at all
1097 /// (say, for functions that already have the attribute).
1098 std::function<bool(const Function &)> SkipFunction;
1099
1100 /// Returns true if this instruction violates attribute assumptions.
1101 std::function<bool(Instruction &)> InstrBreaksAttribute;
1102
1103 /// Sets the inferred attribute for this function.
1104 std::function<void(Function &)> SetAttribute;
1105
1106 /// Attribute we derive.
1107 Attribute::AttrKind AKind;
1108
1109 /// If true, only "exact" definitions can be used to infer this attribute.
1110 /// See GlobalValue::isDefinitionExact.
1111 bool RequiresExactDefinition;
1112
1113 InferenceDescriptor(Attribute::AttrKind AK,
1114 std::function<bool(const Function &)> SkipFunc,
1115 std::function<bool(Instruction &)> InstrScan,
1116 std::function<void(Function &)> SetAttr,
1117 bool ReqExactDef)
1118 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1119 SetAttribute(SetAttr), AKind(AK),
1120 RequiresExactDefinition(ReqExactDef) {}
1121 };
1122
1123private:
1124 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1125
1126public:
1127 void registerAttrInference(InferenceDescriptor AttrInference) {
1128 InferenceDescriptors.push_back(AttrInference);
1129 }
1130
1131 bool run(const SCCNodeSet &SCCNodes);
1132};
1133
1134/// Perform all the requested attribute inference actions according to the
1135/// attribute predicates stored before.
1136bool AttributeInferer::run(const SCCNodeSet &SCCNodes) {
1137 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1138 // Go through all the functions in SCC and check corresponding attribute
1139 // assumptions for each of them. Attributes that are invalid for this SCC
1140 // will be removed from InferInSCC.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001141 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001142
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001143 // No attributes whose assumptions are still valid - done.
1144 if (InferInSCC.empty())
1145 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001146
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001147 // Check if our attributes ever need scanning/can be scanned.
1148 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1149 if (ID.SkipFunction(*F))
Justin Lebar9d943972016-03-14 20:18:54 +00001150 return false;
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001151
1152 // Remove from further inference (invalidate) when visiting a function
1153 // that has no instructions to scan/has an unsuitable definition.
1154 return F->isDeclaration() ||
1155 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1156 });
1157
1158 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1159 // set up the F instructions scan to verify assumptions of the attribute.
1160 SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1161 llvm::copy_if(
1162 InferInSCC, std::back_inserter(InferInThisFunc),
1163 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1164
1165 if (InferInThisFunc.empty())
1166 continue;
1167
1168 // Start instruction scan.
1169 for (Instruction &I : instructions(*F)) {
1170 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1171 if (!ID.InstrBreaksAttribute(I))
1172 return false;
1173 // Remove attribute from further inference on any other functions
1174 // because attribute assumptions have just been violated.
1175 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1176 return D.AKind == ID.AKind;
1177 });
1178 // Remove attribute from the rest of current instruction scan.
1179 return true;
1180 });
1181
1182 if (InferInThisFunc.empty())
1183 break;
Justin Lebar9d943972016-03-14 20:18:54 +00001184 }
1185 }
1186
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001187 if (InferInSCC.empty())
1188 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001189
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001190 bool Changed = false;
1191 for (Function *F : SCCNodes)
1192 // At this point InferInSCC contains only functions that were either:
1193 // - explicitly skipped from scan/inference, or
1194 // - verified to have no instructions that break attribute assumptions.
1195 // Hence we just go and force the attribute for all non-skipped functions.
1196 for (auto &ID : InferInSCC) {
1197 if (ID.SkipFunction(*F))
1198 continue;
1199 Changed = true;
1200 ID.SetAttribute(*F);
1201 }
1202 return Changed;
1203}
Justin Lebar9d943972016-03-14 20:18:54 +00001204
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001205} // end anonymous namespace
1206
1207/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1208static bool InstrBreaksNonConvergent(Instruction &I,
1209 const SCCNodeSet &SCCNodes) {
1210 const CallSite CS(&I);
1211 // Breaks non-convergent assumption if CS is a convergent call to a function
1212 // not in the SCC.
1213 return CS && CS.isConvergent() && SCCNodes.count(CS.getCalledFunction()) == 0;
1214}
1215
1216/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1217static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1218 if (!I.mayThrow())
1219 return false;
1220 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1221 if (Function *Callee = CI->getCalledFunction()) {
1222 // I is a may-throw call to a function inside our SCC. This doesn't
1223 // invalidate our current working assumption that the SCC is no-throw; we
1224 // just have to scan that other function.
1225 if (SCCNodes.count(Callee) > 0)
1226 return false;
1227 }
Chandler Carruth3937bc72016-02-12 09:47:49 +00001228 }
Justin Lebar260854b2016-02-09 23:03:22 +00001229 return true;
1230}
1231
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001232/// Infer attributes from all functions in the SCC by scanning every
1233/// instruction for compliance to the attribute assumptions. Currently it
1234/// does:
1235/// - removal of Convergent attribute
1236/// - addition of NoUnwind attribute
1237///
1238/// Returns true if any changes to function attributes were made.
1239static bool inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes) {
1240
1241 AttributeInferer AI;
1242
1243 // Request to remove the convergent attribute from all functions in the SCC
1244 // if every callsite within the SCC is not convergent (except for calls
1245 // to functions within the SCC).
1246 // Note: Removal of the attr from the callsites will happen in
1247 // InstCombineCalls separately.
1248 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1249 Attribute::Convergent,
1250 // Skip non-convergent functions.
1251 [](const Function &F) { return !F.isConvergent(); },
1252 // Instructions that break non-convergent assumption.
1253 [SCCNodes](Instruction &I) {
1254 return InstrBreaksNonConvergent(I, SCCNodes);
1255 },
1256 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001257 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1258 << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001259 F.setNotConvergent();
1260 },
1261 /* RequiresExactDefinition= */ false});
1262
1263 if (!DisableNoUnwindInference)
1264 // Request to infer nounwind attribute for all the functions in the SCC if
1265 // every callsite within the SCC is not throwing (except for calls to
1266 // functions within the SCC). Note that nounwind attribute suffers from
1267 // derefinement - results may change depending on how functions are
1268 // optimized. Thus it can be inferred only from exact definitions.
1269 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1270 Attribute::NoUnwind,
1271 // Skip non-throwing functions.
1272 [](const Function &F) { return F.doesNotThrow(); },
1273 // Instructions that break non-throwing assumption.
1274 [SCCNodes](Instruction &I) {
1275 return InstrBreaksNonThrowing(I, SCCNodes);
1276 },
1277 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001278 LLVM_DEBUG(dbgs()
1279 << "Adding nounwind attr to fn " << F.getName() << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001280 F.setDoesNotThrow();
1281 ++NumNoUnwind;
1282 },
1283 /* RequiresExactDefinition= */ true});
1284
1285 // Perform all the requested attribute inference actions.
1286 return AI.run(SCCNodes);
1287}
1288
James Molloy7e9bdd52015-11-12 10:55:20 +00001289static bool setDoesNotRecurse(Function &F) {
1290 if (F.doesNotRecurse())
1291 return false;
1292 F.setDoesNotRecurse();
1293 ++NumNoRecurse;
1294 return true;
1295}
1296
Chandler Carruth632d2082016-02-13 08:47:51 +00001297static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001298 // Try and identify functions that do not recurse.
1299
1300 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001301 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001302 return false;
1303
Chandler Carruth632d2082016-02-13 08:47:51 +00001304 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001305 if (!F || F->isDeclaration() || F->doesNotRecurse())
1306 return false;
1307
1308 // If all of the calls in F are identifiable and are to norecurse functions, F
1309 // is norecurse. This check also detects self-recursion as F is not currently
1310 // marked norecurse, so any called from F to F will not be marked norecurse.
Christian Bruel4ead99b2018-12-05 16:48:00 +00001311 for (auto &BB : *F)
1312 for (auto &I : BB.instructionsWithoutDebug())
1313 if (auto CS = CallSite(&I)) {
1314 Function *Callee = CS.getCalledFunction();
1315 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1316 // Function calls a potentially recursive function.
1317 return false;
1318 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001319
Chandler Carruth632d2082016-02-13 08:47:51 +00001320 // Every call was to a non-recursive function other than this function, and
1321 // we have no indirect recursion as the SCC size is one. This function cannot
1322 // recurse.
1323 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001324}
1325
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001326template <typename AARGetterT>
1327static bool deriveAttrsInPostOrder(SCCNodeSet &SCCNodes, AARGetterT &&AARGetter,
1328 bool HasUnknownCall) {
1329 bool Changed = false;
1330
1331 // Bail if the SCC only contains optnone functions.
1332 if (SCCNodes.empty())
1333 return Changed;
1334
1335 Changed |= addArgumentReturnedAttrs(SCCNodes);
1336 Changed |= addReadAttrs(SCCNodes, AARGetter);
1337 Changed |= addArgumentAttrs(SCCNodes);
1338
1339 // If we have no external nodes participating in the SCC, we can deduce some
1340 // more precise attributes as well.
1341 if (!HasUnknownCall) {
1342 Changed |= addNoAliasAttrs(SCCNodes);
1343 Changed |= addNonNullAttrs(SCCNodes);
1344 Changed |= inferAttrsFromFunctionBodies(SCCNodes);
1345 Changed |= addNoRecurseAttrs(SCCNodes);
1346 }
1347
1348 return Changed;
1349}
1350
Chandler Carruthb47f8012016-03-11 11:05:24 +00001351PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001352 CGSCCAnalysisManager &AM,
1353 LazyCallGraph &CG,
1354 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001355 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001356 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001357
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001358 // We pass a lambda into functions to wire them up to the analysis manager
1359 // for getting function analyses.
1360 auto AARGetter = [&](Function &F) -> AAResults & {
1361 return FAM.getResult<AAManager>(F);
1362 };
1363
1364 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1365 // any external or opt-none nodes that will prevent us from optimizing any
1366 // part of the SCC.
1367 SCCNodeSet SCCNodes;
1368 bool HasUnknownCall = false;
1369 for (LazyCallGraph::Node &N : C) {
1370 Function &F = N.getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001371 if (F.hasFnAttribute(Attribute::OptimizeNone) ||
1372 F.hasFnAttribute(Attribute::Naked)) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001373 // Treat any function we're trying not to optimize as if it were an
1374 // indirect call and omit it from the node set used below.
1375 HasUnknownCall = true;
1376 continue;
1377 }
1378 // Track whether any functions in this SCC have an unknown call edge.
1379 // Note: if this is ever a performance hit, we can common it with
1380 // subsequent routines which also do scans over the instructions of the
1381 // function.
1382 if (!HasUnknownCall)
1383 for (Instruction &I : instructions(F))
1384 if (auto CS = CallSite(&I))
1385 if (!CS.getCalledFunction()) {
1386 HasUnknownCall = true;
1387 break;
1388 }
1389
1390 SCCNodes.insert(&F);
1391 }
1392
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001393 if (deriveAttrsInPostOrder(SCCNodes, AARGetter, HasUnknownCall))
1394 return PreservedAnalyses::none();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001395
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001396 return PreservedAnalyses::all();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001397}
1398
1399namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001400
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001401struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001402 // Pass identification, replacement for typeid
1403 static char ID;
1404
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001405 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001406 initializePostOrderFunctionAttrsLegacyPassPass(
1407 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001408 }
1409
1410 bool runOnSCC(CallGraphSCC &SCC) override;
1411
1412 void getAnalysisUsage(AnalysisUsage &AU) const override {
1413 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001414 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001415 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001416 CallGraphSCCPass::getAnalysisUsage(AU);
1417 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001418};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001419
1420} // end anonymous namespace
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001421
1422char PostOrderFunctionAttrsLegacyPass::ID = 0;
1423INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1424 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001425INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001426INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001427INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1428 "Deduce function attributes", false, false)
1429
Chad Rosier611b73b2016-11-07 16:28:04 +00001430Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1431 return new PostOrderFunctionAttrsLegacyPass();
1432}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001433
Sean Silva997cbea2016-07-03 03:35:03 +00001434template <typename AARGetterT>
1435static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001436
1437 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1438 // whether a given CallGraphNode is in this SCC. Also track whether there are
1439 // any external or opt-none nodes that will prevent us from optimizing any
1440 // part of the SCC.
1441 SCCNodeSet SCCNodes;
1442 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001443 for (CallGraphNode *I : SCC) {
1444 Function *F = I->getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001445 if (!F || F->hasFnAttribute(Attribute::OptimizeNone) ||
1446 F->hasFnAttribute(Attribute::Naked)) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001447 // External node or function we're trying not to optimize - we both avoid
1448 // transform them and avoid leveraging information they provide.
1449 ExternalNode = true;
1450 continue;
1451 }
1452
1453 SCCNodes.insert(F);
1454 }
1455
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001456 return deriveAttrsInPostOrder(SCCNodes, AARGetter, ExternalNode);
James Molloy7e9bdd52015-11-12 10:55:20 +00001457}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001458
Sean Silva997cbea2016-07-03 03:35:03 +00001459bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1460 if (skipSCC(SCC))
1461 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001462 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001463}
1464
Chandler Carruth1926b702016-01-08 10:55:52 +00001465namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001466
Sean Silvaf5080192016-06-12 07:48:51 +00001467struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001468 // Pass identification, replacement for typeid
1469 static char ID;
1470
Sean Silvaf5080192016-06-12 07:48:51 +00001471 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001472 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1473 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001474 }
1475
1476 bool runOnModule(Module &M) override;
1477
1478 void getAnalysisUsage(AnalysisUsage &AU) const override {
1479 AU.setPreservesCFG();
1480 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001481 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001482 }
1483};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001484
1485} // end anonymous namespace
Chandler Carruth1926b702016-01-08 10:55:52 +00001486
Sean Silvaf5080192016-06-12 07:48:51 +00001487char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001488
Sean Silvaf5080192016-06-12 07:48:51 +00001489INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001490 "Deduce function attributes in RPO", false, false)
1491INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001492INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001493 "Deduce function attributes in RPO", false, false)
1494
1495Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001496 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001497}
1498
1499static bool addNoRecurseAttrsTopDown(Function &F) {
1500 // We check the preconditions for the function prior to calling this to avoid
1501 // the cost of building up a reversible post-order list. We assert them here
1502 // to make sure none of the invariants this relies on were violated.
1503 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1504 assert(!F.doesNotRecurse() &&
1505 "This function has already been deduced as norecurs!");
1506 assert(F.hasInternalLinkage() &&
1507 "Can only do top-down deduction for internal linkage functions!");
1508
1509 // If F is internal and all of its uses are calls from a non-recursive
1510 // functions, then none of its calls could in fact recurse without going
1511 // through a function marked norecurse, and so we can mark this function too
1512 // as norecurse. Note that the uses must actually be calls -- otherwise
1513 // a pointer to this function could be returned from a norecurse function but
1514 // this function could be recursively (indirectly) called. Note that this
1515 // also detects if F is directly recursive as F is not yet marked as
1516 // a norecurse function.
1517 for (auto *U : F.users()) {
1518 auto *I = dyn_cast<Instruction>(U);
1519 if (!I)
1520 return false;
1521 CallSite CS(I);
1522 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1523 return false;
1524 }
1525 return setDoesNotRecurse(F);
1526}
1527
Sean Silvaadc79392016-06-12 05:44:51 +00001528static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001529 // We only have a post-order SCC traversal (because SCCs are inherently
1530 // discovered in post-order), so we accumulate them in a vector and then walk
1531 // it in reverse. This is simpler than using the RPO iterator infrastructure
1532 // because we need to combine SCC detection and the PO walk of the call
1533 // graph. We can also cheat egregiously because we're primarily interested in
1534 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1535 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001536 SmallVector<Function *, 16> Worklist;
1537 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1538 if (I->size() != 1)
1539 continue;
1540
1541 Function *F = I->front()->getFunction();
1542 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1543 F->hasInternalLinkage())
1544 Worklist.push_back(F);
1545 }
1546
James Molloy7e9bdd52015-11-12 10:55:20 +00001547 bool Changed = false;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001548 for (auto *F : llvm::reverse(Worklist))
Chandler Carruth1926b702016-01-08 10:55:52 +00001549 Changed |= addNoRecurseAttrsTopDown(*F);
1550
Duncan Sands44c8cd92008-12-31 16:14:43 +00001551 return Changed;
1552}
Sean Silvaadc79392016-06-12 05:44:51 +00001553
Sean Silvaf5080192016-06-12 07:48:51 +00001554bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001555 if (skipModule(M))
1556 return false;
1557
1558 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1559
1560 return deduceFunctionAttributeInRPO(M, CG);
1561}
Sean Silvaf5080192016-06-12 07:48:51 +00001562
1563PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001564ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001565 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1566
Chandler Carruth6acdca72017-01-24 12:55:57 +00001567 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001568 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001569
Sean Silvaf5080192016-06-12 07:48:51 +00001570 PreservedAnalyses PA;
1571 PA.preserve<CallGraphAnalysis>();
1572 return PA;
1573}