LLVM API Documentation
00001 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This pass deletes dead arguments from internal functions. Dead argument 00011 // elimination removes arguments which are directly dead, as well as arguments 00012 // only passed into function calls as dead arguments of other functions. This 00013 // pass also deletes dead return values in a similar way. 00014 // 00015 // This pass is often useful as a cleanup pass to run after aggressive 00016 // interprocedural passes, which add possibly-dead arguments or return values. 00017 // 00018 //===----------------------------------------------------------------------===// 00019 00020 #include "llvm/Transforms/IPO.h" 00021 #include "llvm/ADT/DenseMap.h" 00022 #include "llvm/ADT/SmallVector.h" 00023 #include "llvm/ADT/Statistic.h" 00024 #include "llvm/ADT/StringExtras.h" 00025 #include "llvm/IR/CallSite.h" 00026 #include "llvm/IR/CallingConv.h" 00027 #include "llvm/IR/Constant.h" 00028 #include "llvm/IR/DIBuilder.h" 00029 #include "llvm/IR/DebugInfo.h" 00030 #include "llvm/IR/DerivedTypes.h" 00031 #include "llvm/IR/Instructions.h" 00032 #include "llvm/IR/IntrinsicInst.h" 00033 #include "llvm/IR/LLVMContext.h" 00034 #include "llvm/IR/Module.h" 00035 #include "llvm/Pass.h" 00036 #include "llvm/Support/Debug.h" 00037 #include "llvm/Support/raw_ostream.h" 00038 #include <map> 00039 #include <set> 00040 #include <tuple> 00041 using namespace llvm; 00042 00043 #define DEBUG_TYPE "deadargelim" 00044 00045 STATISTIC(NumArgumentsEliminated, "Number of unread args removed"); 00046 STATISTIC(NumRetValsEliminated , "Number of unused return values removed"); 00047 STATISTIC(NumArgumentsReplacedWithUndef, 00048 "Number of unread args replaced with undef"); 00049 namespace { 00050 /// DAE - The dead argument elimination pass. 00051 /// 00052 class DAE : public ModulePass { 00053 public: 00054 00055 /// Struct that represents (part of) either a return value or a function 00056 /// argument. Used so that arguments and return values can be used 00057 /// interchangeably. 00058 struct RetOrArg { 00059 RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx), 00060 IsArg(IsArg) {} 00061 const Function *F; 00062 unsigned Idx; 00063 bool IsArg; 00064 00065 /// Make RetOrArg comparable, so we can put it into a map. 00066 bool operator<(const RetOrArg &O) const { 00067 return std::tie(F, Idx, IsArg) < std::tie(O.F, O.Idx, O.IsArg); 00068 } 00069 00070 /// Make RetOrArg comparable, so we can easily iterate the multimap. 00071 bool operator==(const RetOrArg &O) const { 00072 return F == O.F && Idx == O.Idx && IsArg == O.IsArg; 00073 } 00074 00075 std::string getDescription() const { 00076 return std::string((IsArg ? "Argument #" : "Return value #")) 00077 + utostr(Idx) + " of function " + F->getName().str(); 00078 } 00079 }; 00080 00081 /// Liveness enum - During our initial pass over the program, we determine 00082 /// that things are either alive or maybe alive. We don't mark anything 00083 /// explicitly dead (even if we know they are), since anything not alive 00084 /// with no registered uses (in Uses) will never be marked alive and will 00085 /// thus become dead in the end. 00086 enum Liveness { Live, MaybeLive }; 00087 00088 /// Convenience wrapper 00089 RetOrArg CreateRet(const Function *F, unsigned Idx) { 00090 return RetOrArg(F, Idx, false); 00091 } 00092 /// Convenience wrapper 00093 RetOrArg CreateArg(const Function *F, unsigned Idx) { 00094 return RetOrArg(F, Idx, true); 00095 } 00096 00097 typedef std::multimap<RetOrArg, RetOrArg> UseMap; 00098 /// This maps a return value or argument to any MaybeLive return values or 00099 /// arguments it uses. This allows the MaybeLive values to be marked live 00100 /// when any of its users is marked live. 00101 /// For example (indices are left out for clarity): 00102 /// - Uses[ret F] = ret G 00103 /// This means that F calls G, and F returns the value returned by G. 00104 /// - Uses[arg F] = ret G 00105 /// This means that some function calls G and passes its result as an 00106 /// argument to F. 00107 /// - Uses[ret F] = arg F 00108 /// This means that F returns one of its own arguments. 00109 /// - Uses[arg F] = arg G 00110 /// This means that G calls F and passes one of its own (G's) arguments 00111 /// directly to F. 00112 UseMap Uses; 00113 00114 typedef std::set<RetOrArg> LiveSet; 00115 typedef std::set<const Function*> LiveFuncSet; 00116 00117 /// This set contains all values that have been determined to be live. 00118 LiveSet LiveValues; 00119 /// This set contains all values that are cannot be changed in any way. 00120 LiveFuncSet LiveFunctions; 00121 00122 typedef SmallVector<RetOrArg, 5> UseVector; 00123 00124 // Map each LLVM function to corresponding metadata with debug info. If 00125 // the function is replaced with another one, we should patch the pointer 00126 // to LLVM function in metadata. 00127 // As the code generation for module is finished (and DIBuilder is 00128 // finalized) we assume that subprogram descriptors won't be changed, and 00129 // they are stored in map for short duration anyway. 00130 DenseMap<const Function *, DISubprogram> FunctionDIs; 00131 00132 protected: 00133 // DAH uses this to specify a different ID. 00134 explicit DAE(char &ID) : ModulePass(ID) {} 00135 00136 public: 00137 static char ID; // Pass identification, replacement for typeid 00138 DAE() : ModulePass(ID) { 00139 initializeDAEPass(*PassRegistry::getPassRegistry()); 00140 } 00141 00142 bool runOnModule(Module &M) override; 00143 00144 virtual bool ShouldHackArguments() const { return false; } 00145 00146 private: 00147 Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses); 00148 Liveness SurveyUse(const Use *U, UseVector &MaybeLiveUses, 00149 unsigned RetValNum = 0); 00150 Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses); 00151 00152 void SurveyFunction(const Function &F); 00153 void MarkValue(const RetOrArg &RA, Liveness L, 00154 const UseVector &MaybeLiveUses); 00155 void MarkLive(const RetOrArg &RA); 00156 void MarkLive(const Function &F); 00157 void PropagateLiveness(const RetOrArg &RA); 00158 bool RemoveDeadStuffFromFunction(Function *F); 00159 bool DeleteDeadVarargs(Function &Fn); 00160 bool RemoveDeadArgumentsFromCallers(Function &Fn); 00161 }; 00162 } 00163 00164 00165 char DAE::ID = 0; 00166 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false) 00167 00168 namespace { 00169 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but 00170 /// deletes arguments to functions which are external. This is only for use 00171 /// by bugpoint. 00172 struct DAH : public DAE { 00173 static char ID; 00174 DAH() : DAE(ID) {} 00175 00176 bool ShouldHackArguments() const override { return true; } 00177 }; 00178 } 00179 00180 char DAH::ID = 0; 00181 INITIALIZE_PASS(DAH, "deadarghaX0r", 00182 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)", 00183 false, false) 00184 00185 /// createDeadArgEliminationPass - This pass removes arguments from functions 00186 /// which are not used by the body of the function. 00187 /// 00188 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); } 00189 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); } 00190 00191 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if 00192 /// llvm.vastart is never called, the varargs list is dead for the function. 00193 bool DAE::DeleteDeadVarargs(Function &Fn) { 00194 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!"); 00195 if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false; 00196 00197 // Ensure that the function is only directly called. 00198 if (Fn.hasAddressTaken()) 00199 return false; 00200 00201 // Okay, we know we can transform this function if safe. Scan its body 00202 // looking for calls marked musttail or calls to llvm.vastart. 00203 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 00204 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 00205 CallInst *CI = dyn_cast<CallInst>(I); 00206 if (!CI) 00207 continue; 00208 if (CI->isMustTailCall()) 00209 return false; 00210 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 00211 if (II->getIntrinsicID() == Intrinsic::vastart) 00212 return false; 00213 } 00214 } 00215 } 00216 00217 // If we get here, there are no calls to llvm.vastart in the function body, 00218 // remove the "..." and adjust all the calls. 00219 00220 // Start by computing a new prototype for the function, which is the same as 00221 // the old function, but doesn't have isVarArg set. 00222 FunctionType *FTy = Fn.getFunctionType(); 00223 00224 std::vector<Type*> Params(FTy->param_begin(), FTy->param_end()); 00225 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), 00226 Params, false); 00227 unsigned NumArgs = Params.size(); 00228 00229 // Create the new function body and insert it into the module... 00230 Function *NF = Function::Create(NFTy, Fn.getLinkage()); 00231 NF->copyAttributesFrom(&Fn); 00232 Fn.getParent()->getFunctionList().insert(&Fn, NF); 00233 NF->takeName(&Fn); 00234 00235 // Loop over all of the callers of the function, transforming the call sites 00236 // to pass in a smaller number of arguments into the new function. 00237 // 00238 std::vector<Value*> Args; 00239 for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) { 00240 CallSite CS(*I++); 00241 if (!CS) 00242 continue; 00243 Instruction *Call = CS.getInstruction(); 00244 00245 // Pass all the same arguments. 00246 Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs); 00247 00248 // Drop any attributes that were on the vararg arguments. 00249 AttributeSet PAL = CS.getAttributes(); 00250 if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) { 00251 SmallVector<AttributeSet, 8> AttributesVec; 00252 for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i) 00253 AttributesVec.push_back(PAL.getSlotAttributes(i)); 00254 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 00255 AttributesVec.push_back(AttributeSet::get(Fn.getContext(), 00256 PAL.getFnAttributes())); 00257 PAL = AttributeSet::get(Fn.getContext(), AttributesVec); 00258 } 00259 00260 Instruction *New; 00261 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 00262 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 00263 Args, "", Call); 00264 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 00265 cast<InvokeInst>(New)->setAttributes(PAL); 00266 } else { 00267 New = CallInst::Create(NF, Args, "", Call); 00268 cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 00269 cast<CallInst>(New)->setAttributes(PAL); 00270 if (cast<CallInst>(Call)->isTailCall()) 00271 cast<CallInst>(New)->setTailCall(); 00272 } 00273 New->setDebugLoc(Call->getDebugLoc()); 00274 00275 Args.clear(); 00276 00277 if (!Call->use_empty()) 00278 Call->replaceAllUsesWith(New); 00279 00280 New->takeName(Call); 00281 00282 // Finally, remove the old call from the program, reducing the use-count of 00283 // F. 00284 Call->eraseFromParent(); 00285 } 00286 00287 // Since we have now created the new function, splice the body of the old 00288 // function right into the new function, leaving the old rotting hulk of the 00289 // function empty. 00290 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList()); 00291 00292 // Loop over the argument list, transferring uses of the old arguments over to 00293 // the new arguments, also transferring over the names as well. While we're at 00294 // it, remove the dead arguments from the DeadArguments list. 00295 // 00296 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(), 00297 I2 = NF->arg_begin(); I != E; ++I, ++I2) { 00298 // Move the name and users over to the new version. 00299 I->replaceAllUsesWith(I2); 00300 I2->takeName(I); 00301 } 00302 00303 // Patch the pointer to LLVM function in debug info descriptor. 00304 auto DI = FunctionDIs.find(&Fn); 00305 if (DI != FunctionDIs.end()) 00306 DI->second.replaceFunction(NF); 00307 00308 // Fix up any BlockAddresses that refer to the function. 00309 Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType())); 00310 // Delete the bitcast that we just created, so that NF does not 00311 // appear to be address-taken. 00312 NF->removeDeadConstantUsers(); 00313 // Finally, nuke the old function. 00314 Fn.eraseFromParent(); 00315 return true; 00316 } 00317 00318 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any 00319 /// arguments that are unused, and changes the caller parameters to be undefined 00320 /// instead. 00321 bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn) 00322 { 00323 if (Fn.isDeclaration() || Fn.mayBeOverridden()) 00324 return false; 00325 00326 // Functions with local linkage should already have been handled, except the 00327 // fragile (variadic) ones which we can improve here. 00328 if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg()) 00329 return false; 00330 00331 // If a function seen at compile time is not necessarily the one linked to 00332 // the binary being built, it is illegal to change the actual arguments 00333 // passed to it. These functions can be captured by isWeakForLinker(). 00334 // *NOTE* that mayBeOverridden() is insufficient for this purpose as it 00335 // doesn't include linkage types like AvailableExternallyLinkage and 00336 // LinkOnceODRLinkage. Take link_odr* as an example, it indicates a set of 00337 // *EQUIVALENT* globals that can be merged at link-time. However, the 00338 // semantic of *EQUIVALENT*-functions includes parameters. Changing 00339 // parameters breaks this assumption. 00340 // 00341 if (Fn.isWeakForLinker()) 00342 return false; 00343 00344 if (Fn.use_empty()) 00345 return false; 00346 00347 SmallVector<unsigned, 8> UnusedArgs; 00348 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 00349 I != E; ++I) { 00350 Argument *Arg = I; 00351 00352 if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr()) 00353 UnusedArgs.push_back(Arg->getArgNo()); 00354 } 00355 00356 if (UnusedArgs.empty()) 00357 return false; 00358 00359 bool Changed = false; 00360 00361 for (Use &U : Fn.uses()) { 00362 CallSite CS(U.getUser()); 00363 if (!CS || !CS.isCallee(&U)) 00364 continue; 00365 00366 // Now go through all unused args and replace them with "undef". 00367 for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) { 00368 unsigned ArgNo = UnusedArgs[I]; 00369 00370 Value *Arg = CS.getArgument(ArgNo); 00371 CS.setArgument(ArgNo, UndefValue::get(Arg->getType())); 00372 ++NumArgumentsReplacedWithUndef; 00373 Changed = true; 00374 } 00375 } 00376 00377 return Changed; 00378 } 00379 00380 /// Convenience function that returns the number of return values. It returns 0 00381 /// for void functions and 1 for functions not returning a struct. It returns 00382 /// the number of struct elements for functions returning a struct. 00383 static unsigned NumRetVals(const Function *F) { 00384 if (F->getReturnType()->isVoidTy()) 00385 return 0; 00386 else if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) 00387 return STy->getNumElements(); 00388 else 00389 return 1; 00390 } 00391 00392 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not 00393 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined 00394 /// liveness of Use. 00395 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) { 00396 // We're live if our use or its Function is already marked as live. 00397 if (LiveFunctions.count(Use.F) || LiveValues.count(Use)) 00398 return Live; 00399 00400 // We're maybe live otherwise, but remember that we must become live if 00401 // Use becomes live. 00402 MaybeLiveUses.push_back(Use); 00403 return MaybeLive; 00404 } 00405 00406 00407 /// SurveyUse - This looks at a single use of an argument or return value 00408 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses 00409 /// if it causes the used value to become MaybeLive. 00410 /// 00411 /// RetValNum is the return value number to use when this use is used in a 00412 /// return instruction. This is used in the recursion, you should always leave 00413 /// it at 0. 00414 DAE::Liveness DAE::SurveyUse(const Use *U, 00415 UseVector &MaybeLiveUses, unsigned RetValNum) { 00416 const User *V = U->getUser(); 00417 if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) { 00418 // The value is returned from a function. It's only live when the 00419 // function's return value is live. We use RetValNum here, for the case 00420 // that U is really a use of an insertvalue instruction that uses the 00421 // original Use. 00422 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum); 00423 // We might be live, depending on the liveness of Use. 00424 return MarkIfNotLive(Use, MaybeLiveUses); 00425 } 00426 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) { 00427 if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex() 00428 && IV->hasIndices()) 00429 // The use we are examining is inserted into an aggregate. Our liveness 00430 // depends on all uses of that aggregate, but if it is used as a return 00431 // value, only index at which we were inserted counts. 00432 RetValNum = *IV->idx_begin(); 00433 00434 // Note that if we are used as the aggregate operand to the insertvalue, 00435 // we don't change RetValNum, but do survey all our uses. 00436 00437 Liveness Result = MaybeLive; 00438 for (const Use &UU : IV->uses()) { 00439 Result = SurveyUse(&UU, MaybeLiveUses, RetValNum); 00440 if (Result == Live) 00441 break; 00442 } 00443 return Result; 00444 } 00445 00446 if (ImmutableCallSite CS = V) { 00447 const Function *F = CS.getCalledFunction(); 00448 if (F) { 00449 // Used in a direct call. 00450 00451 // Find the argument number. We know for sure that this use is an 00452 // argument, since if it was the function argument this would be an 00453 // indirect call and the we know can't be looking at a value of the 00454 // label type (for the invoke instruction). 00455 unsigned ArgNo = CS.getArgumentNo(U); 00456 00457 if (ArgNo >= F->getFunctionType()->getNumParams()) 00458 // The value is passed in through a vararg! Must be live. 00459 return Live; 00460 00461 assert(CS.getArgument(ArgNo) 00462 == CS->getOperand(U->getOperandNo()) 00463 && "Argument is not where we expected it"); 00464 00465 // Value passed to a normal call. It's only live when the corresponding 00466 // argument to the called function turns out live. 00467 RetOrArg Use = CreateArg(F, ArgNo); 00468 return MarkIfNotLive(Use, MaybeLiveUses); 00469 } 00470 } 00471 // Used in any other way? Value must be live. 00472 return Live; 00473 } 00474 00475 /// SurveyUses - This looks at all the uses of the given value 00476 /// Returns the Liveness deduced from the uses of this value. 00477 /// 00478 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If 00479 /// the result is Live, MaybeLiveUses might be modified but its content should 00480 /// be ignored (since it might not be complete). 00481 DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) { 00482 // Assume it's dead (which will only hold if there are no uses at all..). 00483 Liveness Result = MaybeLive; 00484 // Check each use. 00485 for (const Use &U : V->uses()) { 00486 Result = SurveyUse(&U, MaybeLiveUses); 00487 if (Result == Live) 00488 break; 00489 } 00490 return Result; 00491 } 00492 00493 // SurveyFunction - This performs the initial survey of the specified function, 00494 // checking out whether or not it uses any of its incoming arguments or whether 00495 // any callers use the return value. This fills in the LiveValues set and Uses 00496 // map. 00497 // 00498 // We consider arguments of non-internal functions to be intrinsically alive as 00499 // well as arguments to functions which have their "address taken". 00500 // 00501 void DAE::SurveyFunction(const Function &F) { 00502 // Functions with inalloca parameters are expecting args in a particular 00503 // register and memory layout. 00504 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) { 00505 MarkLive(F); 00506 return; 00507 } 00508 00509 unsigned RetCount = NumRetVals(&F); 00510 // Assume all return values are dead 00511 typedef SmallVector<Liveness, 5> RetVals; 00512 RetVals RetValLiveness(RetCount, MaybeLive); 00513 00514 typedef SmallVector<UseVector, 5> RetUses; 00515 // These vectors map each return value to the uses that make it MaybeLive, so 00516 // we can add those to the Uses map if the return value really turns out to be 00517 // MaybeLive. Initialized to a list of RetCount empty lists. 00518 RetUses MaybeLiveRetUses(RetCount); 00519 00520 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 00521 if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) 00522 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType() 00523 != F.getFunctionType()->getReturnType()) { 00524 // We don't support old style multiple return values. 00525 MarkLive(F); 00526 return; 00527 } 00528 00529 if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) { 00530 MarkLive(F); 00531 return; 00532 } 00533 00534 DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n"); 00535 // Keep track of the number of live retvals, so we can skip checks once all 00536 // of them turn out to be live. 00537 unsigned NumLiveRetVals = 0; 00538 Type *STy = dyn_cast<StructType>(F.getReturnType()); 00539 // Loop all uses of the function. 00540 for (const Use &U : F.uses()) { 00541 // If the function is PASSED IN as an argument, its address has been 00542 // taken. 00543 ImmutableCallSite CS(U.getUser()); 00544 if (!CS || !CS.isCallee(&U)) { 00545 MarkLive(F); 00546 return; 00547 } 00548 00549 // If this use is anything other than a call site, the function is alive. 00550 const Instruction *TheCall = CS.getInstruction(); 00551 if (!TheCall) { // Not a direct call site? 00552 MarkLive(F); 00553 return; 00554 } 00555 00556 // If we end up here, we are looking at a direct call to our function. 00557 00558 // Now, check how our return value(s) is/are used in this caller. Don't 00559 // bother checking return values if all of them are live already. 00560 if (NumLiveRetVals != RetCount) { 00561 if (STy) { 00562 // Check all uses of the return value. 00563 for (const User *U : TheCall->users()) { 00564 const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U); 00565 if (Ext && Ext->hasIndices()) { 00566 // This use uses a part of our return value, survey the uses of 00567 // that part and store the results for this index only. 00568 unsigned Idx = *Ext->idx_begin(); 00569 if (RetValLiveness[Idx] != Live) { 00570 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]); 00571 if (RetValLiveness[Idx] == Live) 00572 NumLiveRetVals++; 00573 } 00574 } else { 00575 // Used by something else than extractvalue. Mark all return 00576 // values as live. 00577 for (unsigned i = 0; i != RetCount; ++i ) 00578 RetValLiveness[i] = Live; 00579 NumLiveRetVals = RetCount; 00580 break; 00581 } 00582 } 00583 } else { 00584 // Single return value 00585 RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]); 00586 if (RetValLiveness[0] == Live) 00587 NumLiveRetVals = RetCount; 00588 } 00589 } 00590 } 00591 00592 // Now we've inspected all callers, record the liveness of our return values. 00593 for (unsigned i = 0; i != RetCount; ++i) 00594 MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]); 00595 00596 DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n"); 00597 00598 // Now, check all of our arguments. 00599 unsigned i = 0; 00600 UseVector MaybeLiveArgUses; 00601 for (Function::const_arg_iterator AI = F.arg_begin(), 00602 E = F.arg_end(); AI != E; ++AI, ++i) { 00603 Liveness Result; 00604 if (F.getFunctionType()->isVarArg()) { 00605 // Variadic functions will already have a va_arg function expanded inside 00606 // them, making them potentially very sensitive to ABI changes resulting 00607 // from removing arguments entirely, so don't. For example AArch64 handles 00608 // register and stack HFAs very differently, and this is reflected in the 00609 // IR which has already been generated. 00610 Result = Live; 00611 } else { 00612 // See what the effect of this use is (recording any uses that cause 00613 // MaybeLive in MaybeLiveArgUses). 00614 Result = SurveyUses(AI, MaybeLiveArgUses); 00615 } 00616 00617 // Mark the result. 00618 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses); 00619 // Clear the vector again for the next iteration. 00620 MaybeLiveArgUses.clear(); 00621 } 00622 } 00623 00624 /// MarkValue - This function marks the liveness of RA depending on L. If L is 00625 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses, 00626 /// such that RA will be marked live if any use in MaybeLiveUses gets marked 00627 /// live later on. 00628 void DAE::MarkValue(const RetOrArg &RA, Liveness L, 00629 const UseVector &MaybeLiveUses) { 00630 switch (L) { 00631 case Live: MarkLive(RA); break; 00632 case MaybeLive: 00633 { 00634 // Note any uses of this value, so this return value can be 00635 // marked live whenever one of the uses becomes live. 00636 for (UseVector::const_iterator UI = MaybeLiveUses.begin(), 00637 UE = MaybeLiveUses.end(); UI != UE; ++UI) 00638 Uses.insert(std::make_pair(*UI, RA)); 00639 break; 00640 } 00641 } 00642 } 00643 00644 /// MarkLive - Mark the given Function as alive, meaning that it cannot be 00645 /// changed in any way. Additionally, 00646 /// mark any values that are used as this function's parameters or by its return 00647 /// values (according to Uses) live as well. 00648 void DAE::MarkLive(const Function &F) { 00649 DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n"); 00650 // Mark the function as live. 00651 LiveFunctions.insert(&F); 00652 // Mark all arguments as live. 00653 for (unsigned i = 0, e = F.arg_size(); i != e; ++i) 00654 PropagateLiveness(CreateArg(&F, i)); 00655 // Mark all return values as live. 00656 for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i) 00657 PropagateLiveness(CreateRet(&F, i)); 00658 } 00659 00660 /// MarkLive - Mark the given return value or argument as live. Additionally, 00661 /// mark any values that are used by this value (according to Uses) live as 00662 /// well. 00663 void DAE::MarkLive(const RetOrArg &RA) { 00664 if (LiveFunctions.count(RA.F)) 00665 return; // Function was already marked Live. 00666 00667 if (!LiveValues.insert(RA).second) 00668 return; // We were already marked Live. 00669 00670 DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n"); 00671 PropagateLiveness(RA); 00672 } 00673 00674 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness 00675 /// to any other values it uses (according to Uses). 00676 void DAE::PropagateLiveness(const RetOrArg &RA) { 00677 // We don't use upper_bound (or equal_range) here, because our recursive call 00678 // to ourselves is likely to cause the upper_bound (which is the first value 00679 // not belonging to RA) to become erased and the iterator invalidated. 00680 UseMap::iterator Begin = Uses.lower_bound(RA); 00681 UseMap::iterator E = Uses.end(); 00682 UseMap::iterator I; 00683 for (I = Begin; I != E && I->first == RA; ++I) 00684 MarkLive(I->second); 00685 00686 // Erase RA from the Uses map (from the lower bound to wherever we ended up 00687 // after the loop). 00688 Uses.erase(Begin, I); 00689 } 00690 00691 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F 00692 // that are not in LiveValues. Transform the function and all of the callees of 00693 // the function to not have these arguments and return values. 00694 // 00695 bool DAE::RemoveDeadStuffFromFunction(Function *F) { 00696 // Don't modify fully live functions 00697 if (LiveFunctions.count(F)) 00698 return false; 00699 00700 // Start by computing a new prototype for the function, which is the same as 00701 // the old function, but has fewer arguments and a different return type. 00702 FunctionType *FTy = F->getFunctionType(); 00703 std::vector<Type*> Params; 00704 00705 // Keep track of if we have a live 'returned' argument 00706 bool HasLiveReturnedArg = false; 00707 00708 // Set up to build a new list of parameter attributes. 00709 SmallVector<AttributeSet, 8> AttributesVec; 00710 const AttributeSet &PAL = F->getAttributes(); 00711 00712 // Remember which arguments are still alive. 00713 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false); 00714 // Construct the new parameter list from non-dead arguments. Also construct 00715 // a new set of parameter attributes to correspond. Skip the first parameter 00716 // attribute, since that belongs to the return value. 00717 unsigned i = 0; 00718 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 00719 I != E; ++I, ++i) { 00720 RetOrArg Arg = CreateArg(F, i); 00721 if (LiveValues.erase(Arg)) { 00722 Params.push_back(I->getType()); 00723 ArgAlive[i] = true; 00724 00725 // Get the original parameter attributes (skipping the first one, that is 00726 // for the return value. 00727 if (PAL.hasAttributes(i + 1)) { 00728 AttrBuilder B(PAL, i + 1); 00729 if (B.contains(Attribute::Returned)) 00730 HasLiveReturnedArg = true; 00731 AttributesVec. 00732 push_back(AttributeSet::get(F->getContext(), Params.size(), B)); 00733 } 00734 } else { 00735 ++NumArgumentsEliminated; 00736 DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName() 00737 << ") from " << F->getName() << "\n"); 00738 } 00739 } 00740 00741 // Find out the new return value. 00742 Type *RetTy = FTy->getReturnType(); 00743 Type *NRetTy = nullptr; 00744 unsigned RetCount = NumRetVals(F); 00745 00746 // -1 means unused, other numbers are the new index 00747 SmallVector<int, 5> NewRetIdxs(RetCount, -1); 00748 std::vector<Type*> RetTypes; 00749 00750 // If there is a function with a live 'returned' argument but a dead return 00751 // value, then there are two possible actions: 00752 // 1) Eliminate the return value and take off the 'returned' attribute on the 00753 // argument. 00754 // 2) Retain the 'returned' attribute and treat the return value (but not the 00755 // entire function) as live so that it is not eliminated. 00756 // 00757 // It's not clear in the general case which option is more profitable because, 00758 // even in the absence of explicit uses of the return value, code generation 00759 // is free to use the 'returned' attribute to do things like eliding 00760 // save/restores of registers across calls. Whether or not this happens is 00761 // target and ABI-specific as well as depending on the amount of register 00762 // pressure, so there's no good way for an IR-level pass to figure this out. 00763 // 00764 // Fortunately, the only places where 'returned' is currently generated by 00765 // the FE are places where 'returned' is basically free and almost always a 00766 // performance win, so the second option can just be used always for now. 00767 // 00768 // This should be revisited if 'returned' is ever applied more liberally. 00769 if (RetTy->isVoidTy() || HasLiveReturnedArg) { 00770 NRetTy = RetTy; 00771 } else { 00772 StructType *STy = dyn_cast<StructType>(RetTy); 00773 if (STy) 00774 // Look at each of the original return values individually. 00775 for (unsigned i = 0; i != RetCount; ++i) { 00776 RetOrArg Ret = CreateRet(F, i); 00777 if (LiveValues.erase(Ret)) { 00778 RetTypes.push_back(STy->getElementType(i)); 00779 NewRetIdxs[i] = RetTypes.size() - 1; 00780 } else { 00781 ++NumRetValsEliminated; 00782 DEBUG(dbgs() << "DAE - Removing return value " << i << " from " 00783 << F->getName() << "\n"); 00784 } 00785 } 00786 else 00787 // We used to return a single value. 00788 if (LiveValues.erase(CreateRet(F, 0))) { 00789 RetTypes.push_back(RetTy); 00790 NewRetIdxs[0] = 0; 00791 } else { 00792 DEBUG(dbgs() << "DAE - Removing return value from " << F->getName() 00793 << "\n"); 00794 ++NumRetValsEliminated; 00795 } 00796 if (RetTypes.size() > 1) 00797 // More than one return type? Return a struct with them. Also, if we used 00798 // to return a struct and didn't change the number of return values, 00799 // return a struct again. This prevents changing {something} into 00800 // something and {} into void. 00801 // Make the new struct packed if we used to return a packed struct 00802 // already. 00803 NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked()); 00804 else if (RetTypes.size() == 1) 00805 // One return type? Just a simple value then, but only if we didn't use to 00806 // return a struct with that simple value before. 00807 NRetTy = RetTypes.front(); 00808 else if (RetTypes.size() == 0) 00809 // No return types? Make it void, but only if we didn't use to return {}. 00810 NRetTy = Type::getVoidTy(F->getContext()); 00811 } 00812 00813 assert(NRetTy && "No new return type found?"); 00814 00815 // The existing function return attributes. 00816 AttributeSet RAttrs = PAL.getRetAttributes(); 00817 00818 // Remove any incompatible attributes, but only if we removed all return 00819 // values. Otherwise, ensure that we don't have any conflicting attributes 00820 // here. Currently, this should not be possible, but special handling might be 00821 // required when new return value attributes are added. 00822 if (NRetTy->isVoidTy()) 00823 RAttrs = 00824 AttributeSet::get(NRetTy->getContext(), AttributeSet::ReturnIndex, 00825 AttrBuilder(RAttrs, AttributeSet::ReturnIndex). 00826 removeAttributes(AttributeFuncs:: 00827 typeIncompatible(NRetTy, AttributeSet::ReturnIndex), 00828 AttributeSet::ReturnIndex)); 00829 else 00830 assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex). 00831 hasAttributes(AttributeFuncs:: 00832 typeIncompatible(NRetTy, AttributeSet::ReturnIndex), 00833 AttributeSet::ReturnIndex) && 00834 "Return attributes no longer compatible?"); 00835 00836 if (RAttrs.hasAttributes(AttributeSet::ReturnIndex)) 00837 AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs)); 00838 00839 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 00840 AttributesVec.push_back(AttributeSet::get(F->getContext(), 00841 PAL.getFnAttributes())); 00842 00843 // Reconstruct the AttributesList based on the vector we constructed. 00844 AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec); 00845 00846 // Create the new function type based on the recomputed parameters. 00847 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg()); 00848 00849 // No change? 00850 if (NFTy == FTy) 00851 return false; 00852 00853 // Create the new function body and insert it into the module... 00854 Function *NF = Function::Create(NFTy, F->getLinkage()); 00855 NF->copyAttributesFrom(F); 00856 NF->setAttributes(NewPAL); 00857 // Insert the new function before the old function, so we won't be processing 00858 // it again. 00859 F->getParent()->getFunctionList().insert(F, NF); 00860 NF->takeName(F); 00861 00862 // Loop over all of the callers of the function, transforming the call sites 00863 // to pass in a smaller number of arguments into the new function. 00864 // 00865 std::vector<Value*> Args; 00866 while (!F->use_empty()) { 00867 CallSite CS(F->user_back()); 00868 Instruction *Call = CS.getInstruction(); 00869 00870 AttributesVec.clear(); 00871 const AttributeSet &CallPAL = CS.getAttributes(); 00872 00873 // The call return attributes. 00874 AttributeSet RAttrs = CallPAL.getRetAttributes(); 00875 00876 // Adjust in case the function was changed to return void. 00877 RAttrs = 00878 AttributeSet::get(NF->getContext(), AttributeSet::ReturnIndex, 00879 AttrBuilder(RAttrs, AttributeSet::ReturnIndex). 00880 removeAttributes(AttributeFuncs:: 00881 typeIncompatible(NF->getReturnType(), 00882 AttributeSet::ReturnIndex), 00883 AttributeSet::ReturnIndex)); 00884 if (RAttrs.hasAttributes(AttributeSet::ReturnIndex)) 00885 AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs)); 00886 00887 // Declare these outside of the loops, so we can reuse them for the second 00888 // loop, which loops the varargs. 00889 CallSite::arg_iterator I = CS.arg_begin(); 00890 unsigned i = 0; 00891 // Loop over those operands, corresponding to the normal arguments to the 00892 // original function, and add those that are still alive. 00893 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i) 00894 if (ArgAlive[i]) { 00895 Args.push_back(*I); 00896 // Get original parameter attributes, but skip return attributes. 00897 if (CallPAL.hasAttributes(i + 1)) { 00898 AttrBuilder B(CallPAL, i + 1); 00899 // If the return type has changed, then get rid of 'returned' on the 00900 // call site. The alternative is to make all 'returned' attributes on 00901 // call sites keep the return value alive just like 'returned' 00902 // attributes on function declaration but it's less clearly a win 00903 // and this is not an expected case anyway 00904 if (NRetTy != RetTy && B.contains(Attribute::Returned)) 00905 B.removeAttribute(Attribute::Returned); 00906 AttributesVec. 00907 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 00908 } 00909 } 00910 00911 // Push any varargs arguments on the list. Don't forget their attributes. 00912 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) { 00913 Args.push_back(*I); 00914 if (CallPAL.hasAttributes(i + 1)) { 00915 AttrBuilder B(CallPAL, i + 1); 00916 AttributesVec. 00917 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 00918 } 00919 } 00920 00921 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex)) 00922 AttributesVec.push_back(AttributeSet::get(Call->getContext(), 00923 CallPAL.getFnAttributes())); 00924 00925 // Reconstruct the AttributesList based on the vector we constructed. 00926 AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec); 00927 00928 Instruction *New; 00929 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 00930 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 00931 Args, "", Call); 00932 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 00933 cast<InvokeInst>(New)->setAttributes(NewCallPAL); 00934 } else { 00935 New = CallInst::Create(NF, Args, "", Call); 00936 cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 00937 cast<CallInst>(New)->setAttributes(NewCallPAL); 00938 if (cast<CallInst>(Call)->isTailCall()) 00939 cast<CallInst>(New)->setTailCall(); 00940 } 00941 New->setDebugLoc(Call->getDebugLoc()); 00942 00943 Args.clear(); 00944 00945 if (!Call->use_empty()) { 00946 if (New->getType() == Call->getType()) { 00947 // Return type not changed? Just replace users then. 00948 Call->replaceAllUsesWith(New); 00949 New->takeName(Call); 00950 } else if (New->getType()->isVoidTy()) { 00951 // Our return value has uses, but they will get removed later on. 00952 // Replace by null for now. 00953 if (!Call->getType()->isX86_MMXTy()) 00954 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType())); 00955 } else { 00956 assert(RetTy->isStructTy() && 00957 "Return type changed, but not into a void. The old return type" 00958 " must have been a struct!"); 00959 Instruction *InsertPt = Call; 00960 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 00961 BasicBlock::iterator IP = II->getNormalDest()->begin(); 00962 while (isa<PHINode>(IP)) ++IP; 00963 InsertPt = IP; 00964 } 00965 00966 // We used to return a struct. Instead of doing smart stuff with all the 00967 // uses of this struct, we will just rebuild it using 00968 // extract/insertvalue chaining and let instcombine clean that up. 00969 // 00970 // Start out building up our return value from undef 00971 Value *RetVal = UndefValue::get(RetTy); 00972 for (unsigned i = 0; i != RetCount; ++i) 00973 if (NewRetIdxs[i] != -1) { 00974 Value *V; 00975 if (RetTypes.size() > 1) 00976 // We are still returning a struct, so extract the value from our 00977 // return value 00978 V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret", 00979 InsertPt); 00980 else 00981 // We are now returning a single element, so just insert that 00982 V = New; 00983 // Insert the value at the old position 00984 RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt); 00985 } 00986 // Now, replace all uses of the old call instruction with the return 00987 // struct we built 00988 Call->replaceAllUsesWith(RetVal); 00989 New->takeName(Call); 00990 } 00991 } 00992 00993 // Finally, remove the old call from the program, reducing the use-count of 00994 // F. 00995 Call->eraseFromParent(); 00996 } 00997 00998 // Since we have now created the new function, splice the body of the old 00999 // function right into the new function, leaving the old rotting hulk of the 01000 // function empty. 01001 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 01002 01003 // Loop over the argument list, transferring uses of the old arguments over to 01004 // the new arguments, also transferring over the names as well. 01005 i = 0; 01006 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 01007 I2 = NF->arg_begin(); I != E; ++I, ++i) 01008 if (ArgAlive[i]) { 01009 // If this is a live argument, move the name and users over to the new 01010 // version. 01011 I->replaceAllUsesWith(I2); 01012 I2->takeName(I); 01013 ++I2; 01014 } else { 01015 // If this argument is dead, replace any uses of it with null constants 01016 // (these are guaranteed to become unused later on). 01017 if (!I->getType()->isX86_MMXTy()) 01018 I->replaceAllUsesWith(Constant::getNullValue(I->getType())); 01019 } 01020 01021 // If we change the return value of the function we must rewrite any return 01022 // instructions. Check this now. 01023 if (F->getReturnType() != NF->getReturnType()) 01024 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB) 01025 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 01026 Value *RetVal; 01027 01028 if (NFTy->getReturnType()->isVoidTy()) { 01029 RetVal = nullptr; 01030 } else { 01031 assert (RetTy->isStructTy()); 01032 // The original return value was a struct, insert 01033 // extractvalue/insertvalue chains to extract only the values we need 01034 // to return and insert them into our new result. 01035 // This does generate messy code, but we'll let it to instcombine to 01036 // clean that up. 01037 Value *OldRet = RI->getOperand(0); 01038 // Start out building up our return value from undef 01039 RetVal = UndefValue::get(NRetTy); 01040 for (unsigned i = 0; i != RetCount; ++i) 01041 if (NewRetIdxs[i] != -1) { 01042 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i, 01043 "oldret", RI); 01044 if (RetTypes.size() > 1) { 01045 // We're still returning a struct, so reinsert the value into 01046 // our new return value at the new index 01047 01048 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i], 01049 "newret", RI); 01050 } else { 01051 // We are now only returning a simple value, so just return the 01052 // extracted value. 01053 RetVal = EV; 01054 } 01055 } 01056 } 01057 // Replace the return instruction with one returning the new return 01058 // value (possibly 0 if we became void). 01059 ReturnInst::Create(F->getContext(), RetVal, RI); 01060 BB->getInstList().erase(RI); 01061 } 01062 01063 // Patch the pointer to LLVM function in debug info descriptor. 01064 auto DI = FunctionDIs.find(F); 01065 if (DI != FunctionDIs.end()) 01066 DI->second.replaceFunction(NF); 01067 01068 // Now that the old function is dead, delete it. 01069 F->eraseFromParent(); 01070 01071 return true; 01072 } 01073 01074 bool DAE::runOnModule(Module &M) { 01075 bool Changed = false; 01076 01077 // Collect debug info descriptors for functions. 01078 FunctionDIs = makeSubprogramMap(M); 01079 01080 // First pass: Do a simple check to see if any functions can have their "..." 01081 // removed. We can do this if they never call va_start. This loop cannot be 01082 // fused with the next loop, because deleting a function invalidates 01083 // information computed while surveying other functions. 01084 DEBUG(dbgs() << "DAE - Deleting dead varargs\n"); 01085 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 01086 Function &F = *I++; 01087 if (F.getFunctionType()->isVarArg()) 01088 Changed |= DeleteDeadVarargs(F); 01089 } 01090 01091 // Second phase:loop through the module, determining which arguments are live. 01092 // We assume all arguments are dead unless proven otherwise (allowing us to 01093 // determine that dead arguments passed into recursive functions are dead). 01094 // 01095 DEBUG(dbgs() << "DAE - Determining liveness\n"); 01096 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 01097 SurveyFunction(*I); 01098 01099 // Now, remove all dead arguments and return values from each function in 01100 // turn. 01101 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 01102 // Increment now, because the function will probably get removed (ie. 01103 // replaced by a new one). 01104 Function *F = I++; 01105 Changed |= RemoveDeadStuffFromFunction(F); 01106 } 01107 01108 // Finally, look for any unused parameters in functions with non-local 01109 // linkage and replace the passed in parameters with undef. 01110 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 01111 Function& F = *I; 01112 01113 Changed |= RemoveDeadArgumentsFromCallers(F); 01114 } 01115 01116 return Changed; 01117 }