1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source 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 we can prove, through the use of alias analysis, that an 13 // argument is *only* loaded, then we 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 // we refuse to scalarize aggregates which would require passing in more than 21 // three operands to the function, because we don't want to pass thousands of 22 // operands for a large array or structure! 23 // 24 // Note that this transformation could also be done for arguments that are only 25 // stored to (returning the value instead), but we do not currently handle that 26 // case. This case would be best handled when and if we start supporting 27 // multiple return values from functions. 28 // 29 //===----------------------------------------------------------------------===// 30 31 #define DEBUG_TYPE "argpromotion" 32 #include "llvm/Transforms/IPO.h" 33 #include "llvm/Constants.h" 34 #include "llvm/DerivedTypes.h" 35 #include "llvm/Module.h" 36 #include "llvm/CallGraphSCCPass.h" 37 #include "llvm/Instructions.h" 38 #include "llvm/Analysis/AliasAnalysis.h" 39 #include "llvm/Analysis/CallGraph.h" 40 #include "llvm/Target/TargetData.h" 41 #include "llvm/Support/CallSite.h" 42 #include "llvm/Support/CFG.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/ADT/DepthFirstIterator.h" 45 #include "llvm/ADT/Statistic.h" 46 #include "llvm/ADT/StringExtras.h" 47 #include <set> 48 using namespace llvm; 49 50 namespace { 51 Statistic<> NumArgumentsPromoted("argpromotion", 52 "Number of pointer arguments promoted"); 53 Statistic<> NumAggregatesPromoted("argpromotion", 54 "Number of aggregate arguments promoted"); 55 Statistic<> NumArgumentsDead("argpromotion", 56 "Number of dead pointer args eliminated"); 57 58 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass. 59 /// 60 struct ArgPromotion : public CallGraphSCCPass { 61 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 62 AU.addRequired<AliasAnalysis>(); 63 AU.addRequired<TargetData>(); 64 CallGraphSCCPass::getAnalysisUsage(AU); 65 } 66 67 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC); 68 private: 69 bool PromoteArguments(CallGraphNode *CGN); 70 bool isSafeToPromoteArgument(Argument *Arg) const; 71 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote); 72 }; 73 74 RegisterOpt<ArgPromotion> X("argpromotion", 75 "Promote 'by reference' arguments to scalars"); 76 } 77 78 ModulePass *llvm::createArgumentPromotionPass() { 79 return new ArgPromotion(); 80 } 81 82 bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) { 83 bool Changed = false, LocalChange; 84 85 do { // Iterate until we stop promoting from this SCC. 86 LocalChange = false; 87 // Attempt to promote arguments from all functions in this SCC. 88 for (unsigned i = 0, e = SCC.size(); i != e; ++i) 89 LocalChange |= PromoteArguments(SCC[i]); 90 Changed |= LocalChange; // Remember that we changed something. 91 } while (LocalChange); 92 93 return Changed; 94 } 95 96 /// PromoteArguments - This method checks the specified function to see if there 97 /// are any promotable arguments and if it is safe to promote the function (for 98 /// example, all callers are direct). If safe to promote some arguments, it 99 /// calls the DoPromotion method. 100 /// 101 bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) { 102 Function *F = CGN->getFunction(); 103 104 // Make sure that it is local to this module. 105 if (!F || !F->hasInternalLinkage()) return false; 106 107 // First check: see if there are any pointer arguments! If not, quick exit. 108 std::vector<Argument*> PointerArgs; 109 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 110 if (isa<PointerType>(I->getType())) 111 PointerArgs.push_back(I); 112 if (PointerArgs.empty()) return false; 113 114 // Second check: make sure that all callers are direct callers. We can't 115 // transform functions that have indirect callers. 116 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); 117 UI != E; ++UI) { 118 CallSite CS = CallSite::get(*UI); 119 if (!CS.getInstruction()) // "Taking the address" of the function 120 return false; 121 122 // Ensure that this call site is CALLING the function, not passing it as 123 // an argument. 124 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); 125 AI != E; ++AI) 126 if (*AI == F) return false; // Passing the function address in! 127 } 128 129 // Check to see which arguments are promotable. If an argument is not 130 // promotable, remove it from the PointerArgs vector. 131 for (unsigned i = 0; i != PointerArgs.size(); ++i) 132 if (!isSafeToPromoteArgument(PointerArgs[i])) { 133 std::swap(PointerArgs[i--], PointerArgs.back()); 134 PointerArgs.pop_back(); 135 } 136 137 // No promotable pointer arguments. 138 if (PointerArgs.empty()) return false; 139 140 // Okay, promote all of the arguments are rewrite the callees! 141 Function *NewF = DoPromotion(F, PointerArgs); 142 143 // Update the call graph to know that the old function is gone. 144 getAnalysis<CallGraph>().changeFunction(F, NewF); 145 return true; 146 } 147 148 /// IsAlwaysValidPointer - Return true if the specified pointer is always legal 149 /// to load. 150 static bool IsAlwaysValidPointer(Value *V) { 151 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true; 152 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) 153 return IsAlwaysValidPointer(GEP->getOperand(0)); 154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 155 if (CE->getOpcode() == Instruction::GetElementPtr) 156 return IsAlwaysValidPointer(CE->getOperand(0)); 157 158 return false; 159 } 160 161 /// AllCalleesPassInValidPointerForArgument - Return true if we can prove that 162 /// all callees pass in a valid pointer for the specified function argument. 163 static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) { 164 Function *Callee = Arg->getParent(); 165 166 unsigned ArgNo = std::distance(Callee->arg_begin(), Function::arg_iterator(Arg)); 167 168 // Look at all call sites of the function. At this pointer we know we only 169 // have direct callees. 170 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end(); 171 UI != E; ++UI) { 172 CallSite CS = CallSite::get(*UI); 173 assert(CS.getInstruction() && "Should only have direct calls!"); 174 175 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo))) 176 return false; 177 } 178 return true; 179 } 180 181 182 /// isSafeToPromoteArgument - As you might guess from the name of this method, 183 /// it checks to see if it is both safe and useful to promote the argument. 184 /// This method limits promotion of aggregates to only promote up to three 185 /// elements of the aggregate in order to avoid exploding the number of 186 /// arguments passed in. 187 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const { 188 // We can only promote this argument if all of the uses are loads, or are GEP 189 // instructions (with constant indices) that are subsequently loaded. 190 bool HasLoadInEntryBlock = false; 191 BasicBlock *EntryBlock = Arg->getParent()->begin(); 192 std::vector<LoadInst*> Loads; 193 std::vector<std::vector<ConstantInt*> > GEPIndices; 194 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end(); 195 UI != E; ++UI) 196 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 197 if (LI->isVolatile()) return false; // Don't hack volatile loads 198 Loads.push_back(LI); 199 HasLoadInEntryBlock |= LI->getParent() == EntryBlock; 200 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) { 201 if (GEP->use_empty()) { 202 // Dead GEP's cause trouble later. Just remove them if we run into 203 // them. 204 getAnalysis<AliasAnalysis>().deleteValue(GEP); 205 GEP->getParent()->getInstList().erase(GEP); 206 return isSafeToPromoteArgument(Arg); 207 } 208 // Ensure that all of the indices are constants. 209 std::vector<ConstantInt*> Operands; 210 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i) 211 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i))) 212 Operands.push_back(C); 213 else 214 return false; // Not a constant operand GEP! 215 216 // Ensure that the only users of the GEP are load instructions. 217 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end(); 218 UI != E; ++UI) 219 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 220 if (LI->isVolatile()) return false; // Don't hack volatile loads 221 Loads.push_back(LI); 222 HasLoadInEntryBlock |= LI->getParent() == EntryBlock; 223 } else { 224 return false; 225 } 226 227 // See if there is already a GEP with these indices. If not, check to 228 // make sure that we aren't promoting too many elements. If so, nothing 229 // to do. 230 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) == 231 GEPIndices.end()) { 232 if (GEPIndices.size() == 3) { 233 DEBUG(std::cerr << "argpromotion disable promoting argument '" 234 << Arg->getName() << "' because it would require adding more " 235 << "than 3 arguments to the function.\n"); 236 // We limit aggregate promotion to only promoting up to three elements 237 // of the aggregate. 238 return false; 239 } 240 GEPIndices.push_back(Operands); 241 } 242 } else { 243 return false; // Not a load or a GEP. 244 } 245 246 if (Loads.empty()) return true; // No users, this is a dead argument. 247 248 // If we decide that we want to promote this argument, the value is going to 249 // be unconditionally loaded in all callees. This is only safe to do if the 250 // pointer was going to be unconditionally loaded anyway (i.e. there is a load 251 // of the pointer in the entry block of the function) or if we can prove that 252 // all pointers passed in are always to legal locations (for example, no null 253 // pointers are passed in, no pointers to free'd memory, etc). 254 if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg)) 255 return false; // Cannot prove that this is safe!! 256 257 // Okay, now we know that the argument is only used by load instructions and 258 // it is safe to unconditionally load the pointer. Use alias analysis to 259 // check to see if the pointer is guaranteed to not be modified from entry of 260 // the function to each of the load instructions. 261 Function &F = *Arg->getParent(); 262 263 // Because there could be several/many load instructions, remember which 264 // blocks we know to be transparent to the load. 265 std::set<BasicBlock*> TranspBlocks; 266 267 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 268 TargetData &TD = getAnalysis<TargetData>(); 269 270 for (unsigned i = 0, e = Loads.size(); i != e; ++i) { 271 // Check to see if the load is invalidated from the start of the block to 272 // the load itself. 273 LoadInst *Load = Loads[i]; 274 BasicBlock *BB = Load->getParent(); 275 276 const PointerType *LoadTy = 277 cast<PointerType>(Load->getOperand(0)->getType()); 278 unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType()); 279 280 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize)) 281 return false; // Pointer is invalidated! 282 283 // Now check every path from the entry block to the load for transparency. 284 // To do this, we perform a depth first search on the inverse CFG from the 285 // loading block. 286 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 287 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks), 288 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I) 289 if (AA.canBasicBlockModify(**I, Arg, LoadSize)) 290 return false; 291 } 292 293 // If the path from the entry of the function to each load is free of 294 // instructions that potentially invalidate the load, we can make the 295 // transformation! 296 return true; 297 } 298 299 namespace { 300 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value* 301 /// elements are instances of ConstantInt. 302 /// 303 struct GEPIdxComparator { 304 bool operator()(const std::vector<Value*> &LHS, 305 const std::vector<Value*> &RHS) const { 306 unsigned idx = 0; 307 for (; idx < LHS.size() && idx < RHS.size(); ++idx) { 308 if (LHS[idx] != RHS[idx]) { 309 return cast<ConstantInt>(LHS[idx])->getRawValue() < 310 cast<ConstantInt>(RHS[idx])->getRawValue(); 311 } 312 } 313 314 // Return less than if we ran out of stuff in LHS and we didn't run out of 315 // stuff in RHS. 316 return idx == LHS.size() && idx != RHS.size(); 317 } 318 }; 319 } 320 321 322 /// DoPromotion - This method actually performs the promotion of the specified 323 /// arguments, and returns the new function. At this point, we know that it's 324 /// safe to do so. 325 Function *ArgPromotion::DoPromotion(Function *F, 326 std::vector<Argument*> &Args2Prom) { 327 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end()); 328 329 // Start by computing a new prototype for the function, which is the same as 330 // the old function, but has modified arguments. 331 const FunctionType *FTy = F->getFunctionType(); 332 std::vector<const Type*> Params; 333 334 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable; 335 336 // ScalarizedElements - If we are promoting a pointer that has elements 337 // accessed out of it, keep track of which elements are accessed so that we 338 // can add one argument for each. 339 // 340 // Arguments that are directly loaded will have a zero element value here, to 341 // handle cases where there are both a direct load and GEP accesses. 342 // 343 std::map<Argument*, ScalarizeTable> ScalarizedElements; 344 345 // OriginalLoads - Keep track of a representative load instruction from the 346 // original function so that we can tell the alias analysis implementation 347 // what the new GEP/Load instructions we are inserting look like. 348 std::map<std::vector<Value*>, LoadInst*> OriginalLoads; 349 350 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 351 if (!ArgsToPromote.count(I)) { 352 Params.push_back(I->getType()); 353 } else if (I->use_empty()) { 354 ++NumArgumentsDead; 355 } else { 356 // Okay, this is being promoted. Check to see if there are any GEP uses 357 // of the argument. 358 ScalarizeTable &ArgIndices = ScalarizedElements[I]; 359 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 360 ++UI) { 361 Instruction *User = cast<Instruction>(*UI); 362 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User)); 363 std::vector<Value*> Indices(User->op_begin()+1, User->op_end()); 364 ArgIndices.insert(Indices); 365 LoadInst *OrigLoad; 366 if (LoadInst *L = dyn_cast<LoadInst>(User)) 367 OrigLoad = L; 368 else 369 OrigLoad = cast<LoadInst>(User->use_back()); 370 OriginalLoads[Indices] = OrigLoad; 371 } 372 373 // Add a parameter to the function for each element passed in. 374 for (ScalarizeTable::iterator SI = ArgIndices.begin(), 375 E = ArgIndices.end(); SI != E; ++SI) 376 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI)); 377 378 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty()) 379 ++NumArgumentsPromoted; 380 else 381 ++NumAggregatesPromoted; 382 } 383 384 const Type *RetTy = FTy->getReturnType(); 385 386 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which 387 // have zero fixed arguments. 388 bool ExtraArgHack = false; 389 if (Params.empty() && FTy->isVarArg()) { 390 ExtraArgHack = true; 391 Params.push_back(Type::IntTy); 392 } 393 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg()); 394 395 // Create the new function body and insert it into the module... 396 Function *NF = new Function(NFTy, F->getLinkage(), F->getName()); 397 NF->setCallingConv(F->getCallingConv()); 398 F->getParent()->getFunctionList().insert(F, NF); 399 400 // Get the alias analysis information that we need to update to reflect our 401 // changes. 402 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 403 404 // Loop over all of the callers of the function, transforming the call sites 405 // to pass in the loaded pointers. 406 // 407 std::vector<Value*> Args; 408 while (!F->use_empty()) { 409 CallSite CS = CallSite::get(F->use_back()); 410 Instruction *Call = CS.getInstruction(); 411 412 // Loop over the operands, inserting GEP and loads in the caller as 413 // appropriate. 414 CallSite::arg_iterator AI = CS.arg_begin(); 415 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 416 I != E; ++I, ++AI) 417 if (!ArgsToPromote.count(I)) 418 Args.push_back(*AI); // Unmodified argument 419 else if (!I->use_empty()) { 420 // Non-dead argument: insert GEPs and loads as appropriate. 421 ScalarizeTable &ArgIndices = ScalarizedElements[I]; 422 for (ScalarizeTable::iterator SI = ArgIndices.begin(), 423 E = ArgIndices.end(); SI != E; ++SI) { 424 Value *V = *AI; 425 LoadInst *OrigLoad = OriginalLoads[*SI]; 426 if (!SI->empty()) { 427 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call); 428 AA.copyValue(OrigLoad->getOperand(0), V); 429 } 430 Args.push_back(new LoadInst(V, V->getName()+".val", Call)); 431 AA.copyValue(OrigLoad, Args.back()); 432 } 433 } 434 435 if (ExtraArgHack) 436 Args.push_back(Constant::getNullValue(Type::IntTy)); 437 438 // Push any varargs arguments on the list 439 for (; AI != CS.arg_end(); ++AI) 440 Args.push_back(*AI); 441 442 Instruction *New; 443 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 444 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(), 445 Args, "", Call); 446 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 447 } else { 448 New = new CallInst(NF, Args, "", Call); 449 cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 450 if (cast<CallInst>(Call)->isTailCall()) 451 cast<CallInst>(New)->setTailCall(); 452 } 453 Args.clear(); 454 455 // Update the alias analysis implementation to know that we are replacing 456 // the old call with a new one. 457 AA.replaceWithNewValue(Call, New); 458 459 if (!Call->use_empty()) { 460 Call->replaceAllUsesWith(New); 461 std::string Name = Call->getName(); 462 Call->setName(""); 463 New->setName(Name); 464 } 465 466 // Finally, remove the old call from the program, reducing the use-count of 467 // F. 468 Call->getParent()->getInstList().erase(Call); 469 } 470 471 // Since we have now created the new function, splice the body of the old 472 // function right into the new function, leaving the old rotting hulk of the 473 // function empty. 474 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 475 476 // Loop over the argument list, transfering uses of the old arguments over to 477 // the new arguments, also transfering over the names as well. 478 // 479 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), I2 = NF->arg_begin(); 480 I != E; ++I) 481 if (!ArgsToPromote.count(I)) { 482 // If this is an unmodified argument, move the name and users over to the 483 // new version. 484 I->replaceAllUsesWith(I2); 485 I2->setName(I->getName()); 486 AA.replaceWithNewValue(I, I2); 487 ++I2; 488 } else if (I->use_empty()) { 489 AA.deleteValue(I); 490 } else { 491 // Otherwise, if we promoted this argument, then all users are load 492 // instructions, and all loads should be using the new argument that we 493 // added. 494 ScalarizeTable &ArgIndices = ScalarizedElements[I]; 495 496 while (!I->use_empty()) { 497 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) { 498 assert(ArgIndices.begin()->empty() && 499 "Load element should sort to front!"); 500 I2->setName(I->getName()+".val"); 501 LI->replaceAllUsesWith(I2); 502 AA.replaceWithNewValue(LI, I2); 503 LI->getParent()->getInstList().erase(LI); 504 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName() 505 << "' in function '" << F->getName() << "'\n"); 506 } else { 507 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back()); 508 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end()); 509 510 unsigned ArgNo = 0; 511 Function::arg_iterator TheArg = I2; 512 for (ScalarizeTable::iterator It = ArgIndices.begin(); 513 *It != Operands; ++It, ++TheArg) { 514 assert(It != ArgIndices.end() && "GEP not handled??"); 515 } 516 517 std::string NewName = I->getName(); 518 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 519 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i])) 520 NewName += "."+itostr((int64_t)CI->getRawValue()); 521 else 522 NewName += ".x"; 523 TheArg->setName(NewName+".val"); 524 525 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName() 526 << "' of function '" << F->getName() << "'\n"); 527 528 // All of the uses must be load instructions. Replace them all with 529 // the argument specified by ArgNo. 530 while (!GEP->use_empty()) { 531 LoadInst *L = cast<LoadInst>(GEP->use_back()); 532 L->replaceAllUsesWith(TheArg); 533 AA.replaceWithNewValue(L, TheArg); 534 L->getParent()->getInstList().erase(L); 535 } 536 AA.deleteValue(GEP); 537 GEP->getParent()->getInstList().erase(GEP); 538 } 539 } 540 541 // Increment I2 past all of the arguments added for this promoted pointer. 542 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i) 543 ++I2; 544 } 545 546 // Notify the alias analysis implementation that we inserted a new argument. 547 if (ExtraArgHack) 548 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->arg_begin()); 549 550 551 // Tell the alias analysis that the old function is about to disappear. 552 AA.replaceWithNewValue(F, NF); 553 554 // Now that the old function is dead, delete it. 555 F->getParent()->getFunctionList().erase(F); 556 return NF; 557 } 558