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