1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
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 pass promotes "by reference" arguments to be "by value" arguments.  In
11 // practice, this means looking for internal functions that have pointer
12 // arguments.  If it can prove, through the use of alias analysis, that an
13 // argument is *only* loaded, then it can pass the value into the function
14 // instead of the address of the value.  This can cause recursive simplification
15 // of code and lead to the elimination of allocas (especially in C++ template
16 // code like the STL).
17 //
18 // This pass also handles aggregate arguments that are passed into a function,
19 // scalarizing them if the elements of the aggregate are only loaded.  Note that
20 // by default it refuses to scalarize aggregates which would require passing in
21 // more than three operands to the function, because passing thousands of
22 // operands for a large array or structure is unprofitable! This limit can be
23 // configured or disabled, however.
24 //
25 // Note that this transformation could also be done for arguments that are only
26 // stored to (returning the value instead), but does not currently.  This case
27 // would be best handled when and if LLVM begins supporting multiple return
28 // values from functions.
29 //
30 //===----------------------------------------------------------------------===//
31 
32 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Analysis/AliasAnalysis.h"
38 #include "llvm/Analysis/AssumptionCache.h"
39 #include "llvm/Analysis/BasicAliasAnalysis.h"
40 #include "llvm/Analysis/CallGraph.h"
41 #include "llvm/Analysis/CallGraphSCCPass.h"
42 #include "llvm/Analysis/LazyCallGraph.h"
43 #include "llvm/Analysis/Loads.h"
44 #include "llvm/Analysis/TargetLibraryInfo.h"
45 #include "llvm/IR/AttributeSetNode.h"
46 #include "llvm/IR/CFG.h"
47 #include "llvm/IR/CallSite.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugInfo.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Transforms/IPO.h"
58 #include <set>
59 using namespace llvm;
60 
61 #define DEBUG_TYPE "argpromotion"
62 
63 STATISTIC(NumArgumentsPromoted, "Number of pointer arguments promoted");
64 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
65 STATISTIC(NumByValArgsPromoted, "Number of byval arguments promoted");
66 STATISTIC(NumArgumentsDead, "Number of dead pointer args eliminated");
67 
68 /// A vector used to hold the indices of a single GEP instruction
69 typedef std::vector<uint64_t> IndicesVector;
70 
71 /// DoPromotion - This method actually performs the promotion of the specified
72 /// arguments, and returns the new function.  At this point, we know that it's
73 /// safe to do so.
74 static Function *
75 doPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote,
76             SmallPtrSetImpl<Argument *> &ByValArgsToTransform,
77             Optional<function_ref<void(CallSite OldCS, CallSite NewCS)>>
78                 ReplaceCallSite) {
79 
80   // Start by computing a new prototype for the function, which is the same as
81   // the old function, but has modified arguments.
82   FunctionType *FTy = F->getFunctionType();
83   std::vector<Type *> Params;
84 
85   typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable;
86 
87   // ScalarizedElements - If we are promoting a pointer that has elements
88   // accessed out of it, keep track of which elements are accessed so that we
89   // can add one argument for each.
90   //
91   // Arguments that are directly loaded will have a zero element value here, to
92   // handle cases where there are both a direct load and GEP accesses.
93   //
94   std::map<Argument *, ScalarizeTable> ScalarizedElements;
95 
96   // OriginalLoads - Keep track of a representative load instruction from the
97   // original function so that we can tell the alias analysis implementation
98   // what the new GEP/Load instructions we are inserting look like.
99   // We need to keep the original loads for each argument and the elements
100   // of the argument that are accessed.
101   std::map<std::pair<Argument *, IndicesVector>, LoadInst *> OriginalLoads;
102 
103   // Attribute - Keep track of the parameter attributes for the arguments
104   // that we are *not* promoting. For the ones that we do promote, the parameter
105   // attributes are lost
106   SmallVector<AttributeSetNode *, 8> AttributesVec;
107   const AttributeList &PAL = F->getAttributes();
108 
109   // Add any return attributes.
110   AttributesVec.push_back(PAL.getRetAttributes());
111 
112   // First, determine the new argument list
113   unsigned ArgIndex = 1;
114   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
115        ++I, ++ArgIndex) {
116     if (ByValArgsToTransform.count(&*I)) {
117       // Simple byval argument? Just add all the struct element types.
118       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
119       StructType *STy = cast<StructType>(AgTy);
120       Params.insert(Params.end(), STy->element_begin(), STy->element_end());
121       AttributesVec.insert(AttributesVec.end(), STy->getNumElements(), nullptr);
122       ++NumByValArgsPromoted;
123     } else if (!ArgsToPromote.count(&*I)) {
124       // Unchanged argument
125       Params.push_back(I->getType());
126       AttributesVec.push_back(PAL.getParamAttributes(ArgIndex));
127     } else if (I->use_empty()) {
128       // Dead argument (which are always marked as promotable)
129       ++NumArgumentsDead;
130     } else {
131       // Okay, this is being promoted. This means that the only uses are loads
132       // or GEPs which are only used by loads
133 
134       // In this table, we will track which indices are loaded from the argument
135       // (where direct loads are tracked as no indices).
136       ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
137       for (User *U : I->users()) {
138         Instruction *UI = cast<Instruction>(U);
139         Type *SrcTy;
140         if (LoadInst *L = dyn_cast<LoadInst>(UI))
141           SrcTy = L->getType();
142         else
143           SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
144         IndicesVector Indices;
145         Indices.reserve(UI->getNumOperands() - 1);
146         // Since loads will only have a single operand, and GEPs only a single
147         // non-index operand, this will record direct loads without any indices,
148         // and gep+loads with the GEP indices.
149         for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
150              II != IE; ++II)
151           Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
152         // GEPs with a single 0 index can be merged with direct loads
153         if (Indices.size() == 1 && Indices.front() == 0)
154           Indices.clear();
155         ArgIndices.insert(std::make_pair(SrcTy, Indices));
156         LoadInst *OrigLoad;
157         if (LoadInst *L = dyn_cast<LoadInst>(UI))
158           OrigLoad = L;
159         else
160           // Take any load, we will use it only to update Alias Analysis
161           OrigLoad = cast<LoadInst>(UI->user_back());
162         OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
163       }
164 
165       // Add a parameter to the function for each element passed in.
166       for (const auto &ArgIndex : ArgIndices) {
167         // not allowed to dereference ->begin() if size() is 0
168         Params.push_back(GetElementPtrInst::getIndexedType(
169             cast<PointerType>(I->getType()->getScalarType())->getElementType(),
170             ArgIndex.second));
171         AttributesVec.push_back(nullptr);
172         assert(Params.back());
173       }
174 
175       if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
176         ++NumArgumentsPromoted;
177       else
178         ++NumAggregatesPromoted;
179     }
180   }
181 
182   // Add any function attributes.
183   AttributesVec.push_back(PAL.getFnAttributes());
184 
185   Type *RetTy = FTy->getReturnType();
186 
187   // Construct the new function type using the new arguments.
188   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
189 
190   // Create the new function body and insert it into the module.
191   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
192   NF->copyAttributesFrom(F);
193 
194   // Patch the pointer to LLVM function in debug info descriptor.
195   NF->setSubprogram(F->getSubprogram());
196   F->setSubprogram(nullptr);
197 
198   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
199                << "From: " << *F);
200 
201   // Recompute the parameter attributes list based on the new arguments for
202   // the function.
203   NF->setAttributes(AttributeList::get(F->getContext(), AttributesVec));
204   AttributesVec.clear();
205 
206   F->getParent()->getFunctionList().insert(F->getIterator(), NF);
207   NF->takeName(F);
208 
209   // Loop over all of the callers of the function, transforming the call sites
210   // to pass in the loaded pointers.
211   //
212   SmallVector<Value *, 16> Args;
213   while (!F->use_empty()) {
214     CallSite CS(F->user_back());
215     assert(CS.getCalledFunction() == F);
216     Instruction *Call = CS.getInstruction();
217     const AttributeList &CallPAL = CS.getAttributes();
218 
219     // Add any return attributes.
220     AttributesVec.push_back(CallPAL.getRetAttributes());
221 
222     // Loop over the operands, inserting GEP and loads in the caller as
223     // appropriate.
224     CallSite::arg_iterator AI = CS.arg_begin();
225     ArgIndex = 1;
226     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
227          ++I, ++AI, ++ArgIndex)
228       if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
229         Args.push_back(*AI); // Unmodified argument
230         AttributesVec.push_back(CallPAL.getAttributes(ArgIndex));
231       } else if (ByValArgsToTransform.count(&*I)) {
232         // Emit a GEP and load for each element of the struct.
233         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
234         StructType *STy = cast<StructType>(AgTy);
235         Value *Idxs[2] = {
236             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr};
237         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
238           Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
239           Value *Idx = GetElementPtrInst::Create(
240               STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call);
241           // TODO: Tell AA about the new values?
242           Args.push_back(new LoadInst(Idx, Idx->getName() + ".val", Call));
243           AttributesVec.push_back(nullptr);
244         }
245       } else if (!I->use_empty()) {
246         // Non-dead argument: insert GEPs and loads as appropriate.
247         ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
248         // Store the Value* version of the indices in here, but declare it now
249         // for reuse.
250         std::vector<Value *> Ops;
251         for (const auto &ArgIndex : ArgIndices) {
252           Value *V = *AI;
253           LoadInst *OrigLoad =
254               OriginalLoads[std::make_pair(&*I, ArgIndex.second)];
255           if (!ArgIndex.second.empty()) {
256             Ops.reserve(ArgIndex.second.size());
257             Type *ElTy = V->getType();
258             for (unsigned long II : ArgIndex.second) {
259               // Use i32 to index structs, and i64 for others (pointers/arrays).
260               // This satisfies GEP constraints.
261               Type *IdxTy =
262                   (ElTy->isStructTy() ? Type::getInt32Ty(F->getContext())
263                                       : Type::getInt64Ty(F->getContext()));
264               Ops.push_back(ConstantInt::get(IdxTy, II));
265               // Keep track of the type we're currently indexing.
266               if (auto *ElPTy = dyn_cast<PointerType>(ElTy))
267                 ElTy = ElPTy->getElementType();
268               else
269                 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(II);
270             }
271             // And create a GEP to extract those indices.
272             V = GetElementPtrInst::Create(ArgIndex.first, V, Ops,
273                                           V->getName() + ".idx", Call);
274             Ops.clear();
275           }
276           // Since we're replacing a load make sure we take the alignment
277           // of the previous load.
278           LoadInst *newLoad = new LoadInst(V, V->getName() + ".val", Call);
279           newLoad->setAlignment(OrigLoad->getAlignment());
280           // Transfer the AA info too.
281           AAMDNodes AAInfo;
282           OrigLoad->getAAMetadata(AAInfo);
283           newLoad->setAAMetadata(AAInfo);
284 
285           Args.push_back(newLoad);
286           AttributesVec.push_back(nullptr);
287         }
288       }
289 
290     // Push any varargs arguments on the list.
291     for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
292       Args.push_back(*AI);
293       AttributesVec.push_back(CallPAL.getAttributes(ArgIndex));
294     }
295 
296     // Add any function attributes.
297     AttributesVec.push_back(CallPAL.getFnAttributes());
298 
299     SmallVector<OperandBundleDef, 1> OpBundles;
300     CS.getOperandBundlesAsDefs(OpBundles);
301 
302     Instruction *New;
303     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
304       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
305                                Args, OpBundles, "", Call);
306       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
307       cast<InvokeInst>(New)->setAttributes(
308           AttributeList::get(II->getContext(), AttributesVec));
309     } else {
310       New = CallInst::Create(NF, Args, OpBundles, "", Call);
311       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
312       cast<CallInst>(New)->setAttributes(
313           AttributeList::get(New->getContext(), AttributesVec));
314       cast<CallInst>(New)->setTailCallKind(
315           cast<CallInst>(Call)->getTailCallKind());
316     }
317     New->setDebugLoc(Call->getDebugLoc());
318     Args.clear();
319     AttributesVec.clear();
320 
321     // Update the callgraph to know that the callsite has been transformed.
322     if (ReplaceCallSite)
323       (*ReplaceCallSite)(CS, CallSite(New));
324 
325     if (!Call->use_empty()) {
326       Call->replaceAllUsesWith(New);
327       New->takeName(Call);
328     }
329 
330     // Finally, remove the old call from the program, reducing the use-count of
331     // F.
332     Call->eraseFromParent();
333   }
334 
335   const DataLayout &DL = F->getParent()->getDataLayout();
336 
337   // Since we have now created the new function, splice the body of the old
338   // function right into the new function, leaving the old rotting hulk of the
339   // function empty.
340   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
341 
342   // Loop over the argument list, transferring uses of the old arguments over to
343   // the new arguments, also transferring over the names as well.
344   //
345   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
346                               I2 = NF->arg_begin();
347        I != E; ++I) {
348     if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
349       // If this is an unmodified argument, move the name and users over to the
350       // new version.
351       I->replaceAllUsesWith(&*I2);
352       I2->takeName(&*I);
353       ++I2;
354       continue;
355     }
356 
357     if (ByValArgsToTransform.count(&*I)) {
358       // In the callee, we create an alloca, and store each of the new incoming
359       // arguments into the alloca.
360       Instruction *InsertPt = &NF->begin()->front();
361 
362       // Just add all the struct element types.
363       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
364       Value *TheAlloca = new AllocaInst(AgTy, DL.getAllocaAddrSpace(), nullptr,
365                                         "", InsertPt);
366       StructType *STy = cast<StructType>(AgTy);
367       Value *Idxs[2] = {ConstantInt::get(Type::getInt32Ty(F->getContext()), 0),
368                         nullptr};
369 
370       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
371         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
372         Value *Idx = GetElementPtrInst::Create(
373             AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
374             InsertPt);
375         I2->setName(I->getName() + "." + Twine(i));
376         new StoreInst(&*I2++, Idx, InsertPt);
377       }
378 
379       // Anything that used the arg should now use the alloca.
380       I->replaceAllUsesWith(TheAlloca);
381       TheAlloca->takeName(&*I);
382 
383       // If the alloca is used in a call, we must clear the tail flag since
384       // the callee now uses an alloca from the caller.
385       for (User *U : TheAlloca->users()) {
386         CallInst *Call = dyn_cast<CallInst>(U);
387         if (!Call)
388           continue;
389         Call->setTailCall(false);
390       }
391       continue;
392     }
393 
394     if (I->use_empty())
395       continue;
396 
397     // Otherwise, if we promoted this argument, then all users are load
398     // instructions (or GEPs with only load users), and all loads should be
399     // using the new argument that we added.
400     ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
401 
402     while (!I->use_empty()) {
403       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
404         assert(ArgIndices.begin()->second.empty() &&
405                "Load element should sort to front!");
406         I2->setName(I->getName() + ".val");
407         LI->replaceAllUsesWith(&*I2);
408         LI->eraseFromParent();
409         DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
410                      << "' in function '" << F->getName() << "'\n");
411       } else {
412         GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
413         IndicesVector Operands;
414         Operands.reserve(GEP->getNumIndices());
415         for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
416              II != IE; ++II)
417           Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
418 
419         // GEPs with a single 0 index can be merged with direct loads
420         if (Operands.size() == 1 && Operands.front() == 0)
421           Operands.clear();
422 
423         Function::arg_iterator TheArg = I2;
424         for (ScalarizeTable::iterator It = ArgIndices.begin();
425              It->second != Operands; ++It, ++TheArg) {
426           assert(It != ArgIndices.end() && "GEP not handled??");
427         }
428 
429         std::string NewName = I->getName();
430         for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
431           NewName += "." + utostr(Operands[i]);
432         }
433         NewName += ".val";
434         TheArg->setName(NewName);
435 
436         DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
437                      << "' of function '" << NF->getName() << "'\n");
438 
439         // All of the uses must be load instructions.  Replace them all with
440         // the argument specified by ArgNo.
441         while (!GEP->use_empty()) {
442           LoadInst *L = cast<LoadInst>(GEP->user_back());
443           L->replaceAllUsesWith(&*TheArg);
444           L->eraseFromParent();
445         }
446         GEP->eraseFromParent();
447       }
448     }
449 
450     // Increment I2 past all of the arguments added for this promoted pointer.
451     std::advance(I2, ArgIndices.size());
452   }
453 
454   return NF;
455 }
456 
457 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that
458 /// all callees pass in a valid pointer for the specified function argument.
459 static bool allCallersPassInValidPointerForArgument(Argument *Arg) {
460   Function *Callee = Arg->getParent();
461   const DataLayout &DL = Callee->getParent()->getDataLayout();
462 
463   unsigned ArgNo = Arg->getArgNo();
464 
465   // Look at all call sites of the function.  At this point we know we only have
466   // direct callees.
467   for (User *U : Callee->users()) {
468     CallSite CS(U);
469     assert(CS && "Should only have direct calls!");
470 
471     if (!isDereferenceablePointer(CS.getArgument(ArgNo), DL))
472       return false;
473   }
474   return true;
475 }
476 
477 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
478 /// that is greater than or equal to the size of prefix, and each of the
479 /// elements in Prefix is the same as the corresponding elements in Longer.
480 ///
481 /// This means it also returns true when Prefix and Longer are equal!
482 static bool isPrefix(const IndicesVector &Prefix, const IndicesVector &Longer) {
483   if (Prefix.size() > Longer.size())
484     return false;
485   return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
486 }
487 
488 /// Checks if Indices, or a prefix of Indices, is in Set.
489 static bool prefixIn(const IndicesVector &Indices,
490                      std::set<IndicesVector> &Set) {
491   std::set<IndicesVector>::iterator Low;
492   Low = Set.upper_bound(Indices);
493   if (Low != Set.begin())
494     Low--;
495   // Low is now the last element smaller than or equal to Indices. This means
496   // it points to a prefix of Indices (possibly Indices itself), if such
497   // prefix exists.
498   //
499   // This load is safe if any prefix of its operands is safe to load.
500   return Low != Set.end() && isPrefix(*Low, Indices);
501 }
502 
503 /// Mark the given indices (ToMark) as safe in the given set of indices
504 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
505 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
506 /// already. Furthermore, any indices that Indices is itself a prefix of, are
507 /// removed from Safe (since they are implicitely safe because of Indices now).
508 static void markIndicesSafe(const IndicesVector &ToMark,
509                             std::set<IndicesVector> &Safe) {
510   std::set<IndicesVector>::iterator Low;
511   Low = Safe.upper_bound(ToMark);
512   // Guard against the case where Safe is empty
513   if (Low != Safe.begin())
514     Low--;
515   // Low is now the last element smaller than or equal to Indices. This
516   // means it points to a prefix of Indices (possibly Indices itself), if
517   // such prefix exists.
518   if (Low != Safe.end()) {
519     if (isPrefix(*Low, ToMark))
520       // If there is already a prefix of these indices (or exactly these
521       // indices) marked a safe, don't bother adding these indices
522       return;
523 
524     // Increment Low, so we can use it as a "insert before" hint
525     ++Low;
526   }
527   // Insert
528   Low = Safe.insert(Low, ToMark);
529   ++Low;
530   // If there we're a prefix of longer index list(s), remove those
531   std::set<IndicesVector>::iterator End = Safe.end();
532   while (Low != End && isPrefix(ToMark, *Low)) {
533     std::set<IndicesVector>::iterator Remove = Low;
534     ++Low;
535     Safe.erase(Remove);
536   }
537 }
538 
539 /// isSafeToPromoteArgument - As you might guess from the name of this method,
540 /// it checks to see if it is both safe and useful to promote the argument.
541 /// This method limits promotion of aggregates to only promote up to three
542 /// elements of the aggregate in order to avoid exploding the number of
543 /// arguments passed in.
544 static bool isSafeToPromoteArgument(Argument *Arg, bool isByValOrInAlloca,
545                                     AAResults &AAR, unsigned MaxElements) {
546   typedef std::set<IndicesVector> GEPIndicesSet;
547 
548   // Quick exit for unused arguments
549   if (Arg->use_empty())
550     return true;
551 
552   // We can only promote this argument if all of the uses are loads, or are GEP
553   // instructions (with constant indices) that are subsequently loaded.
554   //
555   // Promoting the argument causes it to be loaded in the caller
556   // unconditionally. This is only safe if we can prove that either the load
557   // would have happened in the callee anyway (ie, there is a load in the entry
558   // block) or the pointer passed in at every call site is guaranteed to be
559   // valid.
560   // In the former case, invalid loads can happen, but would have happened
561   // anyway, in the latter case, invalid loads won't happen. This prevents us
562   // from introducing an invalid load that wouldn't have happened in the
563   // original code.
564   //
565   // This set will contain all sets of indices that are loaded in the entry
566   // block, and thus are safe to unconditionally load in the caller.
567   //
568   // This optimization is also safe for InAlloca parameters, because it verifies
569   // that the address isn't captured.
570   GEPIndicesSet SafeToUnconditionallyLoad;
571 
572   // This set contains all the sets of indices that we are planning to promote.
573   // This makes it possible to limit the number of arguments added.
574   GEPIndicesSet ToPromote;
575 
576   // If the pointer is always valid, any load with first index 0 is valid.
577   if (isByValOrInAlloca || allCallersPassInValidPointerForArgument(Arg))
578     SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
579 
580   // First, iterate the entry block and mark loads of (geps of) arguments as
581   // safe.
582   BasicBlock &EntryBlock = Arg->getParent()->front();
583   // Declare this here so we can reuse it
584   IndicesVector Indices;
585   for (Instruction &I : EntryBlock)
586     if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
587       Value *V = LI->getPointerOperand();
588       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
589         V = GEP->getPointerOperand();
590         if (V == Arg) {
591           // This load actually loads (part of) Arg? Check the indices then.
592           Indices.reserve(GEP->getNumIndices());
593           for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
594                II != IE; ++II)
595             if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
596               Indices.push_back(CI->getSExtValue());
597             else
598               // We found a non-constant GEP index for this argument? Bail out
599               // right away, can't promote this argument at all.
600               return false;
601 
602           // Indices checked out, mark them as safe
603           markIndicesSafe(Indices, SafeToUnconditionallyLoad);
604           Indices.clear();
605         }
606       } else if (V == Arg) {
607         // Direct loads are equivalent to a GEP with a single 0 index.
608         markIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
609       }
610     }
611 
612   // Now, iterate all uses of the argument to see if there are any uses that are
613   // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
614   SmallVector<LoadInst *, 16> Loads;
615   IndicesVector Operands;
616   for (Use &U : Arg->uses()) {
617     User *UR = U.getUser();
618     Operands.clear();
619     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
620       // Don't hack volatile/atomic loads
621       if (!LI->isSimple())
622         return false;
623       Loads.push_back(LI);
624       // Direct loads are equivalent to a GEP with a zero index and then a load.
625       Operands.push_back(0);
626     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
627       if (GEP->use_empty()) {
628         // Dead GEP's cause trouble later.  Just remove them if we run into
629         // them.
630         GEP->eraseFromParent();
631         // TODO: This runs the above loop over and over again for dead GEPs
632         // Couldn't we just do increment the UI iterator earlier and erase the
633         // use?
634         return isSafeToPromoteArgument(Arg, isByValOrInAlloca, AAR,
635                                        MaxElements);
636       }
637 
638       // Ensure that all of the indices are constants.
639       for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end(); i != e;
640            ++i)
641         if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
642           Operands.push_back(C->getSExtValue());
643         else
644           return false; // Not a constant operand GEP!
645 
646       // Ensure that the only users of the GEP are load instructions.
647       for (User *GEPU : GEP->users())
648         if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
649           // Don't hack volatile/atomic loads
650           if (!LI->isSimple())
651             return false;
652           Loads.push_back(LI);
653         } else {
654           // Other uses than load?
655           return false;
656         }
657     } else {
658       return false; // Not a load or a GEP.
659     }
660 
661     // Now, see if it is safe to promote this load / loads of this GEP. Loading
662     // is safe if Operands, or a prefix of Operands, is marked as safe.
663     if (!prefixIn(Operands, SafeToUnconditionallyLoad))
664       return false;
665 
666     // See if we are already promoting a load with these indices. If not, check
667     // to make sure that we aren't promoting too many elements.  If so, nothing
668     // to do.
669     if (ToPromote.find(Operands) == ToPromote.end()) {
670       if (MaxElements > 0 && ToPromote.size() == MaxElements) {
671         DEBUG(dbgs() << "argpromotion not promoting argument '"
672                      << Arg->getName()
673                      << "' because it would require adding more "
674                      << "than " << MaxElements
675                      << " arguments to the function.\n");
676         // We limit aggregate promotion to only promoting up to a fixed number
677         // of elements of the aggregate.
678         return false;
679       }
680       ToPromote.insert(std::move(Operands));
681     }
682   }
683 
684   if (Loads.empty())
685     return true; // No users, this is a dead argument.
686 
687   // Okay, now we know that the argument is only used by load instructions and
688   // it is safe to unconditionally perform all of them. Use alias analysis to
689   // check to see if the pointer is guaranteed to not be modified from entry of
690   // the function to each of the load instructions.
691 
692   // Because there could be several/many load instructions, remember which
693   // blocks we know to be transparent to the load.
694   df_iterator_default_set<BasicBlock *, 16> TranspBlocks;
695 
696   for (LoadInst *Load : Loads) {
697     // Check to see if the load is invalidated from the start of the block to
698     // the load itself.
699     BasicBlock *BB = Load->getParent();
700 
701     MemoryLocation Loc = MemoryLocation::get(Load);
702     if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, MRI_Mod))
703       return false; // Pointer is invalidated!
704 
705     // Now check every path from the entry block to the load for transparency.
706     // To do this, we perform a depth first search on the inverse CFG from the
707     // loading block.
708     for (BasicBlock *P : predecessors(BB)) {
709       for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
710         if (AAR.canBasicBlockModify(*TranspBB, Loc))
711           return false;
712     }
713   }
714 
715   // If the path from the entry of the function to each load is free of
716   // instructions that potentially invalidate the load, we can make the
717   // transformation!
718   return true;
719 }
720 
721 /// \brief Checks if a type could have padding bytes.
722 static bool isDenselyPacked(Type *type, const DataLayout &DL) {
723 
724   // There is no size information, so be conservative.
725   if (!type->isSized())
726     return false;
727 
728   // If the alloc size is not equal to the storage size, then there are padding
729   // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
730   if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
731     return false;
732 
733   if (!isa<CompositeType>(type))
734     return true;
735 
736   // For homogenous sequential types, check for padding within members.
737   if (SequentialType *seqTy = dyn_cast<SequentialType>(type))
738     return isDenselyPacked(seqTy->getElementType(), DL);
739 
740   // Check for padding within and between elements of a struct.
741   StructType *StructTy = cast<StructType>(type);
742   const StructLayout *Layout = DL.getStructLayout(StructTy);
743   uint64_t StartPos = 0;
744   for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
745     Type *ElTy = StructTy->getElementType(i);
746     if (!isDenselyPacked(ElTy, DL))
747       return false;
748     if (StartPos != Layout->getElementOffsetInBits(i))
749       return false;
750     StartPos += DL.getTypeAllocSizeInBits(ElTy);
751   }
752 
753   return true;
754 }
755 
756 /// \brief Checks if the padding bytes of an argument could be accessed.
757 static bool canPaddingBeAccessed(Argument *arg) {
758 
759   assert(arg->hasByValAttr());
760 
761   // Track all the pointers to the argument to make sure they are not captured.
762   SmallPtrSet<Value *, 16> PtrValues;
763   PtrValues.insert(arg);
764 
765   // Track all of the stores.
766   SmallVector<StoreInst *, 16> Stores;
767 
768   // Scan through the uses recursively to make sure the pointer is always used
769   // sanely.
770   SmallVector<Value *, 16> WorkList;
771   WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end());
772   while (!WorkList.empty()) {
773     Value *V = WorkList.back();
774     WorkList.pop_back();
775     if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
776       if (PtrValues.insert(V).second)
777         WorkList.insert(WorkList.end(), V->user_begin(), V->user_end());
778     } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
779       Stores.push_back(Store);
780     } else if (!isa<LoadInst>(V)) {
781       return true;
782     }
783   }
784 
785   // Check to make sure the pointers aren't captured
786   for (StoreInst *Store : Stores)
787     if (PtrValues.count(Store->getValueOperand()))
788       return true;
789 
790   return false;
791 }
792 
793 /// PromoteArguments - This method checks the specified function to see if there
794 /// are any promotable arguments and if it is safe to promote the function (for
795 /// example, all callers are direct).  If safe to promote some arguments, it
796 /// calls the DoPromotion method.
797 ///
798 static Function *
799 promoteArguments(Function *F, function_ref<AAResults &(Function &F)> AARGetter,
800                  unsigned MaxElements,
801                  Optional<function_ref<void(CallSite OldCS, CallSite NewCS)>>
802                      ReplaceCallSite) {
803   // Make sure that it is local to this module.
804   if (!F->hasLocalLinkage())
805     return nullptr;
806 
807   // Don't promote arguments for variadic functions. Adding, removing, or
808   // changing non-pack parameters can change the classification of pack
809   // parameters. Frontends encode that classification at the call site in the
810   // IR, while in the callee the classification is determined dynamically based
811   // on the number of registers consumed so far.
812   if (F->isVarArg())
813     return nullptr;
814 
815   // First check: see if there are any pointer arguments!  If not, quick exit.
816   SmallVector<Argument *, 16> PointerArgs;
817   for (Argument &I : F->args())
818     if (I.getType()->isPointerTy())
819       PointerArgs.push_back(&I);
820   if (PointerArgs.empty())
821     return nullptr;
822 
823   // Second check: make sure that all callers are direct callers.  We can't
824   // transform functions that have indirect callers.  Also see if the function
825   // is self-recursive.
826   bool isSelfRecursive = false;
827   for (Use &U : F->uses()) {
828     CallSite CS(U.getUser());
829     // Must be a direct call.
830     if (CS.getInstruction() == nullptr || !CS.isCallee(&U))
831       return nullptr;
832 
833     if (CS.getInstruction()->getParent()->getParent() == F)
834       isSelfRecursive = true;
835   }
836 
837   const DataLayout &DL = F->getParent()->getDataLayout();
838 
839   AAResults &AAR = AARGetter(*F);
840 
841   // Check to see which arguments are promotable.  If an argument is promotable,
842   // add it to ArgsToPromote.
843   SmallPtrSet<Argument *, 8> ArgsToPromote;
844   SmallPtrSet<Argument *, 8> ByValArgsToTransform;
845   for (Argument *PtrArg : PointerArgs) {
846     Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
847 
848     // Replace sret attribute with noalias. This reduces register pressure by
849     // avoiding a register copy.
850     if (PtrArg->hasStructRetAttr()) {
851       unsigned ArgNo = PtrArg->getArgNo();
852       F->setAttributes(
853           F->getAttributes()
854               .removeAttribute(F->getContext(), ArgNo + 1, Attribute::StructRet)
855               .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
856       for (Use &U : F->uses()) {
857         CallSite CS(U.getUser());
858         CS.setAttributes(
859             CS.getAttributes()
860                 .removeAttribute(F->getContext(), ArgNo + 1,
861                                  Attribute::StructRet)
862                 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
863       }
864     }
865 
866     // If this is a byval argument, and if the aggregate type is small, just
867     // pass the elements, which is always safe, if the passed value is densely
868     // packed or if we can prove the padding bytes are never accessed. This does
869     // not apply to inalloca.
870     bool isSafeToPromote =
871         PtrArg->hasByValAttr() &&
872         (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg));
873     if (isSafeToPromote) {
874       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
875         if (MaxElements > 0 && STy->getNumElements() > MaxElements) {
876           DEBUG(dbgs() << "argpromotion disable promoting argument '"
877                        << PtrArg->getName()
878                        << "' because it would require adding more"
879                        << " than " << MaxElements
880                        << " arguments to the function.\n");
881           continue;
882         }
883 
884         // If all the elements are single-value types, we can promote it.
885         bool AllSimple = true;
886         for (const auto *EltTy : STy->elements()) {
887           if (!EltTy->isSingleValueType()) {
888             AllSimple = false;
889             break;
890           }
891         }
892 
893         // Safe to transform, don't even bother trying to "promote" it.
894         // Passing the elements as a scalar will allow sroa to hack on
895         // the new alloca we introduce.
896         if (AllSimple) {
897           ByValArgsToTransform.insert(PtrArg);
898           continue;
899         }
900       }
901     }
902 
903     // If the argument is a recursive type and we're in a recursive
904     // function, we could end up infinitely peeling the function argument.
905     if (isSelfRecursive) {
906       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
907         bool RecursiveType = false;
908         for (const auto *EltTy : STy->elements()) {
909           if (EltTy == PtrArg->getType()) {
910             RecursiveType = true;
911             break;
912           }
913         }
914         if (RecursiveType)
915           continue;
916       }
917     }
918 
919     // Otherwise, see if we can promote the pointer to its value.
920     if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr(), AAR,
921                                 MaxElements))
922       ArgsToPromote.insert(PtrArg);
923   }
924 
925   // No promotable pointer arguments.
926   if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
927     return nullptr;
928 
929   return doPromotion(F, ArgsToPromote, ByValArgsToTransform, ReplaceCallSite);
930 }
931 
932 PreservedAnalyses ArgumentPromotionPass::run(LazyCallGraph::SCC &C,
933                                              CGSCCAnalysisManager &AM,
934                                              LazyCallGraph &CG,
935                                              CGSCCUpdateResult &UR) {
936   bool Changed = false, LocalChange;
937 
938   // Iterate until we stop promoting from this SCC.
939   do {
940     LocalChange = false;
941 
942     for (LazyCallGraph::Node &N : C) {
943       Function &OldF = N.getFunction();
944 
945       FunctionAnalysisManager &FAM =
946           AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
947       // FIXME: This lambda must only be used with this function. We should
948       // skip the lambda and just get the AA results directly.
949       auto AARGetter = [&](Function &F) -> AAResults & {
950         assert(&F == &OldF && "Called with an unexpected function!");
951         return FAM.getResult<AAManager>(F);
952       };
953 
954       Function *NewF = promoteArguments(&OldF, AARGetter, 3u, None);
955       if (!NewF)
956         continue;
957       LocalChange = true;
958 
959       // Directly substitute the functions in the call graph. Note that this
960       // requires the old function to be completely dead and completely
961       // replaced by the new function. It does no call graph updates, it merely
962       // swaps out the particular function mapped to a particular node in the
963       // graph.
964       C.getOuterRefSCC().replaceNodeFunction(N, *NewF);
965       OldF.eraseFromParent();
966     }
967 
968     Changed |= LocalChange;
969   } while (LocalChange);
970 
971   if (!Changed)
972     return PreservedAnalyses::all();
973 
974   return PreservedAnalyses::none();
975 }
976 
977 namespace {
978 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
979 ///
980 struct ArgPromotion : public CallGraphSCCPass {
981   void getAnalysisUsage(AnalysisUsage &AU) const override {
982     AU.addRequired<AssumptionCacheTracker>();
983     AU.addRequired<TargetLibraryInfoWrapperPass>();
984     getAAResultsAnalysisUsage(AU);
985     CallGraphSCCPass::getAnalysisUsage(AU);
986   }
987 
988   bool runOnSCC(CallGraphSCC &SCC) override;
989   static char ID; // Pass identification, replacement for typeid
990   explicit ArgPromotion(unsigned MaxElements = 3)
991       : CallGraphSCCPass(ID), MaxElements(MaxElements) {
992     initializeArgPromotionPass(*PassRegistry::getPassRegistry());
993   }
994 
995 private:
996   using llvm::Pass::doInitialization;
997   bool doInitialization(CallGraph &CG) override;
998   /// The maximum number of elements to expand, or 0 for unlimited.
999   unsigned MaxElements;
1000 };
1001 }
1002 
1003 char ArgPromotion::ID = 0;
1004 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
1005                       "Promote 'by reference' arguments to scalars", false,
1006                       false)
1007 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1008 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1009 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1010 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
1011                     "Promote 'by reference' arguments to scalars", false, false)
1012 
1013 Pass *llvm::createArgumentPromotionPass(unsigned MaxElements) {
1014   return new ArgPromotion(MaxElements);
1015 }
1016 
1017 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
1018   if (skipSCC(SCC))
1019     return false;
1020 
1021   // Get the callgraph information that we need to update to reflect our
1022   // changes.
1023   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1024 
1025   LegacyAARGetter AARGetter(*this);
1026 
1027   bool Changed = false, LocalChange;
1028 
1029   // Iterate until we stop promoting from this SCC.
1030   do {
1031     LocalChange = false;
1032     // Attempt to promote arguments from all functions in this SCC.
1033     for (CallGraphNode *OldNode : SCC) {
1034       Function *OldF = OldNode->getFunction();
1035       if (!OldF)
1036         continue;
1037 
1038       auto ReplaceCallSite = [&](CallSite OldCS, CallSite NewCS) {
1039         Function *Caller = OldCS.getInstruction()->getParent()->getParent();
1040         CallGraphNode *NewCalleeNode =
1041             CG.getOrInsertFunction(NewCS.getCalledFunction());
1042         CallGraphNode *CallerNode = CG[Caller];
1043         CallerNode->replaceCallEdge(OldCS, NewCS, NewCalleeNode);
1044       };
1045 
1046       if (Function *NewF = promoteArguments(OldF, AARGetter, MaxElements,
1047                                             {ReplaceCallSite})) {
1048         LocalChange = true;
1049 
1050         // Update the call graph for the newly promoted function.
1051         CallGraphNode *NewNode = CG.getOrInsertFunction(NewF);
1052         NewNode->stealCalledFunctionsFrom(OldNode);
1053         if (OldNode->getNumReferences() == 0)
1054           delete CG.removeFunctionFromModule(OldNode);
1055         else
1056           OldF->setLinkage(Function::ExternalLinkage);
1057 
1058         // And updat ethe SCC we're iterating as well.
1059         SCC.ReplaceNode(OldNode, NewNode);
1060       }
1061     }
1062     // Remember that we changed something.
1063     Changed |= LocalChange;
1064   } while (LocalChange);
1065 
1066   return Changed;
1067 }
1068 
1069 bool ArgPromotion::doInitialization(CallGraph &CG) {
1070   return CallGraphSCCPass::doInitialization(CG);
1071 }
1072