blob: 0e923a717e6eadb2ce4c3c5034d8caa128285c12 [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"
Brian Homerdingb4b21d82019-07-08 15:57:56 +000030#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000031#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");
Brian Homerdingb4b21d82019-07-08 15:57:56 +000079STATISTIC(NumNoFree, "Number of functions marked as nofree");
Duncan Sands44c8cd92008-12-31 16:14:43 +000080
Sanjay Patel4f742162017-02-13 23:10:51 +000081// FIXME: This is disabled by default to avoid exposing security vulnerabilities
82// in C/C++ code compiled by clang:
83// http://lists.llvm.org/pipermail/cfe-dev/2017-January/052066.html
84static cl::opt<bool> EnableNonnullArgPropagation(
85 "enable-nonnull-arg-prop", cl::Hidden,
86 cl::desc("Try to propagate nonnull argument attributes from callsites to "
87 "caller functions."));
88
Fedor Sergeev6660fd02018-03-23 21:46:16 +000089static cl::opt<bool> DisableNoUnwindInference(
90 "disable-nounwind-inference", cl::Hidden,
91 cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
92
Brian Homerdingb4b21d82019-07-08 15:57:56 +000093static cl::opt<bool> DisableNoFreeInference(
94 "disable-nofree-inference", cl::Hidden,
95 cl::desc("Stop inferring nofree attribute during function-attrs pass"));
96
Duncan Sands44c8cd92008-12-31 16:14:43 +000097namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +000098
99using SCCNodeSet = SmallSetVector<Function *, 8>;
100
101} // end anonymous namespace
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000102
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000103/// Returns the memory access attribute for function F using AAR for AA results,
104/// where SCCNodes is the current SCC.
105///
106/// If ThisBody is true, this function may examine the function body and will
107/// return a result pertaining to this copy of the function. If it is false, the
108/// result will be based only on AA results for the function declaration; it
109/// will be assumed that some other (perhaps less optimized) version of the
110/// function may be selected at link time.
111static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
112 AAResults &AAR,
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000113 const SCCNodeSet &SCCNodes) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000114 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
115 if (MRB == FMRB_DoesNotAccessMemory)
116 // Already perfect!
117 return MAK_ReadNone;
118
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000119 if (!ThisBody) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000120 if (AliasAnalysis::onlyReadsMemory(MRB))
121 return MAK_ReadOnly;
122
Brian Homerding3ecabd72018-08-23 15:05:22 +0000123 if (AliasAnalysis::doesNotReadMemory(MRB))
124 return MAK_WriteOnly;
125
126 // Conservatively assume it reads and writes to memory.
Chandler Carruth7542d372015-09-21 17:39:41 +0000127 return MAK_MayWrite;
128 }
129
130 // Scan the function body for instructions that may read or write memory.
131 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000132 bool WritesMemory = false;
Chandler Carruth7542d372015-09-21 17:39:41 +0000133 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
134 Instruction *I = &*II;
135
136 // Some instructions can be ignored even if they read or write memory.
137 // Detect these now, skipping to the next instruction if one is found.
Chandler Carruth363ac682019-01-07 05:42:51 +0000138 if (auto *Call = dyn_cast<CallBase>(I)) {
Sanjoy Das10c8a042016-02-09 18:40:40 +0000139 // Ignore calls to functions in the same SCC, as long as the call sites
140 // don't have operand bundles. Calls with operand bundles are allowed to
141 // have memory effects not described by the memory effects of the call
142 // target.
Chandler Carruth363ac682019-01-07 05:42:51 +0000143 if (!Call->hasOperandBundles() && Call->getCalledFunction() &&
144 SCCNodes.count(Call->getCalledFunction()))
Chandler Carruth7542d372015-09-21 17:39:41 +0000145 continue;
Chandler Carruth363ac682019-01-07 05:42:51 +0000146 FunctionModRefBehavior MRB = AAR.getModRefBehavior(Call);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000147 ModRefInfo MRI = createModRefInfo(MRB);
Chandler Carruth7542d372015-09-21 17:39:41 +0000148
Chandler Carruth69798fb2015-10-27 01:41:43 +0000149 // If the call doesn't access memory, we're done.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000150 if (isNoModRef(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000151 continue;
152
153 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
Brian Homerding3ecabd72018-08-23 15:05:22 +0000154 // The call could access any memory. If that includes writes, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000155 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000156 WritesMemory = true;
Chandler Carruth69798fb2015-10-27 01:41:43 +0000157 // If it reads, note it.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000158 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000159 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000160 continue;
161 }
Chandler Carruth69798fb2015-10-27 01:41:43 +0000162
163 // Check whether all pointer arguments point to local memory, and
164 // ignore calls that only access local memory.
Chandler Carruth363ac682019-01-07 05:42:51 +0000165 for (CallSite::arg_iterator CI = Call->arg_begin(), CE = Call->arg_end();
Chandler Carruth69798fb2015-10-27 01:41:43 +0000166 CI != CE; ++CI) {
167 Value *Arg = *CI;
Elena Demikhovsky3ec9e152015-11-17 19:30:51 +0000168 if (!Arg->getType()->isPtrOrPtrVectorTy())
Chandler Carruth69798fb2015-10-27 01:41:43 +0000169 continue;
170
171 AAMDNodes AAInfo;
172 I->getAAMetadata(AAInfo);
George Burgess IV6ef80022018-10-10 21:28:44 +0000173 MemoryLocation Loc(Arg, LocationSize::unknown(), AAInfo);
Chandler Carruth69798fb2015-10-27 01:41:43 +0000174
175 // Skip accesses to local or constant memory as they don't impact the
176 // externally visible mod/ref behavior.
177 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
178 continue;
179
Alina Sbirlea63d22502017-12-05 20:12:23 +0000180 if (isModSet(MRI))
Brian Homerding3ecabd72018-08-23 15:05:22 +0000181 // Writes non-local memory.
182 WritesMemory = true;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000183 if (isRefSet(MRI))
Chandler Carruth69798fb2015-10-27 01:41:43 +0000184 // Ok, it reads non-local memory.
185 ReadsMemory = true;
186 }
Chandler Carruth7542d372015-09-21 17:39:41 +0000187 continue;
188 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
189 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
190 if (!LI->isVolatile()) {
191 MemoryLocation Loc = MemoryLocation::get(LI);
192 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
193 continue;
194 }
195 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
196 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
197 if (!SI->isVolatile()) {
198 MemoryLocation Loc = MemoryLocation::get(SI);
199 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
200 continue;
201 }
202 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
203 // Ignore vaargs on local memory.
204 MemoryLocation Loc = MemoryLocation::get(VI);
205 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
206 continue;
207 }
208
209 // Any remaining instructions need to be taken seriously! Check if they
210 // read or write memory.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000211 //
212 // Writes memory, remember that.
213 WritesMemory |= I->mayWriteToMemory();
Chandler Carruth7542d372015-09-21 17:39:41 +0000214
215 // If this instruction may read memory, remember that.
216 ReadsMemory |= I->mayReadFromMemory();
217 }
218
Brian Homerding3ecabd72018-08-23 15:05:22 +0000219 if (WritesMemory) {
220 if (!ReadsMemory)
221 return MAK_WriteOnly;
222 else
223 return MAK_MayWrite;
224 }
225
Chandler Carruth7542d372015-09-21 17:39:41 +0000226 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
227}
228
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000229MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
230 AAResults &AAR) {
231 return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
232}
233
Chandler Carrutha632fb92015-09-13 06:57:25 +0000234/// Deduce readonly/readnone attributes for the SCC.
Chandler Carrutha8125352015-10-30 16:48:08 +0000235template <typename AARGetterT>
Peter Collingbournecea1e4e2017-02-09 23:11:52 +0000236static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000237 // Check if any of the functions in the SCC read or write memory. If they
238 // write memory then they can't be marked readnone or readonly.
239 bool ReadsMemory = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000240 bool WritesMemory = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000241 for (Function *F : SCCNodes) {
Chandler Carrutha8125352015-10-30 16:48:08 +0000242 // Call the callable parameter to look up AA results for this function.
243 AAResults &AAR = AARGetter(*F);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000244
Peter Collingbournec45f7f32017-02-14 00:28:13 +0000245 // Non-exact function definitions may not be selected at link time, and an
246 // alternative version that writes to memory may be selected. See the
247 // comment on GlobalValue::isDefinitionExact for more details.
248 switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
249 AAR, SCCNodes)) {
Chandler Carruth7542d372015-09-21 17:39:41 +0000250 case MAK_MayWrite:
251 return false;
252 case MAK_ReadOnly:
Duncan Sands44c8cd92008-12-31 16:14:43 +0000253 ReadsMemory = true;
Chandler Carruth7542d372015-09-21 17:39:41 +0000254 break;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000255 case MAK_WriteOnly:
256 WritesMemory = true;
257 break;
Chandler Carruth7542d372015-09-21 17:39:41 +0000258 case MAK_ReadNone:
259 // Nothing to do!
260 break;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000261 }
262 }
263
Johannes Doerfert3dcd7992019-07-15 17:31:26 +0000264 // If the SCC contains both functions that read and functions that write, then
265 // we cannot add readonly attributes.
266 if (ReadsMemory && WritesMemory)
267 return false;
268
Duncan Sands44c8cd92008-12-31 16:14:43 +0000269 // Success! Functions in this SCC do not access memory, or only read memory.
270 // Give them the appropriate attribute.
271 bool MadeChange = false;
Brian Homerding3ecabd72018-08-23 15:05:22 +0000272
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000273 for (Function *F : SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000274 if (F->doesNotAccessMemory())
275 // Already perfect!
276 continue;
277
278 if (F->onlyReadsMemory() && ReadsMemory)
279 // No change.
280 continue;
281
Brian Homerding3ecabd72018-08-23 15:05:22 +0000282 if (F->doesNotReadMemory() && WritesMemory)
283 continue;
284
Duncan Sands44c8cd92008-12-31 16:14:43 +0000285 MadeChange = true;
286
287 // Clear out any existing attributes.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000288 F->removeFnAttr(Attribute::ReadOnly);
289 F->removeFnAttr(Attribute::ReadNone);
Brian Homerding3ecabd72018-08-23 15:05:22 +0000290 F->removeFnAttr(Attribute::WriteOnly);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000291
Johannes Doerfertae3cfeb2018-09-11 11:51:29 +0000292 if (!WritesMemory && !ReadsMemory) {
293 // Clear out any "access range attributes" if readnone was deduced.
294 F->removeFnAttr(Attribute::ArgMemOnly);
295 F->removeFnAttr(Attribute::InaccessibleMemOnly);
296 F->removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
297 }
298
Duncan Sands44c8cd92008-12-31 16:14:43 +0000299 // Add in the new attribute.
Brian Homerding3ecabd72018-08-23 15:05:22 +0000300 if (WritesMemory && !ReadsMemory)
301 F->addFnAttr(Attribute::WriteOnly);
302 else
303 F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
Duncan Sands44c8cd92008-12-31 16:14:43 +0000304
Brian Homerding3ecabd72018-08-23 15:05:22 +0000305 if (WritesMemory && !ReadsMemory)
306 ++NumWriteOnly;
307 else if (ReadsMemory)
Duncan Sandscefc8602009-01-02 11:46:24 +0000308 ++NumReadOnly;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000309 else
Duncan Sandscefc8602009-01-02 11:46:24 +0000310 ++NumReadNone;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000311 }
312
313 return MadeChange;
314}
315
Nick Lewycky4c378a42011-12-28 23:24:21 +0000316namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000317
Chandler Carrutha632fb92015-09-13 06:57:25 +0000318/// For a given pointer Argument, this retains a list of Arguments of functions
319/// in the same SCC that the pointer data flows into. We use this to build an
320/// SCC of the arguments.
Chandler Carruth63559d72015-09-13 06:47:20 +0000321struct ArgumentGraphNode {
322 Argument *Definition;
323 SmallVector<ArgumentGraphNode *, 4> Uses;
324};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000325
Chandler Carruth63559d72015-09-13 06:47:20 +0000326class ArgumentGraph {
327 // We store pointers to ArgumentGraphNode objects, so it's important that
328 // that they not move around upon insert.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000329 using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000330
Chandler Carruth63559d72015-09-13 06:47:20 +0000331 ArgumentMapTy ArgumentMap;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000332
Chandler Carruth63559d72015-09-13 06:47:20 +0000333 // There is no root node for the argument graph, in fact:
334 // void f(int *x, int *y) { if (...) f(x, y); }
335 // is an example where the graph is disconnected. The SCCIterator requires a
336 // single entry point, so we maintain a fake ("synthetic") root node that
337 // uses every node. Because the graph is directed and nothing points into
338 // the root, it will not participate in any SCCs (except for its own).
339 ArgumentGraphNode SyntheticRoot;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000340
Chandler Carruth63559d72015-09-13 06:47:20 +0000341public:
342 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000343
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000344 using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000345
Chandler Carruth63559d72015-09-13 06:47:20 +0000346 iterator begin() { return SyntheticRoot.Uses.begin(); }
347 iterator end() { return SyntheticRoot.Uses.end(); }
348 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000349
Chandler Carruth63559d72015-09-13 06:47:20 +0000350 ArgumentGraphNode *operator[](Argument *A) {
351 ArgumentGraphNode &Node = ArgumentMap[A];
352 Node.Definition = A;
353 SyntheticRoot.Uses.push_back(&Node);
354 return &Node;
355 }
356};
Nick Lewycky4c378a42011-12-28 23:24:21 +0000357
Chandler Carrutha632fb92015-09-13 06:57:25 +0000358/// This tracker checks whether callees are in the SCC, and if so it does not
359/// consider that a capture, instead adding it to the "Uses" list and
360/// continuing with the analysis.
Chandler Carruth63559d72015-09-13 06:47:20 +0000361struct ArgumentUsesTracker : public CaptureTracker {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000362 ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
Nick Lewycky4c378a42011-12-28 23:24:21 +0000363
Chandler Carruth63559d72015-09-13 06:47:20 +0000364 void tooManyUses() override { Captured = true; }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000365
Chandler Carruth63559d72015-09-13 06:47:20 +0000366 bool captured(const Use *U) override {
367 CallSite CS(U->getUser());
368 if (!CS.getInstruction()) {
369 Captured = true;
370 return true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000371 }
372
Chandler Carruth63559d72015-09-13 06:47:20 +0000373 Function *F = CS.getCalledFunction();
Sanjoy Das5ce32722016-04-08 00:48:30 +0000374 if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000375 Captured = true;
376 return true;
377 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000378
Sanjoy Das98bfe262015-11-05 03:04:40 +0000379 // Note: the callee and the two successor blocks *follow* the argument
380 // operands. This means there is no need to adjust UseIndex to account for
381 // these.
382
383 unsigned UseIndex =
384 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
385
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000386 assert(UseIndex < CS.data_operands_size() &&
387 "Indirect function calls should have been filtered above!");
388
389 if (UseIndex >= CS.getNumArgOperands()) {
390 // Data operand, but not a argument operand -- must be a bundle operand
391 assert(CS.hasOperandBundles() && "Must be!");
392
393 // CaptureTracking told us that we're being captured by an operand bundle
394 // use. In this case it does not matter if the callee is within our SCC
395 // or not -- we've been captured in some unknown way, and we have to be
396 // conservative.
397 Captured = true;
398 return true;
399 }
400
Sanjoy Das98bfe262015-11-05 03:04:40 +0000401 if (UseIndex >= F->arg_size()) {
402 assert(F->isVarArg() && "More params than args in non-varargs call");
403 Captured = true;
404 return true;
Chandler Carruth63559d72015-09-13 06:47:20 +0000405 }
Sanjoy Das98bfe262015-11-05 03:04:40 +0000406
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000407 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
Chandler Carruth63559d72015-09-13 06:47:20 +0000408 return false;
409 }
410
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000411 // True only if certainly captured (used outside our SCC).
412 bool Captured = false;
413
414 // Uses within our SCC.
415 SmallVector<Argument *, 4> Uses;
Chandler Carruth63559d72015-09-13 06:47:20 +0000416
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000417 const SCCNodeSet &SCCNodes;
Chandler Carruth63559d72015-09-13 06:47:20 +0000418};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000419
420} // end anonymous namespace
Nick Lewycky4c378a42011-12-28 23:24:21 +0000421
422namespace llvm {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000423
Chandler Carruth63559d72015-09-13 06:47:20 +0000424template <> struct GraphTraits<ArgumentGraphNode *> {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000425 using NodeRef = ArgumentGraphNode *;
426 using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000427
Tim Shen48f814e2016-08-31 16:48:13 +0000428 static NodeRef getEntryNode(NodeRef A) { return A; }
429 static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
430 static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
Chandler Carruth63559d72015-09-13 06:47:20 +0000431};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000432
Chandler Carruth63559d72015-09-13 06:47:20 +0000433template <>
434struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
Tim Shenf2187ed2016-08-22 21:09:30 +0000435 static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000436
Chandler Carruth63559d72015-09-13 06:47:20 +0000437 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
438 return AG->begin();
439 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000440
Chandler Carruth63559d72015-09-13 06:47:20 +0000441 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
442};
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000443
444} // end namespace llvm
Nick Lewycky4c378a42011-12-28 23:24:21 +0000445
Chandler Carrutha632fb92015-09-13 06:57:25 +0000446/// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000447static Attribute::AttrKind
448determinePointerReadAttrs(Argument *A,
Chandler Carruth63559d72015-09-13 06:47:20 +0000449 const SmallPtrSet<Argument *, 8> &SCCNodes) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000450 SmallVector<Use *, 32> Worklist;
Florian Hahna1cc8482018-06-12 11:16:56 +0000451 SmallPtrSet<Use *, 32> Visited;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000452
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000453 // inalloca arguments are always clobbered by the call.
454 if (A->hasInAllocaAttr())
455 return Attribute::None;
456
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000457 bool IsRead = false;
458 // We don't need to track IsWritten. If A is written to, return immediately.
459
Chandler Carruthcdf47882014-03-09 03:16:01 +0000460 for (Use &U : A->uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000461 Visited.insert(&U);
462 Worklist.push_back(&U);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000463 }
464
465 while (!Worklist.empty()) {
466 Use *U = Worklist.pop_back_val();
467 Instruction *I = cast<Instruction>(U->getUser());
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000468
469 switch (I->getOpcode()) {
470 case Instruction::BitCast:
471 case Instruction::GetElementPtr:
472 case Instruction::PHI:
473 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000474 case Instruction::AddrSpaceCast:
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000475 // The original value is not read/written via this if the new value isn't.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000476 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000477 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000478 Worklist.push_back(&UU);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000479 break;
480
481 case Instruction::Call:
482 case Instruction::Invoke: {
Nick Lewycky59633cb2014-05-30 02:31:27 +0000483 bool Captures = true;
484
485 if (I->getType()->isVoidTy())
486 Captures = false;
487
488 auto AddUsersToWorklistIfCapturing = [&] {
489 if (Captures)
490 for (Use &UU : I->uses())
David Blaikie70573dc2014-11-19 07:49:26 +0000491 if (Visited.insert(&UU).second)
Nick Lewycky59633cb2014-05-30 02:31:27 +0000492 Worklist.push_back(&UU);
493 };
494
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000495 CallSite CS(I);
Nick Lewycky59633cb2014-05-30 02:31:27 +0000496 if (CS.doesNotAccessMemory()) {
497 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000498 continue;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000499 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000500
501 Function *F = CS.getCalledFunction();
502 if (!F) {
503 if (CS.onlyReadsMemory()) {
504 IsRead = true;
Nick Lewycky59633cb2014-05-30 02:31:27 +0000505 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000506 continue;
507 }
508 return Attribute::None;
509 }
510
Sanjoy Das436e2392015-11-07 01:55:53 +0000511 // Note: the callee and the two successor blocks *follow* the argument
512 // operands. This means there is no need to adjust UseIndex to account
513 // for these.
514
515 unsigned UseIndex = std::distance(CS.arg_begin(), U);
516
Sanjoy Dasea1df7f2015-11-07 01:56:07 +0000517 // U cannot be the callee operand use: since we're exploring the
518 // transitive uses of an Argument, having such a use be a callee would
519 // imply the CallSite is an indirect call or invoke; and we'd take the
520 // early exit above.
521 assert(UseIndex < CS.data_operands_size() &&
522 "Data operand use expected!");
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000523
524 bool IsOperandBundleUse = UseIndex >= CS.getNumArgOperands();
525
526 if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
Sanjoy Das436e2392015-11-07 01:55:53 +0000527 assert(F->isVarArg() && "More params than args in non-varargs call");
528 return Attribute::None;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000529 }
Sanjoy Das436e2392015-11-07 01:55:53 +0000530
Tilmann Scheller925b1932015-11-20 19:17:10 +0000531 Captures &= !CS.doesNotCapture(UseIndex);
532
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000533 // Since the optimizer (by design) cannot see the data flow corresponding
534 // to a operand bundle use, these cannot participate in the optimistic SCC
535 // analysis. Instead, we model the operand bundle uses as arguments in
536 // call to a function external to the SCC.
Duncan P. N. Exon Smith9e3edad2016-08-17 01:23:58 +0000537 if (IsOperandBundleUse ||
538 !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
Sanjoy Das71fe81f2015-11-07 01:56:00 +0000539
540 // The accessors used on CallSite here do the right thing for calls and
541 // invokes with operand bundles.
542
Sanjoy Das436e2392015-11-07 01:55:53 +0000543 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
544 return Attribute::None;
545 if (!CS.doesNotAccessMemory(UseIndex))
546 IsRead = true;
547 }
548
Nick Lewycky59633cb2014-05-30 02:31:27 +0000549 AddUsersToWorklistIfCapturing();
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000550 break;
551 }
552
553 case Instruction::Load:
David Majnemer124bdb72016-05-25 05:53:04 +0000554 // A volatile load has side effects beyond what readonly can be relied
555 // upon.
556 if (cast<LoadInst>(I)->isVolatile())
557 return Attribute::None;
558
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000559 IsRead = true;
560 break;
561
562 case Instruction::ICmp:
563 case Instruction::Ret:
564 break;
565
566 default:
567 return Attribute::None;
568 }
569 }
570
571 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
572}
573
David Majnemer5246e0b2016-07-19 18:50:26 +0000574/// Deduce returned attributes for the SCC.
575static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
576 bool Changed = false;
577
David Majnemer5246e0b2016-07-19 18:50:26 +0000578 // Check each function in turn, determining if an argument is always returned.
579 for (Function *F : SCCNodes) {
580 // We can infer and propagate function attributes only when we know that the
581 // definition we'll get at link time is *exactly* the definition we see now.
582 // For more details, see GlobalValue::mayBeDerefined.
583 if (!F->hasExactDefinition())
584 continue;
585
586 if (F->getReturnType()->isVoidTy())
587 continue;
588
David Majnemerc83044d2016-09-12 16:04:59 +0000589 // There is nothing to do if an argument is already marked as 'returned'.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000590 if (llvm::any_of(F->args(),
591 [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
David Majnemerc83044d2016-09-12 16:04:59 +0000592 continue;
593
David Majnemer5246e0b2016-07-19 18:50:26 +0000594 auto FindRetArg = [&]() -> Value * {
595 Value *RetArg = nullptr;
596 for (BasicBlock &BB : *F)
597 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
598 // Note that stripPointerCasts should look through functions with
599 // returned arguments.
600 Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
601 if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
602 return nullptr;
603
604 if (!RetArg)
605 RetArg = RetVal;
606 else if (RetArg != RetVal)
607 return nullptr;
608 }
609
610 return RetArg;
611 };
612
613 if (Value *RetArg = FindRetArg()) {
614 auto *A = cast<Argument>(RetArg);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000615 A->addAttr(Attribute::Returned);
David Majnemer5246e0b2016-07-19 18:50:26 +0000616 ++NumReturned;
617 Changed = true;
618 }
619 }
620
621 return Changed;
622}
623
Sanjay Patel4f742162017-02-13 23:10:51 +0000624/// If a callsite has arguments that are also arguments to the parent function,
625/// try to propagate attributes from the callsite's arguments to the parent's
626/// arguments. This may be important because inlining can cause information loss
627/// when attribute knowledge disappears with the inlined call.
628static bool addArgumentAttrsFromCallsites(Function &F) {
629 if (!EnableNonnullArgPropagation)
630 return false;
631
632 bool Changed = false;
633
634 // For an argument attribute to transfer from a callsite to the parent, the
635 // call must be guaranteed to execute every time the parent is called.
636 // Conservatively, just check for calls in the entry block that are guaranteed
637 // to execute.
638 // TODO: This could be enhanced by testing if the callsite post-dominates the
639 // entry block or by doing simple forward walks or backward walks to the
640 // callsite.
641 BasicBlock &Entry = F.getEntryBlock();
642 for (Instruction &I : Entry) {
643 if (auto CS = CallSite(&I)) {
644 if (auto *CalledFunc = CS.getCalledFunction()) {
645 for (auto &CSArg : CalledFunc->args()) {
646 if (!CSArg.hasNonNullAttr())
647 continue;
648
649 // If the non-null callsite argument operand is an argument to 'F'
650 // (the caller) and the call is guaranteed to execute, then the value
651 // must be non-null throughout 'F'.
652 auto *FArg = dyn_cast<Argument>(CS.getArgOperand(CSArg.getArgNo()));
653 if (FArg && !FArg->hasNonNullAttr()) {
654 FArg->addAttr(Attribute::NonNull);
655 Changed = true;
656 }
657 }
658 }
659 }
660 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
661 break;
662 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000663
Sanjay Patel4f742162017-02-13 23:10:51 +0000664 return Changed;
665}
666
Whitney Tsang1ccba7c2019-09-11 14:26:22 +0000667static bool addReadAttr(Argument *A, Attribute::AttrKind R) {
668 assert((R == Attribute::ReadOnly || R == Attribute::ReadNone)
669 && "Must be a Read attribute.");
670 assert(A && "Argument must not be null.");
671
672 // If the argument already has the attribute, nothing needs to be done.
673 if (A->hasAttribute(R))
674 return false;
675
676 // Otherwise, remove potentially conflicting attribute, add the new one,
677 // and update statistics.
678 A->removeAttr(Attribute::WriteOnly);
679 A->removeAttr(Attribute::ReadOnly);
680 A->removeAttr(Attribute::ReadNone);
681 A->addAttr(R);
682 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
683 return true;
684}
685
Chandler Carrutha632fb92015-09-13 06:57:25 +0000686/// Deduce nocapture attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000687static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
Duncan Sands44c8cd92008-12-31 16:14:43 +0000688 bool Changed = false;
689
Nick Lewycky4c378a42011-12-28 23:24:21 +0000690 ArgumentGraph AG;
691
Duncan Sands44c8cd92008-12-31 16:14:43 +0000692 // Check each function in turn, determining which pointer arguments are not
693 // captured.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000694 for (Function *F : SCCNodes) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000695 // We can infer and propagate function attributes only when we know that the
696 // definition we'll get at link time is *exactly* the definition we see now.
697 // For more details, see GlobalValue::mayBeDerefined.
698 if (!F->hasExactDefinition())
Duncan Sands44c8cd92008-12-31 16:14:43 +0000699 continue;
700
Sanjay Patel4f742162017-02-13 23:10:51 +0000701 Changed |= addArgumentAttrsFromCallsites(*F);
702
Nick Lewycky4c378a42011-12-28 23:24:21 +0000703 // Functions that are readonly (or readnone) and nounwind and don't return
704 // a value can't capture arguments. Don't analyze them.
705 if (F->onlyReadsMemory() && F->doesNotThrow() &&
706 F->getReturnType()->isVoidTy()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000707 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
708 ++A) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000709 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000710 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000711 ++NumNoCapture;
712 Changed = true;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000713 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000714 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000715 continue;
Benjamin Kramer76b7bd02013-06-22 15:51:19 +0000716 }
717
Chandler Carruth63559d72015-09-13 06:47:20 +0000718 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
719 ++A) {
720 if (!A->getType()->isPointerTy())
721 continue;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000722 bool HasNonLocalUses = false;
723 if (!A->hasNoCaptureAttr()) {
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000724 ArgumentUsesTracker Tracker(SCCNodes);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000725 PointerMayBeCaptured(&*A, &Tracker);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000726 if (!Tracker.Captured) {
727 if (Tracker.Uses.empty()) {
728 // If it's trivially not captured, mark it nocapture now.
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000729 A->addAttr(Attribute::NoCapture);
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000730 ++NumNoCapture;
731 Changed = true;
732 } else {
733 // If it's not trivially captured and not trivially not captured,
734 // then it must be calling into another function in our SCC. Save
735 // its particulars for Argument-SCC analysis later.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000736 ArgumentGraphNode *Node = AG[&*A];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000737 for (Argument *Use : Tracker.Uses) {
738 Node->Uses.push_back(AG[Use]);
739 if (Use != &*A)
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000740 HasNonLocalUses = true;
741 }
Benjamin Kramer40d7f352013-06-22 16:56:32 +0000742 }
743 }
744 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
745 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000746 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
747 // Can we determine that it's readonly/readnone without doing an SCC?
748 // Note that we don't allow any calls at all here, or else our result
749 // will be dependent on the iteration order through the functions in the
750 // SCC.
Chandler Carruth63559d72015-09-13 06:47:20 +0000751 SmallPtrSet<Argument *, 8> Self;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000752 Self.insert(&*A);
753 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
Whitney Tsang1ccba7c2019-09-11 14:26:22 +0000754 if (R != Attribute::None)
755 Changed = addReadAttr(A, R);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000756 }
757 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000758 }
759
760 // The graph we've collected is partial because we stopped scanning for
761 // argument uses once we solved the argument trivially. These partial nodes
762 // show up as ArgumentGraphNode objects with an empty Uses list, and for
763 // these nodes the final decision about whether they capture has already been
764 // made. If the definition doesn't have a 'nocapture' attribute by now, it
765 // captures.
766
Chandler Carruth63559d72015-09-13 06:47:20 +0000767 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000768 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000769 if (ArgumentSCC.size() == 1) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000770 if (!ArgumentSCC[0]->Definition)
771 continue; // synthetic root node
Nick Lewycky4c378a42011-12-28 23:24:21 +0000772
773 // eg. "void f(int* x) { if (...) f(x); }"
774 if (ArgumentSCC[0]->Uses.size() == 1 &&
775 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000776 Argument *A = ArgumentSCC[0]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000777 A->addAttr(Attribute::NoCapture);
Nick Lewycky7e820552009-01-02 03:46:56 +0000778 ++NumNoCapture;
Duncan Sands44c8cd92008-12-31 16:14:43 +0000779 Changed = true;
780 }
Nick Lewycky4c378a42011-12-28 23:24:21 +0000781 continue;
782 }
783
784 bool SCCCaptured = false;
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000785 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
786 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000787 ArgumentGraphNode *Node = *I;
788 if (Node->Uses.empty()) {
789 if (!Node->Definition->hasNoCaptureAttr())
790 SCCCaptured = true;
791 }
792 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000793 if (SCCCaptured)
794 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000795
Chandler Carruth63559d72015-09-13 06:47:20 +0000796 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000797 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
798 // quickly looking up whether a given Argument is in this ArgumentSCC.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000799 for (ArgumentGraphNode *I : ArgumentSCC) {
800 ArgumentSCCNodes.insert(I->Definition);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000801 }
802
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000803 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
804 I != E && !SCCCaptured; ++I) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000805 ArgumentGraphNode *N = *I;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000806 for (ArgumentGraphNode *Use : N->Uses) {
807 Argument *A = Use->Definition;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000808 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
809 continue;
810 SCCCaptured = true;
811 break;
812 }
813 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000814 if (SCCCaptured)
815 continue;
Nick Lewycky4c378a42011-12-28 23:24:21 +0000816
Nick Lewyckyf740db32012-01-05 22:21:45 +0000817 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
Nick Lewycky4c378a42011-12-28 23:24:21 +0000818 Argument *A = ArgumentSCC[i]->Definition;
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000819 A->addAttr(Attribute::NoCapture);
Nick Lewycky4c378a42011-12-28 23:24:21 +0000820 ++NumNoCapture;
821 Changed = true;
822 }
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000823
824 // We also want to compute readonly/readnone. With a small number of false
825 // negatives, we can assume that any pointer which is captured isn't going
826 // to be provably readonly or readnone, since by definition we can't
827 // analyze all uses of a captured pointer.
828 //
829 // The false negatives happen when the pointer is captured by a function
830 // that promises readonly/readnone behaviour on the pointer, then the
831 // pointer's lifetime ends before anything that writes to arbitrary memory.
832 // Also, a readonly/readnone pointer may be returned, but returning a
833 // pointer is capturing it.
834
835 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
836 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
837 Argument *A = ArgumentSCC[i]->Definition;
838 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
839 if (K == Attribute::ReadNone)
840 continue;
841 if (K == Attribute::ReadOnly) {
842 ReadAttr = Attribute::ReadOnly;
843 continue;
844 }
845 ReadAttr = K;
846 break;
847 }
848
849 if (ReadAttr != Attribute::None) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000850 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
851 Argument *A = ArgumentSCC[i]->Definition;
Whitney Tsang1ccba7c2019-09-11 14:26:22 +0000852 Changed = addReadAttr(A, ReadAttr);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000853 }
854 }
Duncan Sands44c8cd92008-12-31 16:14:43 +0000855 }
856
857 return Changed;
858}
859
Chandler Carrutha632fb92015-09-13 06:57:25 +0000860/// Tests whether a function is "malloc-like".
861///
862/// A function is "malloc-like" if it returns either null or a pointer that
863/// doesn't alias any other pointer visible to the caller.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000864static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000865 SmallSetVector<Value *, 8> FlowsToReturn;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000866 for (BasicBlock &BB : *F)
867 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000868 FlowsToReturn.insert(Ret->getReturnValue());
869
870 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
Benjamin Kramer15591272012-10-31 13:45:49 +0000871 Value *RetVal = FlowsToReturn[i];
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000872
873 if (Constant *C = dyn_cast<Constant>(RetVal)) {
874 if (!C->isNullValue() && !isa<UndefValue>(C))
875 return false;
876
877 continue;
878 }
879
880 if (isa<Argument>(RetVal))
881 return false;
882
883 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
884 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000885 // Extend the analysis by looking upwards.
886 case Instruction::BitCast:
887 case Instruction::GetElementPtr:
888 case Instruction::AddrSpaceCast:
889 FlowsToReturn.insert(RVI->getOperand(0));
890 continue;
891 case Instruction::Select: {
892 SelectInst *SI = cast<SelectInst>(RVI);
893 FlowsToReturn.insert(SI->getTrueValue());
894 FlowsToReturn.insert(SI->getFalseValue());
895 continue;
896 }
897 case Instruction::PHI: {
898 PHINode *PN = cast<PHINode>(RVI);
899 for (Value *IncValue : PN->incoming_values())
900 FlowsToReturn.insert(IncValue);
901 continue;
902 }
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000903
Chandler Carruth63559d72015-09-13 06:47:20 +0000904 // Check whether the pointer came from an allocation.
905 case Instruction::Alloca:
906 break;
907 case Instruction::Call:
908 case Instruction::Invoke: {
909 CallSite CS(RVI);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000910 if (CS.hasRetAttr(Attribute::NoAlias))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000911 break;
Chandler Carruth63559d72015-09-13 06:47:20 +0000912 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
913 break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000914 LLVM_FALLTHROUGH;
915 }
Chandler Carruth63559d72015-09-13 06:47:20 +0000916 default:
917 return false; // Did not come from an allocation.
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000918 }
919
Dan Gohman94e61762009-11-19 21:57:48 +0000920 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000921 return false;
922 }
923
924 return true;
925}
926
Chandler Carrutha632fb92015-09-13 06:57:25 +0000927/// Deduce noalias attributes for the SCC.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000928static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
Nick Lewycky9ec96d12009-03-08 17:08:09 +0000929 // Check each function in turn, determining which functions return noalias
930 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000931 for (Function *F : SCCNodes) {
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000932 // Already noalias.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000933 if (F->returnDoesNotAlias())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000934 continue;
935
Sanjoy Das5ce32722016-04-08 00:48:30 +0000936 // We can infer and propagate function attributes only when we know that the
937 // definition we'll get at link time is *exactly* the definition we see now.
938 // For more details, see GlobalValue::mayBeDerefined.
939 if (!F->hasExactDefinition())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000940 return false;
941
Chandler Carruth63559d72015-09-13 06:47:20 +0000942 // We annotate noalias return values, which are only applicable to
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000943 // pointer types.
Duncan Sands19d0b472010-02-16 11:11:14 +0000944 if (!F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000945 continue;
946
Chandler Carruth3824f852015-09-13 08:23:27 +0000947 if (!isFunctionMallocLike(F, SCCNodes))
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000948 return false;
949 }
950
951 bool MadeChange = false;
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000952 for (Function *F : SCCNodes) {
Reid Klecknera0b45f42017-05-03 18:17:31 +0000953 if (F->returnDoesNotAlias() ||
Reid Kleckner6652a522017-04-28 18:37:16 +0000954 !F->getReturnType()->isPointerTy())
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000955 continue;
956
Reid Klecknera0b45f42017-05-03 18:17:31 +0000957 F->setReturnDoesNotAlias();
Nick Lewyckyfbed86a2009-03-08 06:20:47 +0000958 ++NumNoAlias;
959 MadeChange = true;
960 }
961
962 return MadeChange;
963}
964
Chandler Carrutha632fb92015-09-13 06:57:25 +0000965/// Tests whether this function is known to not return null.
Chandler Carruth8874b782015-09-13 08:17:14 +0000966///
967/// Requires that the function returns a pointer.
968///
969/// Returns true if it believes the function will not return a null, and sets
970/// \p Speculative based on whether the returned conclusion is a speculative
971/// conclusion due to SCC calls.
Chandler Carruthc518ebd2015-10-29 18:29:15 +0000972static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
Sean Silva45835e72016-07-02 23:47:27 +0000973 bool &Speculative) {
Philip Reamesa88caea2015-08-31 19:44:38 +0000974 assert(F->getReturnType()->isPointerTy() &&
975 "nonnull only meaningful on pointer types");
976 Speculative = false;
Chandler Carruth63559d72015-09-13 06:47:20 +0000977
Philip Reamesa88caea2015-08-31 19:44:38 +0000978 SmallSetVector<Value *, 8> FlowsToReturn;
979 for (BasicBlock &BB : *F)
980 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
981 FlowsToReturn.insert(Ret->getReturnValue());
982
Nuno Lopes404f1062017-09-09 18:23:11 +0000983 auto &DL = F->getParent()->getDataLayout();
984
Philip Reamesa88caea2015-08-31 19:44:38 +0000985 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
986 Value *RetVal = FlowsToReturn[i];
987
988 // If this value is locally known to be non-null, we're good
Nuno Lopes404f1062017-09-09 18:23:11 +0000989 if (isKnownNonZero(RetVal, DL))
Philip Reamesa88caea2015-08-31 19:44:38 +0000990 continue;
991
992 // Otherwise, we need to look upwards since we can't make any local
Chandler Carruth63559d72015-09-13 06:47:20 +0000993 // conclusions.
Philip Reamesa88caea2015-08-31 19:44:38 +0000994 Instruction *RVI = dyn_cast<Instruction>(RetVal);
995 if (!RVI)
996 return false;
997 switch (RVI->getOpcode()) {
Chandler Carruth63559d72015-09-13 06:47:20 +0000998 // Extend the analysis by looking upwards.
Philip Reamesa88caea2015-08-31 19:44:38 +0000999 case Instruction::BitCast:
1000 case Instruction::GetElementPtr:
1001 case Instruction::AddrSpaceCast:
1002 FlowsToReturn.insert(RVI->getOperand(0));
1003 continue;
1004 case Instruction::Select: {
1005 SelectInst *SI = cast<SelectInst>(RVI);
1006 FlowsToReturn.insert(SI->getTrueValue());
1007 FlowsToReturn.insert(SI->getFalseValue());
1008 continue;
1009 }
1010 case Instruction::PHI: {
1011 PHINode *PN = cast<PHINode>(RVI);
1012 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1013 FlowsToReturn.insert(PN->getIncomingValue(i));
1014 continue;
1015 }
1016 case Instruction::Call:
1017 case Instruction::Invoke: {
1018 CallSite CS(RVI);
1019 Function *Callee = CS.getCalledFunction();
1020 // A call to a node within the SCC is assumed to return null until
1021 // proven otherwise
1022 if (Callee && SCCNodes.count(Callee)) {
1023 Speculative = true;
1024 continue;
1025 }
1026 return false;
1027 }
1028 default:
Chandler Carruth63559d72015-09-13 06:47:20 +00001029 return false; // Unknown source, may be null
Philip Reamesa88caea2015-08-31 19:44:38 +00001030 };
1031 llvm_unreachable("should have either continued or returned");
1032 }
1033
1034 return true;
1035}
1036
Chandler Carrutha632fb92015-09-13 06:57:25 +00001037/// Deduce nonnull attributes for the SCC.
Sean Silva45835e72016-07-02 23:47:27 +00001038static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001039 // Speculative that all functions in the SCC return only nonnull
1040 // pointers. We may refute this as we analyze functions.
1041 bool SCCReturnsNonNull = true;
1042
1043 bool MadeChange = false;
1044
1045 // Check each function in turn, determining which functions return nonnull
1046 // pointers.
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001047 for (Function *F : SCCNodes) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001048 // Already nonnull.
Reid Klecknerb5180542017-03-21 16:57:19 +00001049 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001050 Attribute::NonNull))
1051 continue;
1052
Sanjoy Das5ce32722016-04-08 00:48:30 +00001053 // We can infer and propagate function attributes only when we know that the
1054 // definition we'll get at link time is *exactly* the definition we see now.
1055 // For more details, see GlobalValue::mayBeDerefined.
1056 if (!F->hasExactDefinition())
Philip Reamesa88caea2015-08-31 19:44:38 +00001057 return false;
1058
Chandler Carruth63559d72015-09-13 06:47:20 +00001059 // We annotate nonnull return values, which are only applicable to
Philip Reamesa88caea2015-08-31 19:44:38 +00001060 // pointer types.
1061 if (!F->getReturnType()->isPointerTy())
1062 continue;
1063
1064 bool Speculative = false;
Sean Silva45835e72016-07-02 23:47:27 +00001065 if (isReturnNonNull(F, SCCNodes, Speculative)) {
Philip Reamesa88caea2015-08-31 19:44:38 +00001066 if (!Speculative) {
1067 // Mark the function eagerly since we may discover a function
1068 // which prevents us from speculating about the entire SCC
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001069 LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1070 << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001071 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001072 ++NumNonNullReturn;
1073 MadeChange = true;
1074 }
1075 continue;
1076 }
1077 // At least one function returns something which could be null, can't
1078 // speculate any more.
1079 SCCReturnsNonNull = false;
1080 }
1081
1082 if (SCCReturnsNonNull) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001083 for (Function *F : SCCNodes) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001084 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Philip Reamesa88caea2015-08-31 19:44:38 +00001085 Attribute::NonNull) ||
1086 !F->getReturnType()->isPointerTy())
1087 continue;
1088
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001089 LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
Reid Klecknerb5180542017-03-21 16:57:19 +00001090 F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesa88caea2015-08-31 19:44:38 +00001091 ++NumNonNullReturn;
1092 MadeChange = true;
1093 }
1094 }
1095
1096 return MadeChange;
1097}
1098
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001099namespace {
1100
1101/// Collects a set of attribute inference requests and performs them all in one
1102/// go on a single SCC Node. Inference involves scanning function bodies
1103/// looking for instructions that violate attribute assumptions.
1104/// As soon as all the bodies are fine we are free to set the attribute.
1105/// Customization of inference for individual attributes is performed by
1106/// providing a handful of predicates for each attribute.
1107class AttributeInferer {
1108public:
1109 /// Describes a request for inference of a single attribute.
1110 struct InferenceDescriptor {
1111
1112 /// Returns true if this function does not have to be handled.
1113 /// General intent for this predicate is to provide an optimization
1114 /// for functions that do not need this attribute inference at all
1115 /// (say, for functions that already have the attribute).
1116 std::function<bool(const Function &)> SkipFunction;
1117
1118 /// Returns true if this instruction violates attribute assumptions.
1119 std::function<bool(Instruction &)> InstrBreaksAttribute;
1120
1121 /// Sets the inferred attribute for this function.
1122 std::function<void(Function &)> SetAttribute;
1123
1124 /// Attribute we derive.
1125 Attribute::AttrKind AKind;
1126
1127 /// If true, only "exact" definitions can be used to infer this attribute.
1128 /// See GlobalValue::isDefinitionExact.
1129 bool RequiresExactDefinition;
1130
1131 InferenceDescriptor(Attribute::AttrKind AK,
1132 std::function<bool(const Function &)> SkipFunc,
1133 std::function<bool(Instruction &)> InstrScan,
1134 std::function<void(Function &)> SetAttr,
1135 bool ReqExactDef)
1136 : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1137 SetAttribute(SetAttr), AKind(AK),
1138 RequiresExactDefinition(ReqExactDef) {}
1139 };
1140
1141private:
1142 SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1143
1144public:
1145 void registerAttrInference(InferenceDescriptor AttrInference) {
1146 InferenceDescriptors.push_back(AttrInference);
1147 }
1148
1149 bool run(const SCCNodeSet &SCCNodes);
1150};
1151
1152/// Perform all the requested attribute inference actions according to the
1153/// attribute predicates stored before.
1154bool AttributeInferer::run(const SCCNodeSet &SCCNodes) {
1155 SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1156 // Go through all the functions in SCC and check corresponding attribute
1157 // assumptions for each of them. Attributes that are invalid for this SCC
1158 // will be removed from InferInSCC.
Chandler Carruth3937bc72016-02-12 09:47:49 +00001159 for (Function *F : SCCNodes) {
Justin Lebar9d943972016-03-14 20:18:54 +00001160
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001161 // No attributes whose assumptions are still valid - done.
1162 if (InferInSCC.empty())
1163 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001164
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001165 // Check if our attributes ever need scanning/can be scanned.
1166 llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1167 if (ID.SkipFunction(*F))
Justin Lebar9d943972016-03-14 20:18:54 +00001168 return false;
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001169
1170 // Remove from further inference (invalidate) when visiting a function
1171 // that has no instructions to scan/has an unsuitable definition.
1172 return F->isDeclaration() ||
1173 (ID.RequiresExactDefinition && !F->hasExactDefinition());
1174 });
1175
1176 // For each attribute still in InferInSCC that doesn't explicitly skip F,
1177 // set up the F instructions scan to verify assumptions of the attribute.
1178 SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1179 llvm::copy_if(
1180 InferInSCC, std::back_inserter(InferInThisFunc),
1181 [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1182
1183 if (InferInThisFunc.empty())
1184 continue;
1185
1186 // Start instruction scan.
1187 for (Instruction &I : instructions(*F)) {
1188 llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1189 if (!ID.InstrBreaksAttribute(I))
1190 return false;
1191 // Remove attribute from further inference on any other functions
1192 // because attribute assumptions have just been violated.
1193 llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1194 return D.AKind == ID.AKind;
1195 });
1196 // Remove attribute from the rest of current instruction scan.
1197 return true;
1198 });
1199
1200 if (InferInThisFunc.empty())
1201 break;
Justin Lebar9d943972016-03-14 20:18:54 +00001202 }
1203 }
1204
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001205 if (InferInSCC.empty())
1206 return false;
Justin Lebar9d943972016-03-14 20:18:54 +00001207
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001208 bool Changed = false;
1209 for (Function *F : SCCNodes)
1210 // At this point InferInSCC contains only functions that were either:
1211 // - explicitly skipped from scan/inference, or
1212 // - verified to have no instructions that break attribute assumptions.
1213 // Hence we just go and force the attribute for all non-skipped functions.
1214 for (auto &ID : InferInSCC) {
1215 if (ID.SkipFunction(*F))
1216 continue;
1217 Changed = true;
1218 ID.SetAttribute(*F);
1219 }
1220 return Changed;
1221}
Justin Lebar9d943972016-03-14 20:18:54 +00001222
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001223} // end anonymous namespace
1224
1225/// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1226static bool InstrBreaksNonConvergent(Instruction &I,
1227 const SCCNodeSet &SCCNodes) {
1228 const CallSite CS(&I);
1229 // Breaks non-convergent assumption if CS is a convergent call to a function
1230 // not in the SCC.
1231 return CS && CS.isConvergent() && SCCNodes.count(CS.getCalledFunction()) == 0;
1232}
1233
1234/// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1235static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1236 if (!I.mayThrow())
1237 return false;
1238 if (const auto *CI = dyn_cast<CallInst>(&I)) {
1239 if (Function *Callee = CI->getCalledFunction()) {
1240 // I is a may-throw call to a function inside our SCC. This doesn't
1241 // invalidate our current working assumption that the SCC is no-throw; we
1242 // just have to scan that other function.
1243 if (SCCNodes.count(Callee) > 0)
1244 return false;
1245 }
Chandler Carruth3937bc72016-02-12 09:47:49 +00001246 }
Justin Lebar260854b2016-02-09 23:03:22 +00001247 return true;
1248}
1249
Brian Homerdingb4b21d82019-07-08 15:57:56 +00001250/// Helper for NoFree inference predicate InstrBreaksAttribute.
1251static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes) {
1252 CallSite CS(&I);
1253 if (!CS)
1254 return false;
1255
1256 Function *Callee = CS.getCalledFunction();
1257 if (!Callee)
1258 return true;
1259
1260 if (Callee->doesNotFreeMemory())
1261 return false;
1262
1263 if (SCCNodes.count(Callee) > 0)
1264 return false;
1265
1266 return true;
1267}
1268
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001269/// Infer attributes from all functions in the SCC by scanning every
1270/// instruction for compliance to the attribute assumptions. Currently it
1271/// does:
1272/// - removal of Convergent attribute
1273/// - addition of NoUnwind attribute
1274///
1275/// Returns true if any changes to function attributes were made.
1276static bool inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes) {
1277
1278 AttributeInferer AI;
1279
1280 // Request to remove the convergent attribute from all functions in the SCC
1281 // if every callsite within the SCC is not convergent (except for calls
1282 // to functions within the SCC).
1283 // Note: Removal of the attr from the callsites will happen in
1284 // InstCombineCalls separately.
1285 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1286 Attribute::Convergent,
1287 // Skip non-convergent functions.
1288 [](const Function &F) { return !F.isConvergent(); },
1289 // Instructions that break non-convergent assumption.
1290 [SCCNodes](Instruction &I) {
1291 return InstrBreaksNonConvergent(I, SCCNodes);
1292 },
1293 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001294 LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1295 << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001296 F.setNotConvergent();
1297 },
1298 /* RequiresExactDefinition= */ false});
1299
1300 if (!DisableNoUnwindInference)
1301 // Request to infer nounwind attribute for all the functions in the SCC if
1302 // every callsite within the SCC is not throwing (except for calls to
1303 // functions within the SCC). Note that nounwind attribute suffers from
1304 // derefinement - results may change depending on how functions are
1305 // optimized. Thus it can be inferred only from exact definitions.
1306 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1307 Attribute::NoUnwind,
1308 // Skip non-throwing functions.
1309 [](const Function &F) { return F.doesNotThrow(); },
1310 // Instructions that break non-throwing assumption.
1311 [SCCNodes](Instruction &I) {
1312 return InstrBreaksNonThrowing(I, SCCNodes);
1313 },
1314 [](Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001315 LLVM_DEBUG(dbgs()
1316 << "Adding nounwind attr to fn " << F.getName() << "\n");
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001317 F.setDoesNotThrow();
1318 ++NumNoUnwind;
1319 },
1320 /* RequiresExactDefinition= */ true});
1321
Brian Homerdingb4b21d82019-07-08 15:57:56 +00001322 if (!DisableNoFreeInference)
1323 // Request to infer nofree attribute for all the functions in the SCC if
1324 // every callsite within the SCC does not directly or indirectly free
1325 // memory (except for calls to functions within the SCC). Note that nofree
1326 // attribute suffers from derefinement - results may change depending on
1327 // how functions are optimized. Thus it can be inferred only from exact
1328 // definitions.
1329 AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1330 Attribute::NoFree,
1331 // Skip functions known not to free memory.
1332 [](const Function &F) { return F.doesNotFreeMemory(); },
1333 // Instructions that break non-deallocating assumption.
1334 [SCCNodes](Instruction &I) {
1335 return InstrBreaksNoFree(I, SCCNodes);
1336 },
1337 [](Function &F) {
1338 LLVM_DEBUG(dbgs()
1339 << "Adding nofree attr to fn " << F.getName() << "\n");
1340 F.setDoesNotFreeMemory();
1341 ++NumNoFree;
1342 },
1343 /* RequiresExactDefinition= */ true});
1344
Fedor Sergeev6660fd02018-03-23 21:46:16 +00001345 // Perform all the requested attribute inference actions.
1346 return AI.run(SCCNodes);
1347}
1348
James Molloy7e9bdd52015-11-12 10:55:20 +00001349static bool setDoesNotRecurse(Function &F) {
1350 if (F.doesNotRecurse())
1351 return false;
1352 F.setDoesNotRecurse();
1353 ++NumNoRecurse;
1354 return true;
1355}
1356
Chandler Carruth632d2082016-02-13 08:47:51 +00001357static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
James Molloy7e9bdd52015-11-12 10:55:20 +00001358 // Try and identify functions that do not recurse.
1359
1360 // If the SCC contains multiple nodes we know for sure there is recursion.
Chandler Carruth632d2082016-02-13 08:47:51 +00001361 if (SCCNodes.size() != 1)
James Molloy7e9bdd52015-11-12 10:55:20 +00001362 return false;
1363
Chandler Carruth632d2082016-02-13 08:47:51 +00001364 Function *F = *SCCNodes.begin();
Vivek Pandya11cb15f2019-06-10 04:16:04 +00001365 if (!F || !F->hasExactDefinition() || F->doesNotRecurse())
James Molloy7e9bdd52015-11-12 10:55:20 +00001366 return false;
1367
1368 // If all of the calls in F are identifiable and are to norecurse functions, F
1369 // is norecurse. This check also detects self-recursion as F is not currently
1370 // marked norecurse, so any called from F to F will not be marked norecurse.
Christian Bruel4ead99b2018-12-05 16:48:00 +00001371 for (auto &BB : *F)
1372 for (auto &I : BB.instructionsWithoutDebug())
1373 if (auto CS = CallSite(&I)) {
1374 Function *Callee = CS.getCalledFunction();
1375 if (!Callee || Callee == F || !Callee->doesNotRecurse())
1376 // Function calls a potentially recursive function.
1377 return false;
1378 }
James Molloy7e9bdd52015-11-12 10:55:20 +00001379
Chandler Carruth632d2082016-02-13 08:47:51 +00001380 // Every call was to a non-recursive function other than this function, and
1381 // we have no indirect recursion as the SCC size is one. This function cannot
1382 // recurse.
1383 return setDoesNotRecurse(*F);
James Molloy7e9bdd52015-11-12 10:55:20 +00001384}
1385
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001386template <typename AARGetterT>
Brian Homerdingb4b21d82019-07-08 15:57:56 +00001387static bool deriveAttrsInPostOrder(SCCNodeSet &SCCNodes,
1388 AARGetterT &&AARGetter,
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001389 bool HasUnknownCall) {
1390 bool Changed = false;
1391
1392 // Bail if the SCC only contains optnone functions.
1393 if (SCCNodes.empty())
1394 return Changed;
1395
1396 Changed |= addArgumentReturnedAttrs(SCCNodes);
1397 Changed |= addReadAttrs(SCCNodes, AARGetter);
1398 Changed |= addArgumentAttrs(SCCNodes);
1399
1400 // If we have no external nodes participating in the SCC, we can deduce some
1401 // more precise attributes as well.
1402 if (!HasUnknownCall) {
1403 Changed |= addNoAliasAttrs(SCCNodes);
1404 Changed |= addNonNullAttrs(SCCNodes);
1405 Changed |= inferAttrsFromFunctionBodies(SCCNodes);
1406 Changed |= addNoRecurseAttrs(SCCNodes);
1407 }
1408
1409 return Changed;
1410}
1411
Chandler Carruthb47f8012016-03-11 11:05:24 +00001412PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
Chandler Carruth88823462016-08-24 09:37:14 +00001413 CGSCCAnalysisManager &AM,
1414 LazyCallGraph &CG,
1415 CGSCCUpdateResult &) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001416 FunctionAnalysisManager &FAM =
Chandler Carruth88823462016-08-24 09:37:14 +00001417 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001418
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001419 // We pass a lambda into functions to wire them up to the analysis manager
1420 // for getting function analyses.
1421 auto AARGetter = [&](Function &F) -> AAResults & {
1422 return FAM.getResult<AAManager>(F);
1423 };
1424
1425 // Fill SCCNodes with the elements of the SCC. Also track whether there are
1426 // any external or opt-none nodes that will prevent us from optimizing any
1427 // part of the SCC.
1428 SCCNodeSet SCCNodes;
1429 bool HasUnknownCall = false;
1430 for (LazyCallGraph::Node &N : C) {
1431 Function &F = N.getFunction();
Evandro Menezes85bd3972019-04-04 22:40:06 +00001432 if (F.hasOptNone() || F.hasFnAttribute(Attribute::Naked)) {
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001433 // Treat any function we're trying not to optimize as if it were an
1434 // indirect call and omit it from the node set used below.
1435 HasUnknownCall = true;
1436 continue;
1437 }
1438 // Track whether any functions in this SCC have an unknown call edge.
1439 // Note: if this is ever a performance hit, we can common it with
1440 // subsequent routines which also do scans over the instructions of the
1441 // function.
1442 if (!HasUnknownCall)
1443 for (Instruction &I : instructions(F))
1444 if (auto CS = CallSite(&I))
1445 if (!CS.getCalledFunction()) {
1446 HasUnknownCall = true;
1447 break;
1448 }
1449
1450 SCCNodes.insert(&F);
1451 }
1452
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001453 if (deriveAttrsInPostOrder(SCCNodes, AARGetter, HasUnknownCall))
1454 return PreservedAnalyses::none();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001455
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001456 return PreservedAnalyses::all();
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001457}
1458
1459namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001460
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001461struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001462 // Pass identification, replacement for typeid
1463 static char ID;
1464
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001465 PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001466 initializePostOrderFunctionAttrsLegacyPassPass(
1467 *PassRegistry::getPassRegistry());
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001468 }
1469
1470 bool runOnSCC(CallGraphSCC &SCC) override;
1471
1472 void getAnalysisUsage(AnalysisUsage &AU) const override {
1473 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001474 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth12884f72016-03-02 15:56:53 +00001475 getAAResultsAnalysisUsage(AU);
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001476 CallGraphSCCPass::getAnalysisUsage(AU);
1477 }
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001478};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001479
1480} // end anonymous namespace
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001481
1482char PostOrderFunctionAttrsLegacyPass::ID = 0;
1483INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1484 "Deduce function attributes", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001485INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001486INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001487INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "functionattrs",
1488 "Deduce function attributes", false, false)
1489
Chad Rosier611b73b2016-11-07 16:28:04 +00001490Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1491 return new PostOrderFunctionAttrsLegacyPass();
1492}
Chandler Carruth9c4ed172016-02-18 11:03:11 +00001493
Sean Silva997cbea2016-07-03 03:35:03 +00001494template <typename AARGetterT>
1495static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001496
1497 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1498 // whether a given CallGraphNode is in this SCC. Also track whether there are
1499 // any external or opt-none nodes that will prevent us from optimizing any
1500 // part of the SCC.
1501 SCCNodeSet SCCNodes;
1502 bool ExternalNode = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001503 for (CallGraphNode *I : SCC) {
1504 Function *F = I->getFunction();
Evandro Menezes85bd3972019-04-04 22:40:06 +00001505 if (!F || F->hasOptNone() || F->hasFnAttribute(Attribute::Naked)) {
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001506 // External node or function we're trying not to optimize - we both avoid
1507 // transform them and avoid leveraging information they provide.
1508 ExternalNode = true;
1509 continue;
1510 }
1511
1512 SCCNodes.insert(F);
1513 }
1514
Johannes Doerfertbed4bab2018-08-01 16:37:51 +00001515 return deriveAttrsInPostOrder(SCCNodes, AARGetter, ExternalNode);
James Molloy7e9bdd52015-11-12 10:55:20 +00001516}
Chandler Carruthc518ebd2015-10-29 18:29:15 +00001517
Sean Silva997cbea2016-07-03 03:35:03 +00001518bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1519 if (skipSCC(SCC))
1520 return false;
Peter Collingbournecea1e4e2017-02-09 23:11:52 +00001521 return runImpl(SCC, LegacyAARGetter(*this));
Sean Silva997cbea2016-07-03 03:35:03 +00001522}
1523
Chandler Carruth1926b702016-01-08 10:55:52 +00001524namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001525
Sean Silvaf5080192016-06-12 07:48:51 +00001526struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001527 // Pass identification, replacement for typeid
1528 static char ID;
1529
Sean Silvaf5080192016-06-12 07:48:51 +00001530 ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
Chad Rosier611b73b2016-11-07 16:28:04 +00001531 initializeReversePostOrderFunctionAttrsLegacyPassPass(
1532 *PassRegistry::getPassRegistry());
Chandler Carruth1926b702016-01-08 10:55:52 +00001533 }
1534
1535 bool runOnModule(Module &M) override;
1536
1537 void getAnalysisUsage(AnalysisUsage &AU) const override {
1538 AU.setPreservesCFG();
1539 AU.addRequired<CallGraphWrapperPass>();
Mehdi Amini0ddf4042016-05-02 18:03:33 +00001540 AU.addPreserved<CallGraphWrapperPass>();
Chandler Carruth1926b702016-01-08 10:55:52 +00001541 }
1542};
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001543
1544} // end anonymous namespace
Chandler Carruth1926b702016-01-08 10:55:52 +00001545
Sean Silvaf5080192016-06-12 07:48:51 +00001546char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001547
Sean Silvaf5080192016-06-12 07:48:51 +00001548INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001549 "Deduce function attributes in RPO", false, false)
1550INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
Sean Silvaf5080192016-06-12 07:48:51 +00001551INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass, "rpo-functionattrs",
Chandler Carruth1926b702016-01-08 10:55:52 +00001552 "Deduce function attributes in RPO", false, false)
1553
1554Pass *llvm::createReversePostOrderFunctionAttrsPass() {
Sean Silvaf5080192016-06-12 07:48:51 +00001555 return new ReversePostOrderFunctionAttrsLegacyPass();
Chandler Carruth1926b702016-01-08 10:55:52 +00001556}
1557
1558static bool addNoRecurseAttrsTopDown(Function &F) {
1559 // We check the preconditions for the function prior to calling this to avoid
1560 // the cost of building up a reversible post-order list. We assert them here
1561 // to make sure none of the invariants this relies on were violated.
1562 assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1563 assert(!F.doesNotRecurse() &&
1564 "This function has already been deduced as norecurs!");
1565 assert(F.hasInternalLinkage() &&
1566 "Can only do top-down deduction for internal linkage functions!");
1567
1568 // If F is internal and all of its uses are calls from a non-recursive
1569 // functions, then none of its calls could in fact recurse without going
1570 // through a function marked norecurse, and so we can mark this function too
1571 // as norecurse. Note that the uses must actually be calls -- otherwise
1572 // a pointer to this function could be returned from a norecurse function but
1573 // this function could be recursively (indirectly) called. Note that this
1574 // also detects if F is directly recursive as F is not yet marked as
1575 // a norecurse function.
1576 for (auto *U : F.users()) {
1577 auto *I = dyn_cast<Instruction>(U);
1578 if (!I)
1579 return false;
1580 CallSite CS(I);
1581 if (!CS || !CS.getParent()->getParent()->doesNotRecurse())
1582 return false;
1583 }
1584 return setDoesNotRecurse(F);
1585}
1586
Sean Silvaadc79392016-06-12 05:44:51 +00001587static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
Chandler Carruth1926b702016-01-08 10:55:52 +00001588 // We only have a post-order SCC traversal (because SCCs are inherently
1589 // discovered in post-order), so we accumulate them in a vector and then walk
1590 // it in reverse. This is simpler than using the RPO iterator infrastructure
1591 // because we need to combine SCC detection and the PO walk of the call
1592 // graph. We can also cheat egregiously because we're primarily interested in
1593 // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1594 // with multiple functions in them will clearly be recursive.
Chandler Carruth1926b702016-01-08 10:55:52 +00001595 SmallVector<Function *, 16> Worklist;
1596 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1597 if (I->size() != 1)
1598 continue;
1599
1600 Function *F = I->front()->getFunction();
1601 if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1602 F->hasInternalLinkage())
1603 Worklist.push_back(F);
1604 }
1605
James Molloy7e9bdd52015-11-12 10:55:20 +00001606 bool Changed = false;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001607 for (auto *F : llvm::reverse(Worklist))
Chandler Carruth1926b702016-01-08 10:55:52 +00001608 Changed |= addNoRecurseAttrsTopDown(*F);
1609
Duncan Sands44c8cd92008-12-31 16:14:43 +00001610 return Changed;
1611}
Sean Silvaadc79392016-06-12 05:44:51 +00001612
Sean Silvaf5080192016-06-12 07:48:51 +00001613bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
Sean Silvaadc79392016-06-12 05:44:51 +00001614 if (skipModule(M))
1615 return false;
1616
1617 auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1618
1619 return deduceFunctionAttributeInRPO(M, CG);
1620}
Sean Silvaf5080192016-06-12 07:48:51 +00001621
1622PreservedAnalyses
Sean Silvafd03ac62016-08-09 00:28:38 +00001623ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
Sean Silvaf5080192016-06-12 07:48:51 +00001624 auto &CG = AM.getResult<CallGraphAnalysis>(M);
1625
Chandler Carruth6acdca72017-01-24 12:55:57 +00001626 if (!deduceFunctionAttributeInRPO(M, CG))
Sean Silvaf5080192016-06-12 07:48:51 +00001627 return PreservedAnalyses::all();
Chandler Carruth6acdca72017-01-24 12:55:57 +00001628
Sean Silvaf5080192016-06-12 07:48:51 +00001629 PreservedAnalyses PA;
1630 PA.preserve<CallGraphAnalysis>();
1631 return PA;
1632}