[FunctionAttrs] Fix an iterator wraparound bug
[oota-llvm.git] / lib / Transforms / IPO / FunctionAttrs.cpp
1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple interprocedural pass which walks the
11 // call-graph, looking for functions which do not access or only read
12 // non-local memory, and marking them readnone/readonly.  It does the
13 // same with function arguments independently, marking them readonly/
14 // readnone/nocapture.  Finally, well-known library call declarations
15 // are marked with all attributes that are consistent with the
16 // function's standard definition. This pass is implemented as a
17 // bottom-up traversal of the call-graph.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/CallGraphSCCPass.h"
31 #include "llvm/Analysis/CaptureTracking.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Analysis/TargetLibraryInfo.h"
41 using namespace llvm;
42
43 #define DEBUG_TYPE "functionattrs"
44
45 STATISTIC(NumReadNone, "Number of functions marked readnone");
46 STATISTIC(NumReadOnly, "Number of functions marked readonly");
47 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
48 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
49 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
50 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
51 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
52 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
53
54 namespace {
55 typedef SmallSetVector<Function *, 8> SCCNodeSet;
56 }
57
58 namespace {
59 struct FunctionAttrs : public CallGraphSCCPass {
60   static char ID; // Pass identification, replacement for typeid
61   FunctionAttrs() : CallGraphSCCPass(ID) {
62     initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
63   }
64
65   bool runOnSCC(CallGraphSCC &SCC) override;
66
67   void getAnalysisUsage(AnalysisUsage &AU) const override {
68     AU.setPreservesCFG();
69     AU.addRequired<AssumptionCacheTracker>();
70     AU.addRequired<TargetLibraryInfoWrapperPass>();
71     CallGraphSCCPass::getAnalysisUsage(AU);
72   }
73
74 private:
75   TargetLibraryInfo *TLI;
76 };
77 }
78
79 char FunctionAttrs::ID = 0;
80 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
81                       "Deduce function attributes", false, false)
82 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
83 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
84 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
85 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
86                     "Deduce function attributes", false, false)
87
88 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
89
90 namespace {
91 /// The three kinds of memory access relevant to 'readonly' and
92 /// 'readnone' attributes.
93 enum MemoryAccessKind {
94   MAK_ReadNone = 0,
95   MAK_ReadOnly = 1,
96   MAK_MayWrite = 2
97 };
98 }
99
100 static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
101                                                   const SCCNodeSet &SCCNodes) {
102   FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
103   if (MRB == FMRB_DoesNotAccessMemory)
104     // Already perfect!
105     return MAK_ReadNone;
106
107   // Definitions with weak linkage may be overridden at linktime with
108   // something that writes memory, so treat them like declarations.
109   if (F.isDeclaration() || F.mayBeOverridden()) {
110     if (AliasAnalysis::onlyReadsMemory(MRB))
111       return MAK_ReadOnly;
112
113     // Conservatively assume it writes to memory.
114     return MAK_MayWrite;
115   }
116
117   // Scan the function body for instructions that may read or write memory.
118   bool ReadsMemory = false;
119   for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
120     Instruction *I = &*II;
121
122     // Some instructions can be ignored even if they read or write memory.
123     // Detect these now, skipping to the next instruction if one is found.
124     CallSite CS(cast<Value>(I));
125     if (CS) {
126       // Ignore calls to functions in the same SCC.
127       if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
128         continue;
129       FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
130
131       // If the call doesn't access memory, we're done.
132       if (!(MRB & MRI_ModRef))
133         continue;
134
135       if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
136         // The call could access any memory. If that includes writes, give up.
137         if (MRB & MRI_Mod)
138           return MAK_MayWrite;
139         // If it reads, note it.
140         if (MRB & MRI_Ref)
141           ReadsMemory = true;
142         continue;
143       }
144
145       // Check whether all pointer arguments point to local memory, and
146       // ignore calls that only access local memory.
147       for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
148            CI != CE; ++CI) {
149         Value *Arg = *CI;
150         if (!Arg->getType()->isPointerTy())
151           continue;
152
153         AAMDNodes AAInfo;
154         I->getAAMetadata(AAInfo);
155         MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
156
157         // Skip accesses to local or constant memory as they don't impact the
158         // externally visible mod/ref behavior.
159         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
160           continue;
161
162         if (MRB & MRI_Mod)
163           // Writes non-local memory.  Give up.
164           return MAK_MayWrite;
165         if (MRB & MRI_Ref)
166           // Ok, it reads non-local memory.
167           ReadsMemory = true;
168       }
169       continue;
170     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
171       // Ignore non-volatile loads from local memory. (Atomic is okay here.)
172       if (!LI->isVolatile()) {
173         MemoryLocation Loc = MemoryLocation::get(LI);
174         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
175           continue;
176       }
177     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
178       // Ignore non-volatile stores to local memory. (Atomic is okay here.)
179       if (!SI->isVolatile()) {
180         MemoryLocation Loc = MemoryLocation::get(SI);
181         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
182           continue;
183       }
184     } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
185       // Ignore vaargs on local memory.
186       MemoryLocation Loc = MemoryLocation::get(VI);
187       if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
188         continue;
189     }
190
191     // Any remaining instructions need to be taken seriously!  Check if they
192     // read or write memory.
193     if (I->mayWriteToMemory())
194       // Writes memory.  Just give up.
195       return MAK_MayWrite;
196
197     // If this instruction may read memory, remember that.
198     ReadsMemory |= I->mayReadFromMemory();
199   }
200
201   return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
202 }
203
204 /// Deduce readonly/readnone attributes for the SCC.
205 template <typename AARGetterT>
206 static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
207   // Check if any of the functions in the SCC read or write memory.  If they
208   // write memory then they can't be marked readnone or readonly.
209   bool ReadsMemory = false;
210   for (Function *F : SCCNodes) {
211     // Call the callable parameter to look up AA results for this function.
212     AAResults &AAR = AARGetter(*F);
213
214     switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
215     case MAK_MayWrite:
216       return false;
217     case MAK_ReadOnly:
218       ReadsMemory = true;
219       break;
220     case MAK_ReadNone:
221       // Nothing to do!
222       break;
223     }
224   }
225
226   // Success!  Functions in this SCC do not access memory, or only read memory.
227   // Give them the appropriate attribute.
228   bool MadeChange = false;
229   for (Function *F : SCCNodes) {
230     if (F->doesNotAccessMemory())
231       // Already perfect!
232       continue;
233
234     if (F->onlyReadsMemory() && ReadsMemory)
235       // No change.
236       continue;
237
238     MadeChange = true;
239
240     // Clear out any existing attributes.
241     AttrBuilder B;
242     B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
243     F->removeAttributes(
244         AttributeSet::FunctionIndex,
245         AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
246
247     // Add in the new attribute.
248     F->addAttribute(AttributeSet::FunctionIndex,
249                     ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
250
251     if (ReadsMemory)
252       ++NumReadOnly;
253     else
254       ++NumReadNone;
255   }
256
257   return MadeChange;
258 }
259
260 namespace {
261 /// For a given pointer Argument, this retains a list of Arguments of functions
262 /// in the same SCC that the pointer data flows into. We use this to build an
263 /// SCC of the arguments.
264 struct ArgumentGraphNode {
265   Argument *Definition;
266   SmallVector<ArgumentGraphNode *, 4> Uses;
267 };
268
269 class ArgumentGraph {
270   // We store pointers to ArgumentGraphNode objects, so it's important that
271   // that they not move around upon insert.
272   typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
273
274   ArgumentMapTy ArgumentMap;
275
276   // There is no root node for the argument graph, in fact:
277   //   void f(int *x, int *y) { if (...) f(x, y); }
278   // is an example where the graph is disconnected. The SCCIterator requires a
279   // single entry point, so we maintain a fake ("synthetic") root node that
280   // uses every node. Because the graph is directed and nothing points into
281   // the root, it will not participate in any SCCs (except for its own).
282   ArgumentGraphNode SyntheticRoot;
283
284 public:
285   ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
286
287   typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
288
289   iterator begin() { return SyntheticRoot.Uses.begin(); }
290   iterator end() { return SyntheticRoot.Uses.end(); }
291   ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
292
293   ArgumentGraphNode *operator[](Argument *A) {
294     ArgumentGraphNode &Node = ArgumentMap[A];
295     Node.Definition = A;
296     SyntheticRoot.Uses.push_back(&Node);
297     return &Node;
298   }
299 };
300
301 /// This tracker checks whether callees are in the SCC, and if so it does not
302 /// consider that a capture, instead adding it to the "Uses" list and
303 /// continuing with the analysis.
304 struct ArgumentUsesTracker : public CaptureTracker {
305   ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
306       : Captured(false), SCCNodes(SCCNodes) {}
307
308   void tooManyUses() override { Captured = true; }
309
310   bool captured(const Use *U) override {
311     CallSite CS(U->getUser());
312     if (!CS.getInstruction()) {
313       Captured = true;
314       return true;
315     }
316
317     Function *F = CS.getCalledFunction();
318     if (!F || F->isDeclaration() || F->mayBeOverridden() ||
319         !SCCNodes.count(F)) {
320       Captured = true;
321       return true;
322     }
323
324     // Note: the callee and the two successor blocks *follow* the argument
325     // operands.  This means there is no need to adjust UseIndex to account for
326     // these.
327
328     unsigned UseIndex =
329         std::distance(const_cast<const Use *>(CS.arg_begin()), U);
330
331     assert(UseIndex < CS.arg_size() && "Non-argument use?");
332     if (UseIndex >= F->arg_size()) {
333       assert(F->isVarArg() && "More params than args in non-varargs call");
334       Captured = true;
335       return true;
336     }
337
338     Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
339     return false;
340   }
341
342   bool Captured; // True only if certainly captured (used outside our SCC).
343   SmallVector<Argument *, 4> Uses; // Uses within our SCC.
344
345   const SCCNodeSet &SCCNodes;
346 };
347 }
348
349 namespace llvm {
350 template <> struct GraphTraits<ArgumentGraphNode *> {
351   typedef ArgumentGraphNode NodeType;
352   typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
353
354   static inline NodeType *getEntryNode(NodeType *A) { return A; }
355   static inline ChildIteratorType child_begin(NodeType *N) {
356     return N->Uses.begin();
357   }
358   static inline ChildIteratorType child_end(NodeType *N) {
359     return N->Uses.end();
360   }
361 };
362 template <>
363 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
364   static NodeType *getEntryNode(ArgumentGraph *AG) {
365     return AG->getEntryNode();
366   }
367   static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
368     return AG->begin();
369   }
370   static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
371 };
372 }
373
374 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
375 static Attribute::AttrKind
376 determinePointerReadAttrs(Argument *A,
377                           const SmallPtrSet<Argument *, 8> &SCCNodes) {
378
379   SmallVector<Use *, 32> Worklist;
380   SmallSet<Use *, 32> Visited;
381
382   // inalloca arguments are always clobbered by the call.
383   if (A->hasInAllocaAttr())
384     return Attribute::None;
385
386   bool IsRead = false;
387   // We don't need to track IsWritten. If A is written to, return immediately.
388
389   for (Use &U : A->uses()) {
390     Visited.insert(&U);
391     Worklist.push_back(&U);
392   }
393
394   while (!Worklist.empty()) {
395     Use *U = Worklist.pop_back_val();
396     Instruction *I = cast<Instruction>(U->getUser());
397
398     switch (I->getOpcode()) {
399     case Instruction::BitCast:
400     case Instruction::GetElementPtr:
401     case Instruction::PHI:
402     case Instruction::Select:
403     case Instruction::AddrSpaceCast:
404       // The original value is not read/written via this if the new value isn't.
405       for (Use &UU : I->uses())
406         if (Visited.insert(&UU).second)
407           Worklist.push_back(&UU);
408       break;
409
410     case Instruction::Call:
411     case Instruction::Invoke: {
412       bool Captures = true;
413
414       if (I->getType()->isVoidTy())
415         Captures = false;
416
417       auto AddUsersToWorklistIfCapturing = [&] {
418         if (Captures)
419           for (Use &UU : I->uses())
420             if (Visited.insert(&UU).second)
421               Worklist.push_back(&UU);
422       };
423
424       CallSite CS(I);
425       if (CS.doesNotAccessMemory()) {
426         AddUsersToWorklistIfCapturing();
427         continue;
428       }
429
430       Function *F = CS.getCalledFunction();
431       if (!F) {
432         if (CS.onlyReadsMemory()) {
433           IsRead = true;
434           AddUsersToWorklistIfCapturing();
435           continue;
436         }
437         return Attribute::None;
438       }
439
440       // Note: the callee and the two successor blocks *follow* the argument
441       // operands.  This means there is no need to adjust UseIndex to account
442       // for these.
443
444       unsigned UseIndex = std::distance(CS.arg_begin(), U);
445
446       assert(UseIndex < CS.arg_size() && "Non-argument use?");
447       if (UseIndex >= F->arg_size()) {
448         assert(F->isVarArg() && "More params than args in non-varargs call");
449         return Attribute::None;
450       }
451
452       Captures &= !CS.doesNotCapture(UseIndex);
453       if (!SCCNodes.count(std::next(F->arg_begin(), UseIndex))) {
454         if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
455           return Attribute::None;
456         if (!CS.doesNotAccessMemory(UseIndex))
457           IsRead = true;
458       }
459
460       AddUsersToWorklistIfCapturing();
461       break;
462     }
463
464     case Instruction::Load:
465       IsRead = true;
466       break;
467
468     case Instruction::ICmp:
469     case Instruction::Ret:
470       break;
471
472     default:
473       return Attribute::None;
474     }
475   }
476
477   return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
478 }
479
480 /// Deduce nocapture attributes for the SCC.
481 static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
482   bool Changed = false;
483
484   ArgumentGraph AG;
485
486   AttrBuilder B;
487   B.addAttribute(Attribute::NoCapture);
488
489   // Check each function in turn, determining which pointer arguments are not
490   // captured.
491   for (Function *F : SCCNodes) {
492     // Definitions with weak linkage may be overridden at linktime with
493     // something that captures pointers, so treat them like declarations.
494     if (F->isDeclaration() || F->mayBeOverridden())
495       continue;
496
497     // Functions that are readonly (or readnone) and nounwind and don't return
498     // a value can't capture arguments. Don't analyze them.
499     if (F->onlyReadsMemory() && F->doesNotThrow() &&
500         F->getReturnType()->isVoidTy()) {
501       for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
502            ++A) {
503         if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
504           A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
505           ++NumNoCapture;
506           Changed = true;
507         }
508       }
509       continue;
510     }
511
512     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
513          ++A) {
514       if (!A->getType()->isPointerTy())
515         continue;
516       bool HasNonLocalUses = false;
517       if (!A->hasNoCaptureAttr()) {
518         ArgumentUsesTracker Tracker(SCCNodes);
519         PointerMayBeCaptured(&*A, &Tracker);
520         if (!Tracker.Captured) {
521           if (Tracker.Uses.empty()) {
522             // If it's trivially not captured, mark it nocapture now.
523             A->addAttr(
524                 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
525             ++NumNoCapture;
526             Changed = true;
527           } else {
528             // If it's not trivially captured and not trivially not captured,
529             // then it must be calling into another function in our SCC. Save
530             // its particulars for Argument-SCC analysis later.
531             ArgumentGraphNode *Node = AG[&*A];
532             for (SmallVectorImpl<Argument *>::iterator
533                      UI = Tracker.Uses.begin(),
534                      UE = Tracker.Uses.end();
535                  UI != UE; ++UI) {
536               Node->Uses.push_back(AG[*UI]);
537               if (*UI != A)
538                 HasNonLocalUses = true;
539             }
540           }
541         }
542         // Otherwise, it's captured. Don't bother doing SCC analysis on it.
543       }
544       if (!HasNonLocalUses && !A->onlyReadsMemory()) {
545         // Can we determine that it's readonly/readnone without doing an SCC?
546         // Note that we don't allow any calls at all here, or else our result
547         // will be dependent on the iteration order through the functions in the
548         // SCC.
549         SmallPtrSet<Argument *, 8> Self;
550         Self.insert(&*A);
551         Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
552         if (R != Attribute::None) {
553           AttrBuilder B;
554           B.addAttribute(R);
555           A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
556           Changed = true;
557           R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
558         }
559       }
560     }
561   }
562
563   // The graph we've collected is partial because we stopped scanning for
564   // argument uses once we solved the argument trivially. These partial nodes
565   // show up as ArgumentGraphNode objects with an empty Uses list, and for
566   // these nodes the final decision about whether they capture has already been
567   // made.  If the definition doesn't have a 'nocapture' attribute by now, it
568   // captures.
569
570   for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
571     const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
572     if (ArgumentSCC.size() == 1) {
573       if (!ArgumentSCC[0]->Definition)
574         continue; // synthetic root node
575
576       // eg. "void f(int* x) { if (...) f(x); }"
577       if (ArgumentSCC[0]->Uses.size() == 1 &&
578           ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
579         Argument *A = ArgumentSCC[0]->Definition;
580         A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
581         ++NumNoCapture;
582         Changed = true;
583       }
584       continue;
585     }
586
587     bool SCCCaptured = false;
588     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
589          I != E && !SCCCaptured; ++I) {
590       ArgumentGraphNode *Node = *I;
591       if (Node->Uses.empty()) {
592         if (!Node->Definition->hasNoCaptureAttr())
593           SCCCaptured = true;
594       }
595     }
596     if (SCCCaptured)
597       continue;
598
599     SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
600     // Fill ArgumentSCCNodes with the elements of the ArgumentSCC.  Used for
601     // quickly looking up whether a given Argument is in this ArgumentSCC.
602     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
603       ArgumentSCCNodes.insert((*I)->Definition);
604     }
605
606     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
607          I != E && !SCCCaptured; ++I) {
608       ArgumentGraphNode *N = *I;
609       for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
610                                                           UE = N->Uses.end();
611            UI != UE; ++UI) {
612         Argument *A = (*UI)->Definition;
613         if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
614           continue;
615         SCCCaptured = true;
616         break;
617       }
618     }
619     if (SCCCaptured)
620       continue;
621
622     for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
623       Argument *A = ArgumentSCC[i]->Definition;
624       A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
625       ++NumNoCapture;
626       Changed = true;
627     }
628
629     // We also want to compute readonly/readnone. With a small number of false
630     // negatives, we can assume that any pointer which is captured isn't going
631     // to be provably readonly or readnone, since by definition we can't
632     // analyze all uses of a captured pointer.
633     //
634     // The false negatives happen when the pointer is captured by a function
635     // that promises readonly/readnone behaviour on the pointer, then the
636     // pointer's lifetime ends before anything that writes to arbitrary memory.
637     // Also, a readonly/readnone pointer may be returned, but returning a
638     // pointer is capturing it.
639
640     Attribute::AttrKind ReadAttr = Attribute::ReadNone;
641     for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
642       Argument *A = ArgumentSCC[i]->Definition;
643       Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
644       if (K == Attribute::ReadNone)
645         continue;
646       if (K == Attribute::ReadOnly) {
647         ReadAttr = Attribute::ReadOnly;
648         continue;
649       }
650       ReadAttr = K;
651       break;
652     }
653
654     if (ReadAttr != Attribute::None) {
655       AttrBuilder B, R;
656       B.addAttribute(ReadAttr);
657       R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
658       for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
659         Argument *A = ArgumentSCC[i]->Definition;
660         // Clear out existing readonly/readnone attributes
661         A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
662         A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
663         ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
664         Changed = true;
665       }
666     }
667   }
668
669   return Changed;
670 }
671
672 /// Tests whether a function is "malloc-like".
673 ///
674 /// A function is "malloc-like" if it returns either null or a pointer that
675 /// doesn't alias any other pointer visible to the caller.
676 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
677   SmallSetVector<Value *, 8> FlowsToReturn;
678   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
679     if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
680       FlowsToReturn.insert(Ret->getReturnValue());
681
682   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
683     Value *RetVal = FlowsToReturn[i];
684
685     if (Constant *C = dyn_cast<Constant>(RetVal)) {
686       if (!C->isNullValue() && !isa<UndefValue>(C))
687         return false;
688
689       continue;
690     }
691
692     if (isa<Argument>(RetVal))
693       return false;
694
695     if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
696       switch (RVI->getOpcode()) {
697       // Extend the analysis by looking upwards.
698       case Instruction::BitCast:
699       case Instruction::GetElementPtr:
700       case Instruction::AddrSpaceCast:
701         FlowsToReturn.insert(RVI->getOperand(0));
702         continue;
703       case Instruction::Select: {
704         SelectInst *SI = cast<SelectInst>(RVI);
705         FlowsToReturn.insert(SI->getTrueValue());
706         FlowsToReturn.insert(SI->getFalseValue());
707         continue;
708       }
709       case Instruction::PHI: {
710         PHINode *PN = cast<PHINode>(RVI);
711         for (Value *IncValue : PN->incoming_values())
712           FlowsToReturn.insert(IncValue);
713         continue;
714       }
715
716       // Check whether the pointer came from an allocation.
717       case Instruction::Alloca:
718         break;
719       case Instruction::Call:
720       case Instruction::Invoke: {
721         CallSite CS(RVI);
722         if (CS.paramHasAttr(0, Attribute::NoAlias))
723           break;
724         if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
725           break;
726       } // fall-through
727       default:
728         return false; // Did not come from an allocation.
729       }
730
731     if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
732       return false;
733   }
734
735   return true;
736 }
737
738 /// Deduce noalias attributes for the SCC.
739 static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
740   // Check each function in turn, determining which functions return noalias
741   // pointers.
742   for (Function *F : SCCNodes) {
743     // Already noalias.
744     if (F->doesNotAlias(0))
745       continue;
746
747     // Definitions with weak linkage may be overridden at linktime, so
748     // treat them like declarations.
749     if (F->isDeclaration() || F->mayBeOverridden())
750       return false;
751
752     // We annotate noalias return values, which are only applicable to
753     // pointer types.
754     if (!F->getReturnType()->isPointerTy())
755       continue;
756
757     if (!isFunctionMallocLike(F, SCCNodes))
758       return false;
759   }
760
761   bool MadeChange = false;
762   for (Function *F : SCCNodes) {
763     if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
764       continue;
765
766     F->setDoesNotAlias(0);
767     ++NumNoAlias;
768     MadeChange = true;
769   }
770
771   return MadeChange;
772 }
773
774 /// Tests whether this function is known to not return null.
775 ///
776 /// Requires that the function returns a pointer.
777 ///
778 /// Returns true if it believes the function will not return a null, and sets
779 /// \p Speculative based on whether the returned conclusion is a speculative
780 /// conclusion due to SCC calls.
781 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
782                             const TargetLibraryInfo &TLI, bool &Speculative) {
783   assert(F->getReturnType()->isPointerTy() &&
784          "nonnull only meaningful on pointer types");
785   Speculative = false;
786
787   SmallSetVector<Value *, 8> FlowsToReturn;
788   for (BasicBlock &BB : *F)
789     if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
790       FlowsToReturn.insert(Ret->getReturnValue());
791
792   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
793     Value *RetVal = FlowsToReturn[i];
794
795     // If this value is locally known to be non-null, we're good
796     if (isKnownNonNull(RetVal, &TLI))
797       continue;
798
799     // Otherwise, we need to look upwards since we can't make any local
800     // conclusions.
801     Instruction *RVI = dyn_cast<Instruction>(RetVal);
802     if (!RVI)
803       return false;
804     switch (RVI->getOpcode()) {
805     // Extend the analysis by looking upwards.
806     case Instruction::BitCast:
807     case Instruction::GetElementPtr:
808     case Instruction::AddrSpaceCast:
809       FlowsToReturn.insert(RVI->getOperand(0));
810       continue;
811     case Instruction::Select: {
812       SelectInst *SI = cast<SelectInst>(RVI);
813       FlowsToReturn.insert(SI->getTrueValue());
814       FlowsToReturn.insert(SI->getFalseValue());
815       continue;
816     }
817     case Instruction::PHI: {
818       PHINode *PN = cast<PHINode>(RVI);
819       for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
820         FlowsToReturn.insert(PN->getIncomingValue(i));
821       continue;
822     }
823     case Instruction::Call:
824     case Instruction::Invoke: {
825       CallSite CS(RVI);
826       Function *Callee = CS.getCalledFunction();
827       // A call to a node within the SCC is assumed to return null until
828       // proven otherwise
829       if (Callee && SCCNodes.count(Callee)) {
830         Speculative = true;
831         continue;
832       }
833       return false;
834     }
835     default:
836       return false; // Unknown source, may be null
837     };
838     llvm_unreachable("should have either continued or returned");
839   }
840
841   return true;
842 }
843
844 /// Deduce nonnull attributes for the SCC.
845 static bool addNonNullAttrs(const SCCNodeSet &SCCNodes,
846                             const TargetLibraryInfo &TLI) {
847   // Speculative that all functions in the SCC return only nonnull
848   // pointers.  We may refute this as we analyze functions.
849   bool SCCReturnsNonNull = true;
850
851   bool MadeChange = false;
852
853   // Check each function in turn, determining which functions return nonnull
854   // pointers.
855   for (Function *F : SCCNodes) {
856     // Already nonnull.
857     if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
858                                         Attribute::NonNull))
859       continue;
860
861     // Definitions with weak linkage may be overridden at linktime, so
862     // treat them like declarations.
863     if (F->isDeclaration() || F->mayBeOverridden())
864       return false;
865
866     // We annotate nonnull return values, which are only applicable to
867     // pointer types.
868     if (!F->getReturnType()->isPointerTy())
869       continue;
870
871     bool Speculative = false;
872     if (isReturnNonNull(F, SCCNodes, TLI, Speculative)) {
873       if (!Speculative) {
874         // Mark the function eagerly since we may discover a function
875         // which prevents us from speculating about the entire SCC
876         DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
877         F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
878         ++NumNonNullReturn;
879         MadeChange = true;
880       }
881       continue;
882     }
883     // At least one function returns something which could be null, can't
884     // speculate any more.
885     SCCReturnsNonNull = false;
886   }
887
888   if (SCCReturnsNonNull) {
889     for (Function *F : SCCNodes) {
890       if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
891                                           Attribute::NonNull) ||
892           !F->getReturnType()->isPointerTy())
893         continue;
894
895       DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
896       F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
897       ++NumNonNullReturn;
898       MadeChange = true;
899     }
900   }
901
902   return MadeChange;
903 }
904
905 static void setDoesNotAccessMemory(Function &F) {
906   if (!F.doesNotAccessMemory()) {
907     F.setDoesNotAccessMemory();
908     ++NumAnnotated;
909   }
910 }
911
912 static void setOnlyReadsMemory(Function &F) {
913   if (!F.onlyReadsMemory()) {
914     F.setOnlyReadsMemory();
915     ++NumAnnotated;
916   }
917 }
918
919 static void setDoesNotThrow(Function &F) {
920   if (!F.doesNotThrow()) {
921     F.setDoesNotThrow();
922     ++NumAnnotated;
923   }
924 }
925
926 static void setDoesNotCapture(Function &F, unsigned n) {
927   if (!F.doesNotCapture(n)) {
928     F.setDoesNotCapture(n);
929     ++NumAnnotated;
930   }
931 }
932
933 static void setOnlyReadsMemory(Function &F, unsigned n) {
934   if (!F.onlyReadsMemory(n)) {
935     F.setOnlyReadsMemory(n);
936     ++NumAnnotated;
937   }
938 }
939
940 static void setDoesNotAlias(Function &F, unsigned n) {
941   if (!F.doesNotAlias(n)) {
942     F.setDoesNotAlias(n);
943     ++NumAnnotated;
944   }
945 }
946
947 /// Analyze the name and prototype of the given function and set any applicable
948 /// attributes.
949 ///
950 /// Returns true if any attributes were set and false otherwise.
951 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
952   if (F.hasFnAttribute(Attribute::OptimizeNone))
953     return false;
954
955   FunctionType *FTy = F.getFunctionType();
956   LibFunc::Func TheLibFunc;
957   if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
958     return false;
959
960   switch (TheLibFunc) {
961   case LibFunc::strlen:
962     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
963       return false;
964     setOnlyReadsMemory(F);
965     setDoesNotThrow(F);
966     setDoesNotCapture(F, 1);
967     break;
968   case LibFunc::strchr:
969   case LibFunc::strrchr:
970     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
971         !FTy->getParamType(1)->isIntegerTy())
972       return false;
973     setOnlyReadsMemory(F);
974     setDoesNotThrow(F);
975     break;
976   case LibFunc::strtol:
977   case LibFunc::strtod:
978   case LibFunc::strtof:
979   case LibFunc::strtoul:
980   case LibFunc::strtoll:
981   case LibFunc::strtold:
982   case LibFunc::strtoull:
983     if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
984       return false;
985     setDoesNotThrow(F);
986     setDoesNotCapture(F, 2);
987     setOnlyReadsMemory(F, 1);
988     break;
989   case LibFunc::strcpy:
990   case LibFunc::stpcpy:
991   case LibFunc::strcat:
992   case LibFunc::strncat:
993   case LibFunc::strncpy:
994   case LibFunc::stpncpy:
995     if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
996       return false;
997     setDoesNotThrow(F);
998     setDoesNotCapture(F, 2);
999     setOnlyReadsMemory(F, 2);
1000     break;
1001   case LibFunc::strxfrm:
1002     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1003         !FTy->getParamType(1)->isPointerTy())
1004       return false;
1005     setDoesNotThrow(F);
1006     setDoesNotCapture(F, 1);
1007     setDoesNotCapture(F, 2);
1008     setOnlyReadsMemory(F, 2);
1009     break;
1010   case LibFunc::strcmp: // 0,1
1011   case LibFunc::strspn:  // 0,1
1012   case LibFunc::strncmp: // 0,1
1013   case LibFunc::strcspn: // 0,1
1014   case LibFunc::strcoll: // 0,1
1015   case LibFunc::strcasecmp:  // 0,1
1016   case LibFunc::strncasecmp: //
1017     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1018         !FTy->getParamType(1)->isPointerTy())
1019       return false;
1020     setOnlyReadsMemory(F);
1021     setDoesNotThrow(F);
1022     setDoesNotCapture(F, 1);
1023     setDoesNotCapture(F, 2);
1024     break;
1025   case LibFunc::strstr:
1026   case LibFunc::strpbrk:
1027     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1028       return false;
1029     setOnlyReadsMemory(F);
1030     setDoesNotThrow(F);
1031     setDoesNotCapture(F, 2);
1032     break;
1033   case LibFunc::strtok:
1034   case LibFunc::strtok_r:
1035     if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1036       return false;
1037     setDoesNotThrow(F);
1038     setDoesNotCapture(F, 2);
1039     setOnlyReadsMemory(F, 2);
1040     break;
1041   case LibFunc::scanf:
1042     if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1043       return false;
1044     setDoesNotThrow(F);
1045     setDoesNotCapture(F, 1);
1046     setOnlyReadsMemory(F, 1);
1047     break;
1048   case LibFunc::setbuf:
1049   case LibFunc::setvbuf:
1050     if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1051       return false;
1052     setDoesNotThrow(F);
1053     setDoesNotCapture(F, 1);
1054     break;
1055   case LibFunc::strdup:
1056   case LibFunc::strndup:
1057     if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1058         !FTy->getParamType(0)->isPointerTy())
1059       return false;
1060     setDoesNotThrow(F);
1061     setDoesNotAlias(F, 0);
1062     setDoesNotCapture(F, 1);
1063     setOnlyReadsMemory(F, 1);
1064     break;
1065   case LibFunc::stat:
1066   case LibFunc::statvfs:
1067     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1068         !FTy->getParamType(1)->isPointerTy())
1069       return false;
1070     setDoesNotThrow(F);
1071     setDoesNotCapture(F, 1);
1072     setDoesNotCapture(F, 2);
1073     setOnlyReadsMemory(F, 1);
1074     break;
1075   case LibFunc::sscanf:
1076     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1077         !FTy->getParamType(1)->isPointerTy())
1078       return false;
1079     setDoesNotThrow(F);
1080     setDoesNotCapture(F, 1);
1081     setDoesNotCapture(F, 2);
1082     setOnlyReadsMemory(F, 1);
1083     setOnlyReadsMemory(F, 2);
1084     break;
1085   case LibFunc::sprintf:
1086     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1087         !FTy->getParamType(1)->isPointerTy())
1088       return false;
1089     setDoesNotThrow(F);
1090     setDoesNotCapture(F, 1);
1091     setDoesNotCapture(F, 2);
1092     setOnlyReadsMemory(F, 2);
1093     break;
1094   case LibFunc::snprintf:
1095     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1096         !FTy->getParamType(2)->isPointerTy())
1097       return false;
1098     setDoesNotThrow(F);
1099     setDoesNotCapture(F, 1);
1100     setDoesNotCapture(F, 3);
1101     setOnlyReadsMemory(F, 3);
1102     break;
1103   case LibFunc::setitimer:
1104     if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1105         !FTy->getParamType(2)->isPointerTy())
1106       return false;
1107     setDoesNotThrow(F);
1108     setDoesNotCapture(F, 2);
1109     setDoesNotCapture(F, 3);
1110     setOnlyReadsMemory(F, 2);
1111     break;
1112   case LibFunc::system:
1113     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1114       return false;
1115     // May throw; "system" is a valid pthread cancellation point.
1116     setDoesNotCapture(F, 1);
1117     setOnlyReadsMemory(F, 1);
1118     break;
1119   case LibFunc::malloc:
1120     if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1121       return false;
1122     setDoesNotThrow(F);
1123     setDoesNotAlias(F, 0);
1124     break;
1125   case LibFunc::memcmp:
1126     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1127         !FTy->getParamType(1)->isPointerTy())
1128       return false;
1129     setOnlyReadsMemory(F);
1130     setDoesNotThrow(F);
1131     setDoesNotCapture(F, 1);
1132     setDoesNotCapture(F, 2);
1133     break;
1134   case LibFunc::memchr:
1135   case LibFunc::memrchr:
1136     if (FTy->getNumParams() != 3)
1137       return false;
1138     setOnlyReadsMemory(F);
1139     setDoesNotThrow(F);
1140     break;
1141   case LibFunc::modf:
1142   case LibFunc::modff:
1143   case LibFunc::modfl:
1144     if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1145       return false;
1146     setDoesNotThrow(F);
1147     setDoesNotCapture(F, 2);
1148     break;
1149   case LibFunc::memcpy:
1150   case LibFunc::memccpy:
1151   case LibFunc::memmove:
1152     if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1153       return false;
1154     setDoesNotThrow(F);
1155     setDoesNotCapture(F, 2);
1156     setOnlyReadsMemory(F, 2);
1157     break;
1158   case LibFunc::memalign:
1159     if (!FTy->getReturnType()->isPointerTy())
1160       return false;
1161     setDoesNotAlias(F, 0);
1162     break;
1163   case LibFunc::mkdir:
1164     if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1165       return false;
1166     setDoesNotThrow(F);
1167     setDoesNotCapture(F, 1);
1168     setOnlyReadsMemory(F, 1);
1169     break;
1170   case LibFunc::mktime:
1171     if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1172       return false;
1173     setDoesNotThrow(F);
1174     setDoesNotCapture(F, 1);
1175     break;
1176   case LibFunc::realloc:
1177     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1178         !FTy->getReturnType()->isPointerTy())
1179       return false;
1180     setDoesNotThrow(F);
1181     setDoesNotAlias(F, 0);
1182     setDoesNotCapture(F, 1);
1183     break;
1184   case LibFunc::read:
1185     if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1186       return false;
1187     // May throw; "read" is a valid pthread cancellation point.
1188     setDoesNotCapture(F, 2);
1189     break;
1190   case LibFunc::rewind:
1191     if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1192       return false;
1193     setDoesNotThrow(F);
1194     setDoesNotCapture(F, 1);
1195     break;
1196   case LibFunc::rmdir:
1197   case LibFunc::remove:
1198   case LibFunc::realpath:
1199     if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1200       return false;
1201     setDoesNotThrow(F);
1202     setDoesNotCapture(F, 1);
1203     setOnlyReadsMemory(F, 1);
1204     break;
1205   case LibFunc::rename:
1206     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1207         !FTy->getParamType(1)->isPointerTy())
1208       return false;
1209     setDoesNotThrow(F);
1210     setDoesNotCapture(F, 1);
1211     setDoesNotCapture(F, 2);
1212     setOnlyReadsMemory(F, 1);
1213     setOnlyReadsMemory(F, 2);
1214     break;
1215   case LibFunc::readlink:
1216     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1217         !FTy->getParamType(1)->isPointerTy())
1218       return false;
1219     setDoesNotThrow(F);
1220     setDoesNotCapture(F, 1);
1221     setDoesNotCapture(F, 2);
1222     setOnlyReadsMemory(F, 1);
1223     break;
1224   case LibFunc::write:
1225     if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1226       return false;
1227     // May throw; "write" is a valid pthread cancellation point.
1228     setDoesNotCapture(F, 2);
1229     setOnlyReadsMemory(F, 2);
1230     break;
1231   case LibFunc::bcopy:
1232     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1233         !FTy->getParamType(1)->isPointerTy())
1234       return false;
1235     setDoesNotThrow(F);
1236     setDoesNotCapture(F, 1);
1237     setDoesNotCapture(F, 2);
1238     setOnlyReadsMemory(F, 1);
1239     break;
1240   case LibFunc::bcmp:
1241     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1242         !FTy->getParamType(1)->isPointerTy())
1243       return false;
1244     setDoesNotThrow(F);
1245     setOnlyReadsMemory(F);
1246     setDoesNotCapture(F, 1);
1247     setDoesNotCapture(F, 2);
1248     break;
1249   case LibFunc::bzero:
1250     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1251       return false;
1252     setDoesNotThrow(F);
1253     setDoesNotCapture(F, 1);
1254     break;
1255   case LibFunc::calloc:
1256     if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1257       return false;
1258     setDoesNotThrow(F);
1259     setDoesNotAlias(F, 0);
1260     break;
1261   case LibFunc::chmod:
1262   case LibFunc::chown:
1263     if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1264       return false;
1265     setDoesNotThrow(F);
1266     setDoesNotCapture(F, 1);
1267     setOnlyReadsMemory(F, 1);
1268     break;
1269   case LibFunc::ctermid:
1270   case LibFunc::clearerr:
1271   case LibFunc::closedir:
1272     if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1273       return false;
1274     setDoesNotThrow(F);
1275     setDoesNotCapture(F, 1);
1276     break;
1277   case LibFunc::atoi:
1278   case LibFunc::atol:
1279   case LibFunc::atof:
1280   case LibFunc::atoll:
1281     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1282       return false;
1283     setDoesNotThrow(F);
1284     setOnlyReadsMemory(F);
1285     setDoesNotCapture(F, 1);
1286     break;
1287   case LibFunc::access:
1288     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1289       return false;
1290     setDoesNotThrow(F);
1291     setDoesNotCapture(F, 1);
1292     setOnlyReadsMemory(F, 1);
1293     break;
1294   case LibFunc::fopen:
1295     if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1296         !FTy->getParamType(0)->isPointerTy() ||
1297         !FTy->getParamType(1)->isPointerTy())
1298       return false;
1299     setDoesNotThrow(F);
1300     setDoesNotAlias(F, 0);
1301     setDoesNotCapture(F, 1);
1302     setDoesNotCapture(F, 2);
1303     setOnlyReadsMemory(F, 1);
1304     setOnlyReadsMemory(F, 2);
1305     break;
1306   case LibFunc::fdopen:
1307     if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1308         !FTy->getParamType(1)->isPointerTy())
1309       return false;
1310     setDoesNotThrow(F);
1311     setDoesNotAlias(F, 0);
1312     setDoesNotCapture(F, 2);
1313     setOnlyReadsMemory(F, 2);
1314     break;
1315   case LibFunc::feof:
1316   case LibFunc::free:
1317   case LibFunc::fseek:
1318   case LibFunc::ftell:
1319   case LibFunc::fgetc:
1320   case LibFunc::fseeko:
1321   case LibFunc::ftello:
1322   case LibFunc::fileno:
1323   case LibFunc::fflush:
1324   case LibFunc::fclose:
1325   case LibFunc::fsetpos:
1326   case LibFunc::flockfile:
1327   case LibFunc::funlockfile:
1328   case LibFunc::ftrylockfile:
1329     if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1330       return false;
1331     setDoesNotThrow(F);
1332     setDoesNotCapture(F, 1);
1333     break;
1334   case LibFunc::ferror:
1335     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1336       return false;
1337     setDoesNotThrow(F);
1338     setDoesNotCapture(F, 1);
1339     setOnlyReadsMemory(F);
1340     break;
1341   case LibFunc::fputc:
1342   case LibFunc::fstat:
1343   case LibFunc::frexp:
1344   case LibFunc::frexpf:
1345   case LibFunc::frexpl:
1346   case LibFunc::fstatvfs:
1347     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1348       return false;
1349     setDoesNotThrow(F);
1350     setDoesNotCapture(F, 2);
1351     break;
1352   case LibFunc::fgets:
1353     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1354         !FTy->getParamType(2)->isPointerTy())
1355       return false;
1356     setDoesNotThrow(F);
1357     setDoesNotCapture(F, 3);
1358     break;
1359   case LibFunc::fread:
1360     if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1361         !FTy->getParamType(3)->isPointerTy())
1362       return false;
1363     setDoesNotThrow(F);
1364     setDoesNotCapture(F, 1);
1365     setDoesNotCapture(F, 4);
1366     break;
1367   case LibFunc::fwrite:
1368     if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1369         !FTy->getParamType(3)->isPointerTy())
1370       return false;
1371     setDoesNotThrow(F);
1372     setDoesNotCapture(F, 1);
1373     setDoesNotCapture(F, 4);
1374     break;
1375   case LibFunc::fputs:
1376     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1377         !FTy->getParamType(1)->isPointerTy())
1378       return false;
1379     setDoesNotThrow(F);
1380     setDoesNotCapture(F, 1);
1381     setDoesNotCapture(F, 2);
1382     setOnlyReadsMemory(F, 1);
1383     break;
1384   case LibFunc::fscanf:
1385   case LibFunc::fprintf:
1386     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1387         !FTy->getParamType(1)->isPointerTy())
1388       return false;
1389     setDoesNotThrow(F);
1390     setDoesNotCapture(F, 1);
1391     setDoesNotCapture(F, 2);
1392     setOnlyReadsMemory(F, 2);
1393     break;
1394   case LibFunc::fgetpos:
1395     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1396         !FTy->getParamType(1)->isPointerTy())
1397       return false;
1398     setDoesNotThrow(F);
1399     setDoesNotCapture(F, 1);
1400     setDoesNotCapture(F, 2);
1401     break;
1402   case LibFunc::getc:
1403   case LibFunc::getlogin_r:
1404   case LibFunc::getc_unlocked:
1405     if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1406       return false;
1407     setDoesNotThrow(F);
1408     setDoesNotCapture(F, 1);
1409     break;
1410   case LibFunc::getenv:
1411     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1412       return false;
1413     setDoesNotThrow(F);
1414     setOnlyReadsMemory(F);
1415     setDoesNotCapture(F, 1);
1416     break;
1417   case LibFunc::gets:
1418   case LibFunc::getchar:
1419     setDoesNotThrow(F);
1420     break;
1421   case LibFunc::getitimer:
1422     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1423       return false;
1424     setDoesNotThrow(F);
1425     setDoesNotCapture(F, 2);
1426     break;
1427   case LibFunc::getpwnam:
1428     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1429       return false;
1430     setDoesNotThrow(F);
1431     setDoesNotCapture(F, 1);
1432     setOnlyReadsMemory(F, 1);
1433     break;
1434   case LibFunc::ungetc:
1435     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1436       return false;
1437     setDoesNotThrow(F);
1438     setDoesNotCapture(F, 2);
1439     break;
1440   case LibFunc::uname:
1441     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1442       return false;
1443     setDoesNotThrow(F);
1444     setDoesNotCapture(F, 1);
1445     break;
1446   case LibFunc::unlink:
1447     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1448       return false;
1449     setDoesNotThrow(F);
1450     setDoesNotCapture(F, 1);
1451     setOnlyReadsMemory(F, 1);
1452     break;
1453   case LibFunc::unsetenv:
1454     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1455       return false;
1456     setDoesNotThrow(F);
1457     setDoesNotCapture(F, 1);
1458     setOnlyReadsMemory(F, 1);
1459     break;
1460   case LibFunc::utime:
1461   case LibFunc::utimes:
1462     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1463         !FTy->getParamType(1)->isPointerTy())
1464       return false;
1465     setDoesNotThrow(F);
1466     setDoesNotCapture(F, 1);
1467     setDoesNotCapture(F, 2);
1468     setOnlyReadsMemory(F, 1);
1469     setOnlyReadsMemory(F, 2);
1470     break;
1471   case LibFunc::putc:
1472     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1473       return false;
1474     setDoesNotThrow(F);
1475     setDoesNotCapture(F, 2);
1476     break;
1477   case LibFunc::puts:
1478   case LibFunc::printf:
1479   case LibFunc::perror:
1480     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1481       return false;
1482     setDoesNotThrow(F);
1483     setDoesNotCapture(F, 1);
1484     setOnlyReadsMemory(F, 1);
1485     break;
1486   case LibFunc::pread:
1487     if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1488       return false;
1489     // May throw; "pread" is a valid pthread cancellation point.
1490     setDoesNotCapture(F, 2);
1491     break;
1492   case LibFunc::pwrite:
1493     if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1494       return false;
1495     // May throw; "pwrite" is a valid pthread cancellation point.
1496     setDoesNotCapture(F, 2);
1497     setOnlyReadsMemory(F, 2);
1498     break;
1499   case LibFunc::putchar:
1500     setDoesNotThrow(F);
1501     break;
1502   case LibFunc::popen:
1503     if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1504         !FTy->getParamType(0)->isPointerTy() ||
1505         !FTy->getParamType(1)->isPointerTy())
1506       return false;
1507     setDoesNotThrow(F);
1508     setDoesNotAlias(F, 0);
1509     setDoesNotCapture(F, 1);
1510     setDoesNotCapture(F, 2);
1511     setOnlyReadsMemory(F, 1);
1512     setOnlyReadsMemory(F, 2);
1513     break;
1514   case LibFunc::pclose:
1515     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1516       return false;
1517     setDoesNotThrow(F);
1518     setDoesNotCapture(F, 1);
1519     break;
1520   case LibFunc::vscanf:
1521     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1522       return false;
1523     setDoesNotThrow(F);
1524     setDoesNotCapture(F, 1);
1525     setOnlyReadsMemory(F, 1);
1526     break;
1527   case LibFunc::vsscanf:
1528     if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1529         !FTy->getParamType(2)->isPointerTy())
1530       return false;
1531     setDoesNotThrow(F);
1532     setDoesNotCapture(F, 1);
1533     setDoesNotCapture(F, 2);
1534     setOnlyReadsMemory(F, 1);
1535     setOnlyReadsMemory(F, 2);
1536     break;
1537   case LibFunc::vfscanf:
1538     if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1539         !FTy->getParamType(2)->isPointerTy())
1540       return false;
1541     setDoesNotThrow(F);
1542     setDoesNotCapture(F, 1);
1543     setDoesNotCapture(F, 2);
1544     setOnlyReadsMemory(F, 2);
1545     break;
1546   case LibFunc::valloc:
1547     if (!FTy->getReturnType()->isPointerTy())
1548       return false;
1549     setDoesNotThrow(F);
1550     setDoesNotAlias(F, 0);
1551     break;
1552   case LibFunc::vprintf:
1553     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1554       return false;
1555     setDoesNotThrow(F);
1556     setDoesNotCapture(F, 1);
1557     setOnlyReadsMemory(F, 1);
1558     break;
1559   case LibFunc::vfprintf:
1560   case LibFunc::vsprintf:
1561     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1562         !FTy->getParamType(1)->isPointerTy())
1563       return false;
1564     setDoesNotThrow(F);
1565     setDoesNotCapture(F, 1);
1566     setDoesNotCapture(F, 2);
1567     setOnlyReadsMemory(F, 2);
1568     break;
1569   case LibFunc::vsnprintf:
1570     if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1571         !FTy->getParamType(2)->isPointerTy())
1572       return false;
1573     setDoesNotThrow(F);
1574     setDoesNotCapture(F, 1);
1575     setDoesNotCapture(F, 3);
1576     setOnlyReadsMemory(F, 3);
1577     break;
1578   case LibFunc::open:
1579     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1580       return false;
1581     // May throw; "open" is a valid pthread cancellation point.
1582     setDoesNotCapture(F, 1);
1583     setOnlyReadsMemory(F, 1);
1584     break;
1585   case LibFunc::opendir:
1586     if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1587         !FTy->getParamType(0)->isPointerTy())
1588       return false;
1589     setDoesNotThrow(F);
1590     setDoesNotAlias(F, 0);
1591     setDoesNotCapture(F, 1);
1592     setOnlyReadsMemory(F, 1);
1593     break;
1594   case LibFunc::tmpfile:
1595     if (!FTy->getReturnType()->isPointerTy())
1596       return false;
1597     setDoesNotThrow(F);
1598     setDoesNotAlias(F, 0);
1599     break;
1600   case LibFunc::times:
1601     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1602       return false;
1603     setDoesNotThrow(F);
1604     setDoesNotCapture(F, 1);
1605     break;
1606   case LibFunc::htonl:
1607   case LibFunc::htons:
1608   case LibFunc::ntohl:
1609   case LibFunc::ntohs:
1610     setDoesNotThrow(F);
1611     setDoesNotAccessMemory(F);
1612     break;
1613   case LibFunc::lstat:
1614     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1615         !FTy->getParamType(1)->isPointerTy())
1616       return false;
1617     setDoesNotThrow(F);
1618     setDoesNotCapture(F, 1);
1619     setDoesNotCapture(F, 2);
1620     setOnlyReadsMemory(F, 1);
1621     break;
1622   case LibFunc::lchown:
1623     if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1624       return false;
1625     setDoesNotThrow(F);
1626     setDoesNotCapture(F, 1);
1627     setOnlyReadsMemory(F, 1);
1628     break;
1629   case LibFunc::qsort:
1630     if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1631       return false;
1632     // May throw; places call through function pointer.
1633     setDoesNotCapture(F, 4);
1634     break;
1635   case LibFunc::dunder_strdup:
1636   case LibFunc::dunder_strndup:
1637     if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1638         !FTy->getParamType(0)->isPointerTy())
1639       return false;
1640     setDoesNotThrow(F);
1641     setDoesNotAlias(F, 0);
1642     setDoesNotCapture(F, 1);
1643     setOnlyReadsMemory(F, 1);
1644     break;
1645   case LibFunc::dunder_strtok_r:
1646     if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1647       return false;
1648     setDoesNotThrow(F);
1649     setDoesNotCapture(F, 2);
1650     setOnlyReadsMemory(F, 2);
1651     break;
1652   case LibFunc::under_IO_getc:
1653     if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1654       return false;
1655     setDoesNotThrow(F);
1656     setDoesNotCapture(F, 1);
1657     break;
1658   case LibFunc::under_IO_putc:
1659     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1660       return false;
1661     setDoesNotThrow(F);
1662     setDoesNotCapture(F, 2);
1663     break;
1664   case LibFunc::dunder_isoc99_scanf:
1665     if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1666       return false;
1667     setDoesNotThrow(F);
1668     setDoesNotCapture(F, 1);
1669     setOnlyReadsMemory(F, 1);
1670     break;
1671   case LibFunc::stat64:
1672   case LibFunc::lstat64:
1673   case LibFunc::statvfs64:
1674     if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1675         !FTy->getParamType(1)->isPointerTy())
1676       return false;
1677     setDoesNotThrow(F);
1678     setDoesNotCapture(F, 1);
1679     setDoesNotCapture(F, 2);
1680     setOnlyReadsMemory(F, 1);
1681     break;
1682   case LibFunc::dunder_isoc99_sscanf:
1683     if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1684         !FTy->getParamType(1)->isPointerTy())
1685       return false;
1686     setDoesNotThrow(F);
1687     setDoesNotCapture(F, 1);
1688     setDoesNotCapture(F, 2);
1689     setOnlyReadsMemory(F, 1);
1690     setOnlyReadsMemory(F, 2);
1691     break;
1692   case LibFunc::fopen64:
1693     if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1694         !FTy->getParamType(0)->isPointerTy() ||
1695         !FTy->getParamType(1)->isPointerTy())
1696       return false;
1697     setDoesNotThrow(F);
1698     setDoesNotAlias(F, 0);
1699     setDoesNotCapture(F, 1);
1700     setDoesNotCapture(F, 2);
1701     setOnlyReadsMemory(F, 1);
1702     setOnlyReadsMemory(F, 2);
1703     break;
1704   case LibFunc::fseeko64:
1705   case LibFunc::ftello64:
1706     if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1707       return false;
1708     setDoesNotThrow(F);
1709     setDoesNotCapture(F, 1);
1710     break;
1711   case LibFunc::tmpfile64:
1712     if (!FTy->getReturnType()->isPointerTy())
1713       return false;
1714     setDoesNotThrow(F);
1715     setDoesNotAlias(F, 0);
1716     break;
1717   case LibFunc::fstat64:
1718   case LibFunc::fstatvfs64:
1719     if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1720       return false;
1721     setDoesNotThrow(F);
1722     setDoesNotCapture(F, 2);
1723     break;
1724   case LibFunc::open64:
1725     if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1726       return false;
1727     // May throw; "open" is a valid pthread cancellation point.
1728     setDoesNotCapture(F, 1);
1729     setOnlyReadsMemory(F, 1);
1730     break;
1731   case LibFunc::gettimeofday:
1732     if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1733         !FTy->getParamType(1)->isPointerTy())
1734       return false;
1735     // Currently some platforms have the restrict keyword on the arguments to
1736     // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1737     // arguments.
1738     setDoesNotThrow(F);
1739     setDoesNotCapture(F, 1);
1740     setDoesNotCapture(F, 2);
1741     break;
1742   default:
1743     // Didn't mark any attributes.
1744     return false;
1745   }
1746
1747   return true;
1748 }
1749
1750 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1751   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1752   bool Changed = false;
1753
1754   // We compute dedicated AA results for each function in the SCC as needed. We
1755   // use a lambda referencing external objects so that they live long enough to
1756   // be queried, but we re-use them each time.
1757   Optional<BasicAAResult> BAR;
1758   Optional<AAResults> AAR;
1759   auto AARGetter = [&](Function &F) -> AAResults & {
1760     BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1761     AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1762     return *AAR;
1763   };
1764
1765   // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1766   // whether a given CallGraphNode is in this SCC. Also track whether there are
1767   // any external or opt-none nodes that will prevent us from optimizing any
1768   // part of the SCC.
1769   SCCNodeSet SCCNodes;
1770   bool ExternalNode = false;
1771   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1772     Function *F = (*I)->getFunction();
1773     if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1774       // External node or function we're trying not to optimize - we both avoid
1775       // transform them and avoid leveraging information they provide.
1776       ExternalNode = true;
1777       continue;
1778     }
1779
1780     // When initially processing functions, also infer their prototype
1781     // attributes if they are declarations.
1782     if (F->isDeclaration())
1783       Changed |= inferPrototypeAttributes(*F, *TLI);
1784
1785     SCCNodes.insert(F);
1786   }
1787
1788   Changed |= addReadAttrs(SCCNodes, AARGetter);
1789   Changed |= addArgumentAttrs(SCCNodes);
1790
1791   // If we have no external nodes participating in the SCC, we can infer some
1792   // more precise attributes as well.
1793   if (!ExternalNode) {
1794     Changed |= addNoAliasAttrs(SCCNodes);
1795     Changed |= addNonNullAttrs(SCCNodes, *TLI);
1796   }
1797
1798   return Changed;
1799 }