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