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