blob: 77e98ecd9103cfa7d4bd10294fe808985c53bb91 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Duncan Sands44c8cd92008-12-31 16:14:43 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenkof27d1612017-10-19 21:21:30 +00008//
Chandler Carruth1926b702016-01-08 10:55:52 +00009/// \file
10/// This file implements interprocedural passes which walk the
11/// call-graph deducing and/or propagating function attributes.
Eugene Zelenkof27d1612017-10-19 21:21:30 +000012//
Duncan Sands44c8cd92008-12-31 16:14:43 +000013//===----------------------------------------------------------------------===//
14
Chandler Carruth9c4ed172016-02-18 11:03:11 +000015#include "llvm/Transforms/IPO/FunctionAttrs.h"
Nick Lewycky4c378a42011-12-28 23:24:21 +000016#include "llvm/ADT/SCCIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000017#include "llvm/ADT/STLExtras.h"
Benjamin Kramer15591272012-10-31 13:45:49 +000018#include "llvm/ADT/SetVector.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000019#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000020#include "llvm/ADT/SmallVector.h"
Duncan Sands44c8cd92008-12-31 16:14:43 +000021#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000023#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/BasicAliasAnalysis.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000025#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000027#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/CaptureTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000029#include "llvm/Analysis/LazyCallGraph.h"
30#include "llvm/Analysis/MemoryLocation.h"
Philip Reamesa88caea2015-08-31 19:44:38 +000031#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000032#include "llvm/IR/Argument.h"
33#include "llvm/IR/Attributes.h"
34#include "llvm/IR/BasicBlock.h"
35#include "llvm/IR/CallSite.h"
36#include "llvm/IR/Constant.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000039#include "llvm/IR/InstIterator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000040#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Instructions.h"
Christian Bruel4ead99b2018-12-05 16:48:00 +000043#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000044#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.
Chandler Carruth363ac682019-01-07 05:42:51 +0000132 if (auto *Call = dyn_cast<CallBase>(I)) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000133 // Ignore calls to functions in the same SCC, as long as the call sites
134 // don't have operand bundles. Calls with operand bundles are allowed to
135 // have memory effects not described by the memory effects of the call
136 // target.
Chandler Carruth363ac682019-01-07 05:42:51 +0000137 if (!Call->hasOperandBundles() && Call->getCalledFunction() &&
138 SCCNodes.count(Call->getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000139 continue;
Chandler Carruth363ac682019-01-07 05:42:51 +0000140 FunctionModRefBehavior MRB = AAR.getModRefBehavior(Call);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000141 ModRefInfo MRI = createModRefInfo(MRB);
Chandler Carruth7542d372015-09-21 17:39:41 +0000142
Chandler Carruth69798fb2015-10-27 01:41:43 +0000143 // If the call doesn't access memory, we're done.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000144 if (isNoModRef(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000145 continue;
146
147 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
Brian Homerding3ecabd72018-08-23 15:05:22 +0000148 // The call could access any memory. If that includes writes, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000149 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000150 WritesMemory = true;
Chandler Carruth69798fb2015-10-27 01:41:43 +0000151 // If it reads, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000152 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000153 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000154 continue;
155 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000156
157 // Check whether all pointer arguments point to local memory, and
158 // ignore calls that only access local memory.
Chandler Carruth363ac682019-01-07 05:42:51 +0000159 for (CallSite::arg_iterator CI = Call->arg_begin(), CE = Call->arg_end();
Chandler Carruth69798fb2015-10-27 01:41:43 +0000160 CI != CE; ++CI) {
161 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000162 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000163 continue;
164
165 AAMDNodes AAInfo;
166 I->getAAMetadata(AAInfo);
George Burgess IV6ef80022018-10-10 21:28:44 +0000167 MemoryLocation Loc(Arg, LocationSize::unknown(), AAInfo);
Chandler Carruth69798fb2015-10-27 01:41:43 +0000168
169 // Skip accesses to local or constant memory as they don't impact the
170 // externally visible mod/ref behavior.
171 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
172 continue;
173
Alina Sbirlea63d22502017-12-05 20:12:23 +0000174 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000175 // Writes non-local memory.
176 WritesMemory = true;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000177 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000178 // Ok, it reads non-local memory.
179 ReadsMemory = true;
180 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000181 continue;
182 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
183 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
184 if (!LI->isVolatile()) {
185 MemoryLocation Loc = MemoryLocation::get(LI);
186 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
187 continue;
188 }
189 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
190 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
191 if (!SI->isVolatile()) {
192 MemoryLocation Loc = MemoryLocation::get(SI);
193 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
194 continue;
195 }
196 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
197 // Ignore vaargs on local memory.
198 MemoryLocation Loc = MemoryLocation::get(VI);
199 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
200 continue;
201 }
202
203 // Any remaining instructions need to be taken seriously! Check if they
204 // read or write memory.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000205 //
206 // Writes memory, remember that.
207 WritesMemory |= I->mayWriteToMemory();
Chandler Carruth7542d372015-09-21 17:39:41 +0000208
209 // If this instruction may read memory, remember that.
210 ReadsMemory |= I->mayReadFromMemory();
211 }
212
Brian Homerding3ecabd72018-08-23 15:05:22 +0000213 if (WritesMemory) {
214 if (!ReadsMemory)
215 return MAK_WriteOnly;
216 else
217 return MAK_MayWrite;
218 }
219
Chandler Carruth7542d372015-09-21 17:39:41 +0000220 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
221}
222
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000223MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
224 AAResults &AAR) {
225 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
226}
227
Chandler Carrutha632fb92015-09-13 06:57:25 +0000228/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000229template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000230static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000231 // Check if any of the functions in the SCC read or write memory. If they
232 // write memory then they can't be marked readnone or readonly.
233 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000234 bool WritesMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000235 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000236 // Call the callable parameter to look up AA results for this function.
237 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000238
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000239 // Non-exact function definitions may not be selected at link time, and an
240 // alternative version that writes to memory may be selected. See the
241 // comment on GlobalValue::isDefinitionExact for more details.
242 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
243 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000244 case MAK_MayWrite:
245 return false;
246 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000247 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000248 break;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000249 case MAK_WriteOnly:
250 WritesMemory = true;
251 break;
Chandler Carruth7542d372015-09-21 17:39:41 +0000252 case MAK_ReadNone:
253 // Nothing to do!
254 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000255 }
256 }
257
258 // Success! Functions in this SCC do not access memory, or only read memory.
259 // Give them the appropriate attribute.
260 bool MadeChange = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000261
262 assert(!(ReadsMemory && WritesMemory) &&
263 "Function marked read-only and write-only");
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000264 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000265 if (F->doesNotAccessMemory())
266 // Already perfect!
267 continue;
268
269 if (F->onlyReadsMemory() && ReadsMemory)
270 // No change.
271 continue;
272
Brian Homerding3ecabd72018-08-23 15:05:22 +0000273 if (F->doesNotReadMemory() && WritesMemory)
274 continue;
275
Duncan Sands44c8cd92008-12-31 16:14:43 +0000276 MadeChange = true;
277
278 // Clear out any existing attributes.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000279 F->removeFnAttr(Attribute::ReadOnly);
280 F->removeFnAttr(Attribute::ReadNone);
Brian Homerding3ecabd72018-08-23 15:05:22 +0000281 F->removeFnAttr(Attribute::WriteOnly);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000282
Johannes Doerfertae3cfeb2018-09-11 11:51:29 +0000283 if (!WritesMemory && !ReadsMemory) {
284 // Clear out any "access range attributes" if readnone was deduced.
285 F->removeFnAttr(Attribute::ArgMemOnly);
286 F->removeFnAttr(Attribute::InaccessibleMemOnly);
287 F->removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
288 }
289
Duncan Sands44c8cd92008-12-31 16:14:43 +0000290 // Add in the new attribute.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000291 if (WritesMemory && !ReadsMemory)
292 F->addFnAttr(Attribute::WriteOnly);
293 else
294 F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000295
Brian Homerding3ecabd72018-08-23 15:05:22 +0000296 if (WritesMemory && !ReadsMemory)
297 ++NumWriteOnly;
298 else if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000299 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000300 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000301 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000302 }
303
304 return MadeChange;
305}
306
Nick Lewycky4c378a42011-12-28 23:24:21 +0000307namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000308
Chandler Carrutha632fb92015-09-13 06:57:25 +0000309/// For a given pointer Argument, this retains a list of Arguments of functions
310/// in the same SCC that the pointer data flows into. We use this to build an
311/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000312struct ArgumentGraphNode {
313 Argument *Definition;
314 SmallVector<ArgumentGraphNode *, 4> Uses;
315};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000316
Chandler Carruth63559d72015-09-13 06:47:20 +0000317class ArgumentGraph {
318 // We store pointers to ArgumentGraphNode objects, so it's important that
319 // that they not move around upon insert.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000320 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000321
Chandler Carruth63559d72015-09-13 06:47:20 +0000322 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000323
Chandler Carruth63559d72015-09-13 06:47:20 +0000324 // There is no root node for the argument graph, in fact:
325 // void f(int *x, int *y) { if (...) f(x, y); }
326 // is an example where the graph is disconnected. The SCCIterator requires a
327 // single entry point, so we maintain a fake ("synthetic") root node that
328 // uses every node. Because the graph is directed and nothing points into
329 // the root, it will not participate in any SCCs (except for its own).
330 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000331
Chandler Carruth63559d72015-09-13 06:47:20 +0000332public:
333 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000334
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000335 using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000336
Chandler Carruth63559d72015-09-13 06:47:20 +0000337 iterator begin() { return SyntheticRoot.Uses.begin(); }
338 iterator end() { return SyntheticRoot.Uses.end(); }
339 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000340
Chandler Carruth63559d72015-09-13 06:47:20 +0000341 ArgumentGraphNode *operator[](Argument *A) {
342 ArgumentGraphNode &Node = ArgumentMap[A];
343 Node.Definition = A;
344 SyntheticRoot.Uses.push_back(&Node);
345 return &Node;
346 }
347};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000348
Chandler Carrutha632fb92015-09-13 06:57:25 +0000349/// This tracker checks whether callees are in the SCC, and if so it does not
350/// consider that a capture, instead adding it to the "Uses" list and
351/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000352struct ArgumentUsesTracker : public CaptureTracker {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000353 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000354
Chandler Carruth63559d72015-09-13 06:47:20 +0000355 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000356
Chandler Carruth63559d72015-09-13 06:47:20 +0000357 bool captured(const Use *U) override {
358 CallSite CS(U->getUser());
359 if (!CS.getInstruction()) {
360 Captured = true;
361 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000362 }
363
Chandler Carruth63559d72015-09-13 06:47:20 +0000364 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000365 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000366 Captured = true;
367 return true;
368 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000369
Sanjoy Das98bfe262015-11-05 03:04:40 +0000370 // Note: the callee and the two successor blocks *follow* the argument
371 // operands. This means there is no need to adjust UseIndex to account for
372 // these.
373
374 unsigned UseIndex =
375 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
376
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000377 assert(UseIndex < CS.data_operands_size() &&
378 "Indirect function calls should have been filtered above!");
379
380 if (UseIndex >= CS.getNumArgOperands()) {
381 // Data operand, but not a argument operand -- must be a bundle operand
382 assert(CS.hasOperandBundles() && "Must be!");
383
384 // CaptureTracking told us that we're being captured by an operand bundle
385 // use. In this case it does not matter if the callee is within our SCC
386 // or not -- we've been captured in some unknown way, and we have to be
387 // conservative.
388 Captured = true;
389 return true;
390 }
391
Sanjoy Das98bfe262015-11-05 03:04:40 +0000392 if (UseIndex >= F->arg_size()) {
393 assert(F->isVarArg() && "More params than args in non-varargs call");
394 Captured = true;
395 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000396 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000397
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000398 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000399 return false;
400 }
401
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000402 // True only if certainly captured (used outside our SCC).
403 bool Captured = false;
404
405 // Uses within our SCC.
406 SmallVector<Argument *, 4> Uses;
Chandler Carruth63559d72015-09-13 06:47:20 +0000407
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000408 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000409};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000410
411} // end anonymous namespace
Nick Lewycky4c378a42011-12-28 23:24:21 +0000412
413namespace llvm {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000414
Chandler Carruth63559d72015-09-13 06:47:20 +0000415template <> struct GraphTraits<ArgumentGraphNode *> {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000416 using NodeRef = ArgumentGraphNode *;
417 using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000418
Tim Shen48f814e2016-08-31 16:48:13 +0000419 static NodeRef getEntryNode(NodeRef A) { return A; }
420 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
421 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000422};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000423
Chandler Carruth63559d72015-09-13 06:47:20 +0000424template <>
425struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000426 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000427
Chandler Carruth63559d72015-09-13 06:47:20 +0000428 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
429 return AG->begin();
430 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000431
Chandler Carruth63559d72015-09-13 06:47:20 +0000432 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
433};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000434
435} // end namespace llvm
Nick Lewycky4c378a42011-12-28 23:24:21 +0000436
Chandler Carrutha632fb92015-09-13 06:57:25 +0000437/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000438static Attribute::AttrKind
439determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000440 const SmallPtrSet<Argument *, 8> &SCCNodes) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000441 SmallVector<Use *, 32> Worklist;
Florian Hahna1cc8482018-06-12 11:16:56 +0000442 SmallPtrSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000443
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000444 // inalloca arguments are always clobbered by the call.
445 if (A->hasInAllocaAttr())
446 return Attribute::None;
447
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000448 bool IsRead = false;
449 // We don't need to track IsWritten. If A is written to, return immediately.
450
Chandler Carruthcdf47882014-03-09 03:16:01 +0000451 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000452 Visited.insert(&U);
453 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000454 }
455
456 while (!Worklist.empty()) {
457 Use *U = Worklist.pop_back_val();
458 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000459
460 switch (I->getOpcode()) {
461 case Instruction::BitCast:
462 case Instruction::GetElementPtr:
463 case Instruction::PHI:
464 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000465 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000466 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000467 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000468 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000469 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000470 break;
471
472 case Instruction::Call:
473 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000474 bool Captures = true;
475
476 if (I->getType()->isVoidTy())
477 Captures = false;
478
479 auto AddUsersToWorklistIfCapturing = [&] {
480 if (Captures)
481 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000482 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000483 Worklist.push_back(&UU);
484 };
485
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000486 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000487 if (CS.doesNotAccessMemory()) {
488 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000489 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000490 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000491
492 Function *F = CS.getCalledFunction();
493 if (!F) {
494 if (CS.onlyReadsMemory()) {
495 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000496 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000497 continue;
498 }
499 return Attribute::None;
500 }
501
Sanjoy Das436e2392015-11-07 01:55:53 +0000502 // Note: the callee and the two successor blocks *follow* the argument
503 // operands. This means there is no need to adjust UseIndex to account
504 // for these.
505
506 unsigned UseIndex = std::distance(CS.arg_begin(), U);
507
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000508 // U cannot be the callee operand use: since we're exploring the
509 // transitive uses of an Argument, having such a use be a callee would
510 // imply the CallSite is an indirect call or invoke; and we'd take the
511 // early exit above.
512 assert(UseIndex < CS.data_operands_size() &&
513 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000514
515 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
516
517 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000518 assert(F->isVarArg() && "More params than args in non-varargs call");
519 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000520 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000521
Tilmann Scheller925b1932015-11-20 19:17:10 +0000522 Captures &= !CS.doesNotCapture(UseIndex);
523
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000524 // Since the optimizer (by design) cannot see the data flow corresponding
525 // to a operand bundle use, these cannot participate in the optimistic SCC
526 // analysis. Instead, we model the operand bundle uses as arguments in
527 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000528 if (IsOperandBundleUse ||
529 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000530
531 // The accessors used on CallSite here do the right thing for calls and
532 // invokes with operand bundles.
533
Sanjoy Das436e2392015-11-07 01:55:53 +0000534 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
535 return Attribute::None;
536 if (!CS.doesNotAccessMemory(UseIndex))
537 IsRead = true;
538 }
539
Nick Lewycky59633cb2014-05-30 02:31:27 +0000540 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000541 break;
542 }
543
544 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000545 // A volatile load has side effects beyond what readonly can be relied
546 // upon.
547 if (cast<LoadInst>(I)->isVolatile())
548 return Attribute::None;
549
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000550 IsRead = true;
551 break;
552
553 case Instruction::ICmp:
554 case Instruction::Ret:
555 break;
556
557 default:
558 return Attribute::None;
559 }
560 }
561
562 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
563}
564
David Majnemer5246e0b2016-07-19 18:50:26 +0000565/// Deduce returned attributes for the SCC.
566static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
567 bool Changed = false;
568
David Majnemer5246e0b2016-07-19 18:50:26 +0000569 // Check each function in turn, determining if an argument is always returned.
570 for (Function *F : SCCNodes) {
571 // We can infer and propagate function attributes only when we know that the
572 // definition we'll get at link time is *exactly* the definition we see now.
573 // For more details, see GlobalValue::mayBeDerefined.
574 if (!F->hasExactDefinition())
575 continue;
576
577 if (F->getReturnType()->isVoidTy())
578 continue;
579
David Majnemerc83044d2016-09-12 16:04:59 +0000580 // There is nothing to do if an argument is already marked as 'returned'.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000581 if (llvm::any_of(F->args(),
582 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
David Majnemerc83044d2016-09-12 16:04:59 +0000583 continue;
584
David Majnemer5246e0b2016-07-19 18:50:26 +0000585 auto FindRetArg = [&]() -> Value * {
586 Value *RetArg = nullptr;
587 for (BasicBlock &BB : *F)
588 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
589 // Note that stripPointerCasts should look through functions with
590 // returned arguments.
591 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
592 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
593 return nullptr;
594
595 if (!RetArg)
596 RetArg = RetVal;
597 else if (RetArg != RetVal)
598 return nullptr;
599 }
600
601 return RetArg;
602 };
603
604 if (Value *RetArg = FindRetArg()) {
605 auto *A = cast<Argument>(RetArg);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000606 A->addAttr(Attribute::Returned);
David Majnemer5246e0b2016-07-19 18:50:26 +0000607 ++NumReturned;
608 Changed = true;
609 }
610 }
611
612 return Changed;
613}
614
Sanjay Patel4f742162017-02-13 23:10:51 +0000615/// If a callsite has arguments that are also arguments to the parent function,
616/// try to propagate attributes from the callsite's arguments to the parent's
617/// arguments. This may be important because inlining can cause information loss
618/// when attribute knowledge disappears with the inlined call.
619static bool addArgumentAttrsFromCallsites(Function &F) {
620 if (!EnableNonnullArgPropagation)
621 return false;
622
623 bool Changed = false;
624
625 // For an argument attribute to transfer from a callsite to the parent, the
626 // call must be guaranteed to execute every time the parent is called.
627 // Conservatively, just check for calls in the entry block that are guaranteed
628 // to execute.
629 // TODO: This could be enhanced by testing if the callsite post-dominates the
630 // entry block or by doing simple forward walks or backward walks to the
631 // callsite.
632 BasicBlock &Entry = F.getEntryBlock();
633 for (Instruction &I : Entry) {
634 if (auto CS = CallSite(&I)) {
635 if (auto *CalledFunc = CS.getCalledFunction()) {
636 for (auto &CSArg : CalledFunc->args()) {
637 if (!CSArg.hasNonNullAttr())
638 continue;
639
640 // If the non-null callsite argument operand is an argument to 'F'
641 // (the caller) and the call is guaranteed to execute, then the value
642 // must be non-null throughout 'F'.
643 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
644 if (FArg && !FArg->hasNonNullAttr()) {
645 FArg->addAttr(Attribute::NonNull);
646 Changed = true;
647 }
648 }
649 }
650 }
651 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
652 break;
653 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000654
Sanjay Patel4f742162017-02-13 23:10:51 +0000655 return Changed;
656}
657
Chandler Carrutha632fb92015-09-13 06:57:25 +0000658/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000659static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000660 bool Changed = false;
661
Nick Lewycky4c378a42011-12-28 23:24:21 +0000662 ArgumentGraph AG;
663
Duncan Sands44c8cd92008-12-31 16:14:43 +0000664 // Check each function in turn, determining which pointer arguments are not
665 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000666 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000667 // We can infer and propagate function attributes only when we know that the
668 // definition we'll get at link time is *exactly* the definition we see now.
669 // For more details, see GlobalValue::mayBeDerefined.
670 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000671 continue;
672
Sanjay Patel4f742162017-02-13 23:10:51 +0000673 Changed |= addArgumentAttrsFromCallsites(*F);
674
Nick Lewycky4c378a42011-12-28 23:24:21 +0000675 // Functions that are readonly (or readnone) and nounwind and don't return
676 // a value can't capture arguments. Don't analyze them.
677 if (F->onlyReadsMemory() && F->doesNotThrow() &&
678 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000679 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
680 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000681 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000682 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000683 ++NumNoCapture;
684 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000685 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000686 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000687 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000688 }
689
Chandler Carruth63559d72015-09-13 06:47:20 +0000690 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
691 ++A) {
692 if (!A->getType()->isPointerTy())
693 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000694 bool HasNonLocalUses = false;
695 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000696 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000697 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000698 if (!Tracker.Captured) {
699 if (Tracker.Uses.empty()) {
700 // If it's trivially not captured, mark it nocapture now.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000701 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000702 ++NumNoCapture;
703 Changed = true;
704 } else {
705 // If it's not trivially captured and not trivially not captured,
706 // then it must be calling into another function in our SCC. Save
707 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000708 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000709 for (Argument *Use : Tracker.Uses) {
710 Node->Uses.push_back(AG[Use]);
711 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000712 HasNonLocalUses = true;
713 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000714 }
715 }
716 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
717 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000718 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
719 // Can we determine that it's readonly/readnone without doing an SCC?
720 // Note that we don't allow any calls at all here, or else our result
721 // will be dependent on the iteration order through the functions in the
722 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000723 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000724 Self.insert(&*A);
725 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000726 if (R != Attribute::None) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000727 A->addAttr(R);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000728 Changed = true;
729 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
730 }
731 }
732 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000733 }
734
735 // The graph we've collected is partial because we stopped scanning for
736 // argument uses once we solved the argument trivially. These partial nodes
737 // show up as ArgumentGraphNode objects with an empty Uses list, and for
738 // these nodes the final decision about whether they capture has already been
739 // made. If the definition doesn't have a 'nocapture' attribute by now, it
740 // captures.
741
Chandler Carruth63559d72015-09-13 06:47:20 +0000742 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000743 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000744 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000745 if (!ArgumentSCC[0]->Definition)
746 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000747
748 // eg. "void f(int* x) { if (...) f(x); }"
749 if (ArgumentSCC[0]->Uses.size() == 1 &&
750 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000751 Argument *A = ArgumentSCC[0]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000752 A->addAttr(Attribute::NoCapture);
Nick Lewycky7e820552009-01-02 03:46:56 +0000753 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000754 Changed = true;
755 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000756 continue;
757 }
758
759 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000760 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
761 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000762 ArgumentGraphNode *Node = *I;
763 if (Node->Uses.empty()) {
764 if (!Node->Definition->hasNoCaptureAttr())
765 SCCCaptured = true;
766 }
767 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000768 if (SCCCaptured)
769 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000770
Chandler Carruth63559d72015-09-13 06:47:20 +0000771 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000772 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
773 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000774 for (ArgumentGraphNode *I : ArgumentSCC) {
775 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000776 }
777
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000778 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
779 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000780 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000781 for (ArgumentGraphNode *Use : N->Uses) {
782 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000783 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
784 continue;
785 SCCCaptured = true;
786 break;
787 }
788 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000789 if (SCCCaptured)
790 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000791
Nick Lewyckyf740db32012-01-05 22:21:45 +0000792 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000793 Argument *A = ArgumentSCC[i]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000794 A->addAttr(Attribute::NoCapture);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000795 ++NumNoCapture;
796 Changed = true;
797 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000798
799 // We also want to compute readonly/readnone. With a small number of false
800 // negatives, we can assume that any pointer which is captured isn't going
801 // to be provably readonly or readnone, since by definition we can't
802 // analyze all uses of a captured pointer.
803 //
804 // The false negatives happen when the pointer is captured by a function
805 // that promises readonly/readnone behaviour on the pointer, then the
806 // pointer's lifetime ends before anything that writes to arbitrary memory.
807 // Also, a readonly/readnone pointer may be returned, but returning a
808 // pointer is capturing it.
809
810 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
811 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
812 Argument *A = ArgumentSCC[i]->Definition;
813 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
814 if (K == Attribute::ReadNone)
815 continue;
816 if (K == Attribute::ReadOnly) {
817 ReadAttr = Attribute::ReadOnly;
818 continue;
819 }
820 ReadAttr = K;
821 break;
822 }
823
824 if (ReadAttr != Attribute::None) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000825 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
826 Argument *A = ArgumentSCC[i]->Definition;
Bjorn Steinbrink236446c2015-05-25 19:46:38 +0000827 // Clear out existing readonly/readnone attributes
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000828 A->removeAttr(Attribute::ReadOnly);
829 A->removeAttr(Attribute::ReadNone);
830 A->addAttr(ReadAttr);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000831 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
832 Changed = true;
833 }
834 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000835 }
836
837 return Changed;
838}
839
Chandler Carrutha632fb92015-09-13 06:57:25 +0000840/// Tests whether a function is "malloc-like".
841///
842/// A function is "malloc-like" if it returns either null or a pointer that
843/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000844static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000845 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000846 for (BasicBlock &BB : *F)
847 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000848 FlowsToReturn.insert(Ret->getReturnValue());
849
850 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000851 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000852
853 if (Constant *C = dyn_cast<Constant>(RetVal)) {
854 if (!C->isNullValue() && !isa<UndefValue>(C))
855 return false;
856
857 continue;
858 }
859
860 if (isa<Argument>(RetVal))
861 return false;
862
863 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
864 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000865 // Extend the analysis by looking upwards.
866 case Instruction::BitCast:
867 case Instruction::GetElementPtr:
868 case Instruction::AddrSpaceCast:
869 FlowsToReturn.insert(RVI->getOperand(0));
870 continue;
871 case Instruction::Select: {
872 SelectInst *SI = cast<SelectInst>(RVI);
873 FlowsToReturn.insert(SI->getTrueValue());
874 FlowsToReturn.insert(SI->getFalseValue());
875 continue;
876 }
877 case Instruction::PHI: {
878 PHINode *PN = cast<PHINode>(RVI);
879 for (Value *IncValue : PN->incoming_values())
880 FlowsToReturn.insert(IncValue);
881 continue;
882 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000883
Chandler Carruth63559d72015-09-13 06:47:20 +0000884 // Check whether the pointer came from an allocation.
885 case Instruction::Alloca:
886 break;
887 case Instruction::Call:
888 case Instruction::Invoke: {
889 CallSite CS(RVI);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000890 if (CS.hasRetAttr(Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000891 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000892 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
893 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000894 LLVM_FALLTHROUGH;
895 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000896 default:
897 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000898 }
899
Dan Gohman94e61762009-11-19 21:57:48 +0000900 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000901 return false;
902 }
903
904 return true;
905}
906
Chandler Carrutha632fb92015-09-13 06:57:25 +0000907/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000908static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000909 // Check each function in turn, determining which functions return noalias
910 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000911 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000912 // Already noalias.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000913 if (F->returnDoesNotAlias())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000914 continue;
915
Sanjoy Das5ce32722016-04-08 00:48:30 +0000916 // We can infer and propagate function attributes only when we know that the
917 // definition we'll get at link time is *exactly* the definition we see now.
918 // For more details, see GlobalValue::mayBeDerefined.
919 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000920 return false;
921
Chandler Carruth63559d72015-09-13 06:47:20 +0000922 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000923 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000924 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000925 continue;
926
Chandler Carruth3824f852015-09-13 08:23:27 +0000927 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000928 return false;
929 }
930
931 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000932 for (Function *F : SCCNodes) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000933 if (F->returnDoesNotAlias() ||
Reid Kleckner6652a522017-04-28 18:37:16 +0000934 !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000935 continue;
936
Reid Klecknera0b45f42017-05-03 18:17:31 +0000937 F->setReturnDoesNotAlias();
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000938 ++NumNoAlias;
939 MadeChange = true;
940 }
941
942 return MadeChange;
943}
944
Chandler Carrutha632fb92015-09-13 06:57:25 +0000945/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000946///
947/// Requires that the function returns a pointer.
948///
949/// Returns true if it believes the function will not return a null, and sets
950/// \p Speculative based on whether the returned conclusion is a speculative
951/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000952static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000953 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000954 assert(F->getReturnType()->isPointerTy() &&
955 "nonnull only meaningful on pointer types");
956 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000957
Philip Reamesa88caea2015-08-31 19:44:38 +0000958 SmallSetVector<Value *, 8> FlowsToReturn;
959 for (BasicBlock &BB : *F)
960 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
961 FlowsToReturn.insert(Ret->getReturnValue());
962
Nuno Lopes404f1062017-09-09 18:23:11 +0000963 auto &DL = F->getParent()->getDataLayout();
964
Philip Reamesa88caea2015-08-31 19:44:38 +0000965 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
966 Value *RetVal = FlowsToReturn[i];
967
968 // If this value is locally known to be non-null, we're good
Nuno Lopes404f1062017-09-09 18:23:11 +0000969 if (isKnownNonZero(RetVal, DL))
Philip Reamesa88caea2015-08-31 19:44:38 +0000970 continue;
971
972 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000973 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000974 Instruction *RVI = dyn_cast<Instruction>(RetVal);
975 if (!RVI)
976 return false;
977 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000978 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000979 case Instruction::BitCast:
980 case Instruction::GetElementPtr:
981 case Instruction::AddrSpaceCast:
982 FlowsToReturn.insert(RVI->getOperand(0));
983 continue;
984 case Instruction::Select: {
985 SelectInst *SI = cast<SelectInst>(RVI);
986 FlowsToReturn.insert(SI->getTrueValue());
987 FlowsToReturn.insert(SI->getFalseValue());
988 continue;
989 }
990 case Instruction::PHI: {
991 PHINode *PN = cast<PHINode>(RVI);
992 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
993 FlowsToReturn.insert(PN->getIncomingValue(i));
994 continue;
995 }
996 case Instruction::Call:
997 case Instruction::Invoke: {
998 CallSite CS(RVI);
999 Function *Callee = CS.getCalledFunction();
1000 // A call to a node within the SCC is assumed to return null until
1001 // proven otherwise
1002 if (Callee && SCCNodes.count(Callee)) {
1003 Speculative = true;
1004 continue;
1005 }
1006 return false;
1007 }
1008 default:
Chandler Carruth63559d72015-09-13 06:47:20 +00001009 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +00001010 };
1011 llvm_unreachable("should have either continued or returned");
1012 }
1013
1014 return true;
1015}
1016
Chandler Carrutha632fb92015-09-13 06:57:25 +00001017/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +00001018static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001019 // Speculative that all functions in the SCC return only nonnull
1020 // pointers. We may refute this as we analyze functions.
1021 bool SCCReturnsNonNull = true;
1022
1023 bool MadeChange = false;
1024
1025 // Check each function in turn, determining which functions return nonnull
1026 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001027 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001028 // Already nonnull.
Reid Klecknerb5180542017-03-21 16:57:19 +00001029 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001030 Attribute::NonNull))
1031 continue;
1032
Sanjoy Das5ce32722016-04-08 00:48:30 +00001033 // We can infer and propagate function attributes only when we know that the
1034 // definition we'll get at link time is *exactly* the definition we see now.
1035 // For more details, see GlobalValue::mayBeDerefined.
1036 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +00001037 return false;
1038
Chandler Carruth63559d72015-09-13 06:47:20 +00001039 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +00001040 // pointer types.
1041 if (!F->getReturnType()->isPointerTy())
1042 continue;
1043
1044 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +00001045 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001046 if (!Speculative) {
1047 // Mark the function eagerly since we may discover a function
1048 // which prevents us from speculating about the entire SCC
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001049 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1050 << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001051 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001052 ++NumNonNullReturn;
1053 MadeChange = true;
1054 }
1055 continue;
1056 }
1057 // At least one function returns something which could be null, can't
1058 // speculate any more.
1059 SCCReturnsNonNull = false;
1060 }
1061
1062 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001063 for (Function *F : SCCNodes) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001064 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001065 Attribute::NonNull) ||
1066 !F->getReturnType()->isPointerTy())
1067 continue;
1068
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001069 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001070 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001071 ++NumNonNullReturn;
1072 MadeChange = true;
1073 }
1074 }
1075
1076 return MadeChange;
1077}
1078
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001079namespace {
1080
1081/// Collects a set of attribute inference requests and performs them all in one
1082/// go on a single SCC Node. Inference involves scanning function bodies
1083/// looking for instructions that violate attribute assumptions.
1084/// As soon as all the bodies are fine we are free to set the attribute.
1085/// Customization of inference for individual attributes is performed by
1086/// providing a handful of predicates for each attribute.
1087class AttributeInferer {
1088public:
1089 /// Describes a request for inference of a single attribute.
1090 struct InferenceDescriptor {
1091
1092 /// Returns true if this function does not have to be handled.
1093 /// General intent for this predicate is to provide an optimization
1094 /// for functions that do not need this attribute inference at all
1095 /// (say, for functions that already have the attribute).
1096 std::function<bool(const Function &)> SkipFunction;
1097
1098 /// Returns true if this instruction violates attribute assumptions.
1099 std::function<bool(Instruction &)> InstrBreaksAttribute;
1100
1101 /// Sets the inferred attribute for this function.
1102 std::function<void(Function &)> SetAttribute;
1103
1104 /// Attribute we derive.
1105 Attribute::AttrKind AKind;
1106
1107 /// If true, only "exact" definitions can be used to infer this attribute.
1108 /// See GlobalValue::isDefinitionExact.
1109 bool RequiresExactDefinition;
1110
1111 InferenceDescriptor(Attribute::AttrKind AK,
1112 std::function<bool(const Function &)> SkipFunc,
1113 std::function<bool(Instruction &)> InstrScan,
1114 std::function<void(Function &)> SetAttr,
1115 bool ReqExactDef)
1116 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1117 SetAttribute(SetAttr), AKind(AK),
1118 RequiresExactDefinition(ReqExactDef) {}
1119 };
1120
1121private:
1122 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1123
1124public:
1125 void registerAttrInference(InferenceDescriptor AttrInference) {
1126 InferenceDescriptors.push_back(AttrInference);
1127 }
1128
1129 bool run(const SCCNodeSet &SCCNodes);
1130};
1131
1132/// Perform all the requested attribute inference actions according to the
1133/// attribute predicates stored before.
1134bool AttributeInferer::run(const SCCNodeSet &SCCNodes) {
1135 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1136 // Go through all the functions in SCC and check corresponding attribute
1137 // assumptions for each of them. Attributes that are invalid for this SCC
1138 // will be removed from InferInSCC.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001139 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001140
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001141 // No attributes whose assumptions are still valid - done.
1142 if (InferInSCC.empty())
1143 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001144
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001145 // Check if our attributes ever need scanning/can be scanned.
1146 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1147 if (ID.SkipFunction(*F))
Justin Lebar9d943972016-03-14 20:18:54 +00001148 return false;
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001149
1150 // Remove from further inference (invalidate) when visiting a function
1151 // that has no instructions to scan/has an unsuitable definition.
1152 return F->isDeclaration() ||
1153 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1154 });
1155
1156 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1157 // set up the F instructions scan to verify assumptions of the attribute.
1158 SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1159 llvm::copy_if(
1160 InferInSCC, std::back_inserter(InferInThisFunc),
1161 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1162
1163 if (InferInThisFunc.empty())
1164 continue;
1165
1166 // Start instruction scan.
1167 for (Instruction &I : instructions(*F)) {
1168 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1169 if (!ID.InstrBreaksAttribute(I))
1170 return false;
1171 // Remove attribute from further inference on any other functions
1172 // because attribute assumptions have just been violated.
1173 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1174 return D.AKind == ID.AKind;
1175 });
1176 // Remove attribute from the rest of current instruction scan.
1177 return true;
1178 });
1179
1180 if (InferInThisFunc.empty())
1181 break;
Justin Lebar9d943972016-03-14 20:18:54 +00001182 }
1183 }
1184
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001185 if (InferInSCC.empty())
1186 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001187
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001188 bool Changed = false;
1189 for (Function *F : SCCNodes)
1190 // At this point InferInSCC contains only functions that were either:
1191 // - explicitly skipped from scan/inference, or
1192 // - verified to have no instructions that break attribute assumptions.
1193 // Hence we just go and force the attribute for all non-skipped functions.
1194 for (auto &ID : InferInSCC) {
1195 if (ID.SkipFunction(*F))
1196 continue;
1197 Changed = true;
1198 ID.SetAttribute(*F);
1199 }
1200 return Changed;
1201}
Justin Lebar9d943972016-03-14 20:18:54 +00001202
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001203} // end anonymous namespace
1204
1205/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1206static bool InstrBreaksNonConvergent(Instruction &I,
1207 const SCCNodeSet &SCCNodes) {
1208 const CallSite CS(&I);
1209 // Breaks non-convergent assumption if CS is a convergent call to a function
1210 // not in the SCC.
1211 return CS && CS.isConvergent() && SCCNodes.count(CS.getCalledFunction()) == 0;
1212}
1213
1214/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1215static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1216 if (!I.mayThrow())
1217 return false;
1218 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1219 if (Function *Callee = CI->getCalledFunction()) {
1220 // I is a may-throw call to a function inside our SCC. This doesn't
1221 // invalidate our current working assumption that the SCC is no-throw; we
1222 // just have to scan that other function.
1223 if (SCCNodes.count(Callee) > 0)
1224 return false;
1225 }
Chandler Carruth3937bc72016-02-12 09:47:49 +00001226 }
Justin Lebar260854b2016-02-09 23:03:22 +00001227 return true;
1228}
1229
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001230/// Infer attributes from all functions in the SCC by scanning every
1231/// instruction for compliance to the attribute assumptions. Currently it
1232/// does:
1233/// - removal of Convergent attribute
1234/// - addition of NoUnwind attribute
1235///
1236/// Returns true if any changes to function attributes were made.
1237static bool inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes) {
1238
1239 AttributeInferer AI;
1240
1241 // Request to remove the convergent attribute from all functions in the SCC
1242 // if every callsite within the SCC is not convergent (except for calls
1243 // to functions within the SCC).
1244 // Note: Removal of the attr from the callsites will happen in
1245 // InstCombineCalls separately.
1246 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1247 Attribute::Convergent,
1248 // Skip non-convergent functions.
1249 [](const Function &F) { return !F.isConvergent(); },
1250 // Instructions that break non-convergent assumption.
1251 [SCCNodes](Instruction &I) {
1252 return InstrBreaksNonConvergent(I, SCCNodes);
1253 },
1254 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001255 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1256 << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001257 F.setNotConvergent();
1258 },
1259 /* RequiresExactDefinition= */ false});
1260
1261 if (!DisableNoUnwindInference)
1262 // Request to infer nounwind attribute for all the functions in the SCC if
1263 // every callsite within the SCC is not throwing (except for calls to
1264 // functions within the SCC). Note that nounwind attribute suffers from
1265 // derefinement - results may change depending on how functions are
1266 // optimized. Thus it can be inferred only from exact definitions.
1267 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1268 Attribute::NoUnwind,
1269 // Skip non-throwing functions.
1270 [](const Function &F) { return F.doesNotThrow(); },
1271 // Instructions that break non-throwing assumption.
1272 [SCCNodes](Instruction &I) {
1273 return InstrBreaksNonThrowing(I, SCCNodes);
1274 },
1275 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001276 LLVM_DEBUG(dbgs()
1277 << "Adding nounwind attr to fn " << F.getName() << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001278 F.setDoesNotThrow();
1279 ++NumNoUnwind;
1280 },
1281 /* RequiresExactDefinition= */ true});
1282
1283 // Perform all the requested attribute inference actions.
1284 return AI.run(SCCNodes);
1285}
1286
James Molloy7e9bdd52015-11-12 10:55:20 +00001287static bool setDoesNotRecurse(Function &F) {
1288 if (F.doesNotRecurse())
1289 return false;
1290 F.setDoesNotRecurse();
1291 ++NumNoRecurse;
1292 return true;
1293}
1294
Chandler Carruth632d2082016-02-13 08:47:51 +00001295static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001296 // Try and identify functions that do not recurse.
1297
1298 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001299 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001300 return false;
1301
Chandler Carruth632d2082016-02-13 08:47:51 +00001302 Function *F = *SCCNodes.begin();
James Molloy7e9bdd52015-11-12 10:55:20 +00001303 if (!F || F->isDeclaration() || F->doesNotRecurse())
1304 return false;
1305
1306 // If all of the calls in F are identifiable and are to norecurse functions, F
1307 // is norecurse. This check also detects self-recursion as F is not currently
1308 // marked norecurse, so any called from F to F will not be marked norecurse.
Christian Bruel4ead99b2018-12-05 16:48:00 +00001309 for (auto &BB : *F)
1310 for (auto &I : BB.instructionsWithoutDebug())
1311 if (auto CS = CallSite(&I)) {
1312 Function *Callee = CS.getCalledFunction();
1313 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1314 // Function calls a potentially recursive function.
1315 return false;
1316 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001317
Chandler Carruth632d2082016-02-13 08:47:51 +00001318 // Every call was to a non-recursive function other than this function, and
1319 // we have no indirect recursion as the SCC size is one. This function cannot
1320 // recurse.
1321 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001322}
1323
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001324template <typename AARGetterT>
1325static bool deriveAttrsInPostOrder(SCCNodeSet &SCCNodes, AARGetterT &&AARGetter,
1326 bool HasUnknownCall) {
1327 bool Changed = false;
1328
1329 // Bail if the SCC only contains optnone functions.
1330 if (SCCNodes.empty())
1331 return Changed;
1332
1333 Changed |= addArgumentReturnedAttrs(SCCNodes);
1334 Changed |= addReadAttrs(SCCNodes, AARGetter);
1335 Changed |= addArgumentAttrs(SCCNodes);
1336
1337 // If we have no external nodes participating in the SCC, we can deduce some
1338 // more precise attributes as well.
1339 if (!HasUnknownCall) {
1340 Changed |= addNoAliasAttrs(SCCNodes);
1341 Changed |= addNonNullAttrs(SCCNodes);
1342 Changed |= inferAttrsFromFunctionBodies(SCCNodes);
1343 Changed |= addNoRecurseAttrs(SCCNodes);
1344 }
1345
1346 return Changed;
1347}
1348
Chandler Carruthb47f8012016-03-11 11:05:24 +00001349PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001350 CGSCCAnalysisManager &AM,
1351 LazyCallGraph &CG,
1352 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001353 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001354 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001355
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001356 // We pass a lambda into functions to wire them up to the analysis manager
1357 // for getting function analyses.
1358 auto AARGetter = [&](Function &F) -> AAResults & {
1359 return FAM.getResult<AAManager>(F);
1360 };
1361
1362 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1363 // any external or opt-none nodes that will prevent us from optimizing any
1364 // part of the SCC.
1365 SCCNodeSet SCCNodes;
1366 bool HasUnknownCall = false;
1367 for (LazyCallGraph::Node &N : C) {
1368 Function &F = N.getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001369 if (F.hasFnAttribute(Attribute::OptimizeNone) ||
1370 F.hasFnAttribute(Attribute::Naked)) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001371 // Treat any function we're trying not to optimize as if it were an
1372 // indirect call and omit it from the node set used below.
1373 HasUnknownCall = true;
1374 continue;
1375 }
1376 // Track whether any functions in this SCC have an unknown call edge.
1377 // Note: if this is ever a performance hit, we can common it with
1378 // subsequent routines which also do scans over the instructions of the
1379 // function.
1380 if (!HasUnknownCall)
1381 for (Instruction &I : instructions(F))
1382 if (auto CS = CallSite(&I))
1383 if (!CS.getCalledFunction()) {
1384 HasUnknownCall = true;
1385 break;
1386 }
1387
1388 SCCNodes.insert(&F);
1389 }
1390
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001391 if (deriveAttrsInPostOrder(SCCNodes, AARGetter, HasUnknownCall))
1392 return PreservedAnalyses::none();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001393
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001394 return PreservedAnalyses::all();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001395}
1396
1397namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001398
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001399struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001400 // Pass identification, replacement for typeid
1401 static char ID;
1402
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001403 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001404 initializePostOrderFunctionAttrsLegacyPassPass(
1405 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001406 }
1407
1408 bool runOnSCC(CallGraphSCC &SCC) override;
1409
1410 void getAnalysisUsage(AnalysisUsage &AU) const override {
1411 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001412 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001413 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001414 CallGraphSCCPass::getAnalysisUsage(AU);
1415 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001416};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001417
1418} // end anonymous namespace
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001419
1420char PostOrderFunctionAttrsLegacyPass::ID = 0;
1421INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1422 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001423INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001424INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001425INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1426 "Deduce function attributes", false, false)
1427
Chad Rosier611b73b2016-11-07 16:28:04 +00001428Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1429 return new PostOrderFunctionAttrsLegacyPass();
1430}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001431
Sean Silva997cbea2016-07-03 03:35:03 +00001432template <typename AARGetterT>
1433static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001434
1435 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1436 // whether a given CallGraphNode is in this SCC. Also track whether there are
1437 // any external or opt-none nodes that will prevent us from optimizing any
1438 // part of the SCC.
1439 SCCNodeSet SCCNodes;
1440 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001441 for (CallGraphNode *I : SCC) {
1442 Function *F = I->getFunction();
Luke Cheeseman6c1e6bb2018-02-22 14:42:08 +00001443 if (!F || F->hasFnAttribute(Attribute::OptimizeNone) ||
1444 F->hasFnAttribute(Attribute::Naked)) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001445 // External node or function we're trying not to optimize - we both avoid
1446 // transform them and avoid leveraging information they provide.
1447 ExternalNode = true;
1448 continue;
1449 }
1450
1451 SCCNodes.insert(F);
1452 }
1453
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001454 return deriveAttrsInPostOrder(SCCNodes, AARGetter, ExternalNode);
James Molloy7e9bdd52015-11-12 10:55:20 +00001455}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001456
Sean Silva997cbea2016-07-03 03:35:03 +00001457bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1458 if (skipSCC(SCC))
1459 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001460 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001461}
1462
Chandler Carruth1926b702016-01-08 10:55:52 +00001463namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001464
Sean Silvaf5080192016-06-12 07:48:51 +00001465struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001466 // Pass identification, replacement for typeid
1467 static char ID;
1468
Sean Silvaf5080192016-06-12 07:48:51 +00001469 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001470 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1471 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001472 }
1473
1474 bool runOnModule(Module &M) override;
1475
1476 void getAnalysisUsage(AnalysisUsage &AU) const override {
1477 AU.setPreservesCFG();
1478 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001479 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001480 }
1481};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001482
1483} // end anonymous namespace
Chandler Carruth1926b702016-01-08 10:55:52 +00001484
Sean Silvaf5080192016-06-12 07:48:51 +00001485char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001486
Sean Silvaf5080192016-06-12 07:48:51 +00001487INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001488 "Deduce function attributes in RPO", false, false)
1489INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001490INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001491 "Deduce function attributes in RPO", false, false)
1492
1493Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001494 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001495}
1496
1497static bool addNoRecurseAttrsTopDown(Function &F) {
1498 // We check the preconditions for the function prior to calling this to avoid
1499 // the cost of building up a reversible post-order list. We assert them here
1500 // to make sure none of the invariants this relies on were violated.
1501 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1502 assert(!F.doesNotRecurse() &&
1503 "This function has already been deduced as norecurs!");
1504 assert(F.hasInternalLinkage() &&
1505 "Can only do top-down deduction for internal linkage functions!");
1506
1507 // If F is internal and all of its uses are calls from a non-recursive
1508 // functions, then none of its calls could in fact recurse without going
1509 // through a function marked norecurse, and so we can mark this function too
1510 // as norecurse. Note that the uses must actually be calls -- otherwise
1511 // a pointer to this function could be returned from a norecurse function but
1512 // this function could be recursively (indirectly) called. Note that this
1513 // also detects if F is directly recursive as F is not yet marked as
1514 // a norecurse function.
1515 for (auto *U : F.users()) {
1516 auto *I = dyn_cast<Instruction>(U);
1517 if (!I)
1518 return false;
1519 CallSite CS(I);
1520 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1521 return false;
1522 }
1523 return setDoesNotRecurse(F);
1524}
1525
Sean Silvaadc79392016-06-12 05:44:51 +00001526static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001527 // We only have a post-order SCC traversal (because SCCs are inherently
1528 // discovered in post-order), so we accumulate them in a vector and then walk
1529 // it in reverse. This is simpler than using the RPO iterator infrastructure
1530 // because we need to combine SCC detection and the PO walk of the call
1531 // graph. We can also cheat egregiously because we're primarily interested in
1532 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1533 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001534 SmallVector<Function *, 16> Worklist;
1535 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1536 if (I->size() != 1)
1537 continue;
1538
1539 Function *F = I->front()->getFunction();
1540 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1541 F->hasInternalLinkage())
1542 Worklist.push_back(F);
1543 }
1544
James Molloy7e9bdd52015-11-12 10:55:20 +00001545 bool Changed = false;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001546 for (auto *F : llvm::reverse(Worklist))
Chandler Carruth1926b702016-01-08 10:55:52 +00001547 Changed |= addNoRecurseAttrsTopDown(*F);
1548
Duncan Sands44c8cd92008-12-31 16:14:43 +00001549 return Changed;
1550}
Sean Silvaadc79392016-06-12 05:44:51 +00001551
Sean Silvaf5080192016-06-12 07:48:51 +00001552bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001553 if (skipModule(M))
1554 return false;
1555
1556 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1557
1558 return deduceFunctionAttributeInRPO(M, CG);
1559}
Sean Silvaf5080192016-06-12 07:48:51 +00001560
1561PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001562ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001563 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1564
Chandler Carruth6acdca72017-01-24 12:55:57 +00001565 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001566 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001567
Sean Silvaf5080192016-06-12 07:48:51 +00001568 PreservedAnalyses PA;
1569 PA.preserve<CallGraphAnalysis>();
1570 return PA;
1571}