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