1 //===- DeadArgumentElimination.cpp - Eliminate dead 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 deletes dead arguments from internal functions. Dead argument 11 // elimination removes arguments which are directly dead, as well as arguments 12 // only passed into function calls as dead arguments of other functions. This 13 // pass also deletes dead return values in a similar way. 14 // 15 // This pass is often useful as a cleanup pass to run after aggressive 16 // interprocedural passes, which add possibly-dead arguments or return values. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/IR/Argument.h" 24 #include "llvm/IR/Attributes.h" 25 #include "llvm/IR/BasicBlock.h" 26 #include "llvm/IR/CallSite.h" 27 #include "llvm/IR/Constant.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/InstrTypes.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/PassManager.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/IR/Use.h" 40 #include "llvm/IR/User.h" 41 #include "llvm/IR/Value.h" 42 #include "llvm/Pass.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Transforms/IPO.h" 47 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 48 #include <cassert> 49 #include <cstdint> 50 #include <utility> 51 #include <vector> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "deadargelim" 56 57 STATISTIC(NumArgumentsEliminated, "Number of unread args removed"); 58 STATISTIC(NumRetValsEliminated , "Number of unused return values removed"); 59 STATISTIC(NumArgumentsReplacedWithUndef, 60 "Number of unread args replaced with undef"); 61 62 namespace { 63 64 /// DAE - The dead argument elimination pass. 65 class DAE : public ModulePass { 66 protected: 67 // DAH uses this to specify a different ID. 68 explicit DAE(char &ID) : ModulePass(ID) {} 69 70 public: 71 static char ID; // Pass identification, replacement for typeid 72 73 DAE() : ModulePass(ID) { 74 initializeDAEPass(*PassRegistry::getPassRegistry()); 75 } 76 77 bool runOnModule(Module &M) override { 78 if (skipModule(M)) 79 return false; 80 DeadArgumentEliminationPass DAEP(ShouldHackArguments()); 81 ModuleAnalysisManager DummyMAM; 82 PreservedAnalyses PA = DAEP.run(M, DummyMAM); 83 return !PA.areAllPreserved(); 84 } 85 86 virtual bool ShouldHackArguments() const { return false; } 87 }; 88 89 } // end anonymous namespace 90 91 char DAE::ID = 0; 92 93 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false) 94 95 namespace { 96 97 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but 98 /// deletes arguments to functions which are external. This is only for use 99 /// by bugpoint. 100 struct DAH : public DAE { 101 static char ID; 102 103 DAH() : DAE(ID) {} 104 105 bool ShouldHackArguments() const override { return true; } 106 }; 107 108 } // end anonymous namespace 109 110 char DAH::ID = 0; 111 112 INITIALIZE_PASS(DAH, "deadarghaX0r", 113 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)", 114 false, false) 115 116 /// createDeadArgEliminationPass - This pass removes arguments from functions 117 /// which are not used by the body of the function. 118 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); } 119 120 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); } 121 122 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if 123 /// llvm.vastart is never called, the varargs list is dead for the function. 124 bool DeadArgumentEliminationPass::DeleteDeadVarargs(Function &Fn) { 125 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!"); 126 if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false; 127 128 // Ensure that the function is only directly called. 129 if (Fn.hasAddressTaken()) 130 return false; 131 132 // Don't touch naked functions. The assembly might be using an argument, or 133 // otherwise rely on the frame layout in a way that this analysis will not 134 // see. 135 if (Fn.hasFnAttribute(Attribute::Naked)) { 136 return false; 137 } 138 139 // Okay, we know we can transform this function if safe. Scan its body 140 // looking for calls marked musttail or calls to llvm.vastart. 141 for (BasicBlock &BB : Fn) { 142 for (Instruction &I : BB) { 143 CallInst *CI = dyn_cast<CallInst>(&I); 144 if (!CI) 145 continue; 146 if (CI->isMustTailCall()) 147 return false; 148 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 149 if (II->getIntrinsicID() == Intrinsic::vastart) 150 return false; 151 } 152 } 153 } 154 155 // If we get here, there are no calls to llvm.vastart in the function body, 156 // remove the "..." and adjust all the calls. 157 158 // Start by computing a new prototype for the function, which is the same as 159 // the old function, but doesn't have isVarArg set. 160 FunctionType *FTy = Fn.getFunctionType(); 161 162 std::vector<Type *> Params(FTy->param_begin(), FTy->param_end()); 163 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), 164 Params, false); 165 unsigned NumArgs = Params.size(); 166 167 // Create the new function body and insert it into the module... 168 Function *NF = Function::Create(NFTy, Fn.getLinkage()); 169 NF->copyAttributesFrom(&Fn); 170 NF->setComdat(Fn.getComdat()); 171 Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF); 172 NF->takeName(&Fn); 173 174 // Loop over all of the callers of the function, transforming the call sites 175 // to pass in a smaller number of arguments into the new function. 176 // 177 std::vector<Value *> Args; 178 for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) { 179 CallSite CS(*I++); 180 if (!CS) 181 continue; 182 Instruction *Call = CS.getInstruction(); 183 184 // Pass all the same arguments. 185 Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs); 186 187 // Drop any attributes that were on the vararg arguments. 188 AttributeList PAL = CS.getAttributes(); 189 if (!PAL.isEmpty()) { 190 SmallVector<AttributeSet, 8> ArgAttrs; 191 for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo) 192 ArgAttrs.push_back(PAL.getParamAttributes(ArgNo)); 193 PAL = AttributeList::get(Fn.getContext(), PAL.getFnAttributes(), 194 PAL.getRetAttributes(), ArgAttrs); 195 } 196 197 SmallVector<OperandBundleDef, 1> OpBundles; 198 CS.getOperandBundlesAsDefs(OpBundles); 199 200 CallSite NewCS; 201 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 202 NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 203 Args, OpBundles, "", Call); 204 } else { 205 NewCS = CallInst::Create(NF, Args, OpBundles, "", Call); 206 cast<CallInst>(NewCS.getInstruction()) 207 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind()); 208 } 209 NewCS.setCallingConv(CS.getCallingConv()); 210 NewCS.setAttributes(PAL); 211 NewCS->setDebugLoc(Call->getDebugLoc()); 212 uint64_t W; 213 if (Call->extractProfTotalWeight(W)) 214 NewCS->setProfWeight(W); 215 216 Args.clear(); 217 218 if (!Call->use_empty()) 219 Call->replaceAllUsesWith(NewCS.getInstruction()); 220 221 NewCS->takeName(Call); 222 223 // Finally, remove the old call from the program, reducing the use-count of 224 // F. 225 Call->eraseFromParent(); 226 } 227 228 // Since we have now created the new function, splice the body of the old 229 // function right into the new function, leaving the old rotting hulk of the 230 // function empty. 231 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList()); 232 233 // Loop over the argument list, transferring uses of the old arguments over to 234 // the new arguments, also transferring over the names as well. While we're at 235 // it, remove the dead arguments from the DeadArguments list. 236 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(), 237 I2 = NF->arg_begin(); I != E; ++I, ++I2) { 238 // Move the name and users over to the new version. 239 I->replaceAllUsesWith(&*I2); 240 I2->takeName(&*I); 241 } 242 243 // Clone metadatas from the old function, including debug info descriptor. 244 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 245 Fn.getAllMetadata(MDs); 246 for (auto MD : MDs) 247 NF->addMetadata(MD.first, *MD.second); 248 249 // Fix up any BlockAddresses that refer to the function. 250 Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType())); 251 // Delete the bitcast that we just created, so that NF does not 252 // appear to be address-taken. 253 NF->removeDeadConstantUsers(); 254 // Finally, nuke the old function. 255 Fn.eraseFromParent(); 256 return true; 257 } 258 259 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any 260 /// arguments that are unused, and changes the caller parameters to be undefined 261 /// instead. 262 bool DeadArgumentEliminationPass::RemoveDeadArgumentsFromCallers(Function &Fn) { 263 // We cannot change the arguments if this TU does not define the function or 264 // if the linker may choose a function body from another TU, even if the 265 // nominal linkage indicates that other copies of the function have the same 266 // semantics. In the below example, the dead load from %p may not have been 267 // eliminated from the linker-chosen copy of f, so replacing %p with undef 268 // in callers may introduce undefined behavior. 269 // 270 // define linkonce_odr void @f(i32* %p) { 271 // %v = load i32 %p 272 // ret void 273 // } 274 if (!Fn.hasExactDefinition()) 275 return false; 276 277 // Functions with local linkage should already have been handled, except the 278 // fragile (variadic) ones which we can improve here. 279 if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg()) 280 return false; 281 282 // Don't touch naked functions. The assembly might be using an argument, or 283 // otherwise rely on the frame layout in a way that this analysis will not 284 // see. 285 if (Fn.hasFnAttribute(Attribute::Naked)) 286 return false; 287 288 if (Fn.use_empty()) 289 return false; 290 291 SmallVector<unsigned, 8> UnusedArgs; 292 bool Changed = false; 293 294 for (Argument &Arg : Fn.args()) { 295 if (!Arg.hasSwiftErrorAttr() && Arg.use_empty() && !Arg.hasByValOrInAllocaAttr()) { 296 if (Arg.isUsedByMetadata()) { 297 Arg.replaceAllUsesWith(UndefValue::get(Arg.getType())); 298 Changed = true; 299 } 300 UnusedArgs.push_back(Arg.getArgNo()); 301 } 302 } 303 304 if (UnusedArgs.empty()) 305 return false; 306 307 for (Use &U : Fn.uses()) { 308 CallSite CS(U.getUser()); 309 if (!CS || !CS.isCallee(&U)) 310 continue; 311 312 // Now go through all unused args and replace them with "undef". 313 for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) { 314 unsigned ArgNo = UnusedArgs[I]; 315 316 Value *Arg = CS.getArgument(ArgNo); 317 CS.setArgument(ArgNo, UndefValue::get(Arg->getType())); 318 ++NumArgumentsReplacedWithUndef; 319 Changed = true; 320 } 321 } 322 323 return Changed; 324 } 325 326 /// Convenience function that returns the number of return values. It returns 0 327 /// for void functions and 1 for functions not returning a struct. It returns 328 /// the number of struct elements for functions returning a struct. 329 static unsigned NumRetVals(const Function *F) { 330 Type *RetTy = F->getReturnType(); 331 if (RetTy->isVoidTy()) 332 return 0; 333 else if (StructType *STy = dyn_cast<StructType>(RetTy)) 334 return STy->getNumElements(); 335 else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy)) 336 return ATy->getNumElements(); 337 else 338 return 1; 339 } 340 341 /// Returns the sub-type a function will return at a given Idx. Should 342 /// correspond to the result type of an ExtractValue instruction executed with 343 /// just that one Idx (i.e. only top-level structure is considered). 344 static Type *getRetComponentType(const Function *F, unsigned Idx) { 345 Type *RetTy = F->getReturnType(); 346 assert(!RetTy->isVoidTy() && "void type has no subtype"); 347 348 if (StructType *STy = dyn_cast<StructType>(RetTy)) 349 return STy->getElementType(Idx); 350 else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy)) 351 return ATy->getElementType(); 352 else 353 return RetTy; 354 } 355 356 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not 357 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined 358 /// liveness of Use. 359 DeadArgumentEliminationPass::Liveness 360 DeadArgumentEliminationPass::MarkIfNotLive(RetOrArg Use, 361 UseVector &MaybeLiveUses) { 362 // We're live if our use or its Function is already marked as live. 363 if (LiveFunctions.count(Use.F) || LiveValues.count(Use)) 364 return Live; 365 366 // We're maybe live otherwise, but remember that we must become live if 367 // Use becomes live. 368 MaybeLiveUses.push_back(Use); 369 return MaybeLive; 370 } 371 372 /// SurveyUse - This looks at a single use of an argument or return value 373 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses 374 /// if it causes the used value to become MaybeLive. 375 /// 376 /// RetValNum is the return value number to use when this use is used in a 377 /// return instruction. This is used in the recursion, you should always leave 378 /// it at 0. 379 DeadArgumentEliminationPass::Liveness 380 DeadArgumentEliminationPass::SurveyUse(const Use *U, UseVector &MaybeLiveUses, 381 unsigned RetValNum) { 382 const User *V = U->getUser(); 383 if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) { 384 // The value is returned from a function. It's only live when the 385 // function's return value is live. We use RetValNum here, for the case 386 // that U is really a use of an insertvalue instruction that uses the 387 // original Use. 388 const Function *F = RI->getParent()->getParent(); 389 if (RetValNum != -1U) { 390 RetOrArg Use = CreateRet(F, RetValNum); 391 // We might be live, depending on the liveness of Use. 392 return MarkIfNotLive(Use, MaybeLiveUses); 393 } else { 394 DeadArgumentEliminationPass::Liveness Result = MaybeLive; 395 for (unsigned i = 0; i < NumRetVals(F); ++i) { 396 RetOrArg Use = CreateRet(F, i); 397 // We might be live, depending on the liveness of Use. If any 398 // sub-value is live, then the entire value is considered live. This 399 // is a conservative choice, and better tracking is possible. 400 DeadArgumentEliminationPass::Liveness SubResult = 401 MarkIfNotLive(Use, MaybeLiveUses); 402 if (Result != Live) 403 Result = SubResult; 404 } 405 return Result; 406 } 407 } 408 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) { 409 if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex() 410 && IV->hasIndices()) 411 // The use we are examining is inserted into an aggregate. Our liveness 412 // depends on all uses of that aggregate, but if it is used as a return 413 // value, only index at which we were inserted counts. 414 RetValNum = *IV->idx_begin(); 415 416 // Note that if we are used as the aggregate operand to the insertvalue, 417 // we don't change RetValNum, but do survey all our uses. 418 419 Liveness Result = MaybeLive; 420 for (const Use &UU : IV->uses()) { 421 Result = SurveyUse(&UU, MaybeLiveUses, RetValNum); 422 if (Result == Live) 423 break; 424 } 425 return Result; 426 } 427 428 if (auto CS = ImmutableCallSite(V)) { 429 const Function *F = CS.getCalledFunction(); 430 if (F) { 431 // Used in a direct call. 432 433 // The function argument is live if it is used as a bundle operand. 434 if (CS.isBundleOperand(U)) 435 return Live; 436 437 // Find the argument number. We know for sure that this use is an 438 // argument, since if it was the function argument this would be an 439 // indirect call and the we know can't be looking at a value of the 440 // label type (for the invoke instruction). 441 unsigned ArgNo = CS.getArgumentNo(U); 442 443 if (ArgNo >= F->getFunctionType()->getNumParams()) 444 // The value is passed in through a vararg! Must be live. 445 return Live; 446 447 assert(CS.getArgument(ArgNo) 448 == CS->getOperand(U->getOperandNo()) 449 && "Argument is not where we expected it"); 450 451 // Value passed to a normal call. It's only live when the corresponding 452 // argument to the called function turns out live. 453 RetOrArg Use = CreateArg(F, ArgNo); 454 return MarkIfNotLive(Use, MaybeLiveUses); 455 } 456 } 457 // Used in any other way? Value must be live. 458 return Live; 459 } 460 461 /// SurveyUses - This looks at all the uses of the given value 462 /// Returns the Liveness deduced from the uses of this value. 463 /// 464 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If 465 /// the result is Live, MaybeLiveUses might be modified but its content should 466 /// be ignored (since it might not be complete). 467 DeadArgumentEliminationPass::Liveness 468 DeadArgumentEliminationPass::SurveyUses(const Value *V, 469 UseVector &MaybeLiveUses) { 470 // Assume it's dead (which will only hold if there are no uses at all..). 471 Liveness Result = MaybeLive; 472 // Check each use. 473 for (const Use &U : V->uses()) { 474 Result = SurveyUse(&U, MaybeLiveUses); 475 if (Result == Live) 476 break; 477 } 478 return Result; 479 } 480 481 // SurveyFunction - This performs the initial survey of the specified function, 482 // checking out whether or not it uses any of its incoming arguments or whether 483 // any callers use the return value. This fills in the LiveValues set and Uses 484 // map. 485 // 486 // We consider arguments of non-internal functions to be intrinsically alive as 487 // well as arguments to functions which have their "address taken". 488 void DeadArgumentEliminationPass::SurveyFunction(const Function &F) { 489 // Functions with inalloca parameters are expecting args in a particular 490 // register and memory layout. 491 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) { 492 MarkLive(F); 493 return; 494 } 495 496 // Don't touch naked functions. The assembly might be using an argument, or 497 // otherwise rely on the frame layout in a way that this analysis will not 498 // see. 499 if (F.hasFnAttribute(Attribute::Naked)) { 500 MarkLive(F); 501 return; 502 } 503 504 unsigned RetCount = NumRetVals(&F); 505 506 // Assume all return values are dead 507 using RetVals = SmallVector<Liveness, 5>; 508 509 RetVals RetValLiveness(RetCount, MaybeLive); 510 511 using RetUses = SmallVector<UseVector, 5>; 512 513 // These vectors map each return value to the uses that make it MaybeLive, so 514 // we can add those to the Uses map if the return value really turns out to be 515 // MaybeLive. Initialized to a list of RetCount empty lists. 516 RetUses MaybeLiveRetUses(RetCount); 517 518 bool HasMustTailCalls = false; 519 520 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 521 if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 522 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType() 523 != F.getFunctionType()->getReturnType()) { 524 // We don't support old style multiple return values. 525 MarkLive(F); 526 return; 527 } 528 } 529 530 // If we have any returns of `musttail` results - the signature can't 531 // change 532 if (BB->getTerminatingMustTailCall() != nullptr) 533 HasMustTailCalls = true; 534 } 535 536 if (HasMustTailCalls) { 537 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName() 538 << " has musttail calls\n"); 539 } 540 541 if (!F.hasLocalLinkage() && (!ShouldHackArguments || F.isIntrinsic())) { 542 MarkLive(F); 543 return; 544 } 545 546 LLVM_DEBUG( 547 dbgs() << "DeadArgumentEliminationPass - Inspecting callers for fn: " 548 << F.getName() << "\n"); 549 // Keep track of the number of live retvals, so we can skip checks once all 550 // of them turn out to be live. 551 unsigned NumLiveRetVals = 0; 552 553 bool HasMustTailCallers = false; 554 555 // Loop all uses of the function. 556 for (const Use &U : F.uses()) { 557 // If the function is PASSED IN as an argument, its address has been 558 // taken. 559 ImmutableCallSite CS(U.getUser()); 560 if (!CS || !CS.isCallee(&U)) { 561 MarkLive(F); 562 return; 563 } 564 565 // The number of arguments for `musttail` call must match the number of 566 // arguments of the caller 567 if (CS.isMustTailCall()) 568 HasMustTailCallers = true; 569 570 // If this use is anything other than a call site, the function is alive. 571 const Instruction *TheCall = CS.getInstruction(); 572 if (!TheCall) { // Not a direct call site? 573 MarkLive(F); 574 return; 575 } 576 577 // If we end up here, we are looking at a direct call to our function. 578 579 // Now, check how our return value(s) is/are used in this caller. Don't 580 // bother checking return values if all of them are live already. 581 if (NumLiveRetVals == RetCount) 582 continue; 583 584 // Check all uses of the return value. 585 for (const Use &U : TheCall->uses()) { 586 if (ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U.getUser())) { 587 // This use uses a part of our return value, survey the uses of 588 // that part and store the results for this index only. 589 unsigned Idx = *Ext->idx_begin(); 590 if (RetValLiveness[Idx] != Live) { 591 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]); 592 if (RetValLiveness[Idx] == Live) 593 NumLiveRetVals++; 594 } 595 } else { 596 // Used by something else than extractvalue. Survey, but assume that the 597 // result applies to all sub-values. 598 UseVector MaybeLiveAggregateUses; 599 if (SurveyUse(&U, MaybeLiveAggregateUses) == Live) { 600 NumLiveRetVals = RetCount; 601 RetValLiveness.assign(RetCount, Live); 602 break; 603 } else { 604 for (unsigned i = 0; i != RetCount; ++i) { 605 if (RetValLiveness[i] != Live) 606 MaybeLiveRetUses[i].append(MaybeLiveAggregateUses.begin(), 607 MaybeLiveAggregateUses.end()); 608 } 609 } 610 } 611 } 612 } 613 614 if (HasMustTailCallers) { 615 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName() 616 << " has musttail callers\n"); 617 } 618 619 // Now we've inspected all callers, record the liveness of our return values. 620 for (unsigned i = 0; i != RetCount; ++i) 621 MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]); 622 623 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Inspecting args for fn: " 624 << F.getName() << "\n"); 625 626 // Now, check all of our arguments. 627 unsigned i = 0; 628 UseVector MaybeLiveArgUses; 629 for (Function::const_arg_iterator AI = F.arg_begin(), 630 E = F.arg_end(); AI != E; ++AI, ++i) { 631 Liveness Result; 632 if (F.getFunctionType()->isVarArg() || HasMustTailCallers || 633 HasMustTailCalls) { 634 // Variadic functions will already have a va_arg function expanded inside 635 // them, making them potentially very sensitive to ABI changes resulting 636 // from removing arguments entirely, so don't. For example AArch64 handles 637 // register and stack HFAs very differently, and this is reflected in the 638 // IR which has already been generated. 639 // 640 // `musttail` calls to this function restrict argument removal attempts. 641 // The signature of the caller must match the signature of the function. 642 // 643 // `musttail` calls in this function prevents us from changing its 644 // signature 645 Result = Live; 646 } else { 647 // See what the effect of this use is (recording any uses that cause 648 // MaybeLive in MaybeLiveArgUses). 649 Result = SurveyUses(&*AI, MaybeLiveArgUses); 650 } 651 652 // Mark the result. 653 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses); 654 // Clear the vector again for the next iteration. 655 MaybeLiveArgUses.clear(); 656 } 657 } 658 659 /// MarkValue - This function marks the liveness of RA depending on L. If L is 660 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses, 661 /// such that RA will be marked live if any use in MaybeLiveUses gets marked 662 /// live later on. 663 void DeadArgumentEliminationPass::MarkValue(const RetOrArg &RA, Liveness L, 664 const UseVector &MaybeLiveUses) { 665 switch (L) { 666 case Live: 667 MarkLive(RA); 668 break; 669 case MaybeLive: 670 // Note any uses of this value, so this return value can be 671 // marked live whenever one of the uses becomes live. 672 for (const auto &MaybeLiveUse : MaybeLiveUses) 673 Uses.insert(std::make_pair(MaybeLiveUse, RA)); 674 break; 675 } 676 } 677 678 /// MarkLive - Mark the given Function as alive, meaning that it cannot be 679 /// changed in any way. Additionally, 680 /// mark any values that are used as this function's parameters or by its return 681 /// values (according to Uses) live as well. 682 void DeadArgumentEliminationPass::MarkLive(const Function &F) { 683 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Intrinsically live fn: " 684 << F.getName() << "\n"); 685 // Mark the function as live. 686 LiveFunctions.insert(&F); 687 // Mark all arguments as live. 688 for (unsigned i = 0, e = F.arg_size(); i != e; ++i) 689 PropagateLiveness(CreateArg(&F, i)); 690 // Mark all return values as live. 691 for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i) 692 PropagateLiveness(CreateRet(&F, i)); 693 } 694 695 /// MarkLive - Mark the given return value or argument as live. Additionally, 696 /// mark any values that are used by this value (according to Uses) live as 697 /// well. 698 void DeadArgumentEliminationPass::MarkLive(const RetOrArg &RA) { 699 if (LiveFunctions.count(RA.F)) 700 return; // Function was already marked Live. 701 702 if (!LiveValues.insert(RA).second) 703 return; // We were already marked Live. 704 705 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Marking " 706 << RA.getDescription() << " live\n"); 707 PropagateLiveness(RA); 708 } 709 710 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness 711 /// to any other values it uses (according to Uses). 712 void DeadArgumentEliminationPass::PropagateLiveness(const RetOrArg &RA) { 713 // We don't use upper_bound (or equal_range) here, because our recursive call 714 // to ourselves is likely to cause the upper_bound (which is the first value 715 // not belonging to RA) to become erased and the iterator invalidated. 716 UseMap::iterator Begin = Uses.lower_bound(RA); 717 UseMap::iterator E = Uses.end(); 718 UseMap::iterator I; 719 for (I = Begin; I != E && I->first == RA; ++I) 720 MarkLive(I->second); 721 722 // Erase RA from the Uses map (from the lower bound to wherever we ended up 723 // after the loop). 724 Uses.erase(Begin, I); 725 } 726 727 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F 728 // that are not in LiveValues. Transform the function and all of the callees of 729 // the function to not have these arguments and return values. 730 // 731 bool DeadArgumentEliminationPass::RemoveDeadStuffFromFunction(Function *F) { 732 // Don't modify fully live functions 733 if (LiveFunctions.count(F)) 734 return false; 735 736 // Start by computing a new prototype for the function, which is the same as 737 // the old function, but has fewer arguments and a different return type. 738 FunctionType *FTy = F->getFunctionType(); 739 std::vector<Type*> Params; 740 741 // Keep track of if we have a live 'returned' argument 742 bool HasLiveReturnedArg = false; 743 744 // Set up to build a new list of parameter attributes. 745 SmallVector<AttributeSet, 8> ArgAttrVec; 746 const AttributeList &PAL = F->getAttributes(); 747 748 // Remember which arguments are still alive. 749 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false); 750 // Construct the new parameter list from non-dead arguments. Also construct 751 // a new set of parameter attributes to correspond. Skip the first parameter 752 // attribute, since that belongs to the return value. 753 unsigned i = 0; 754 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 755 I != E; ++I, ++i) { 756 RetOrArg Arg = CreateArg(F, i); 757 if (LiveValues.erase(Arg)) { 758 Params.push_back(I->getType()); 759 ArgAlive[i] = true; 760 ArgAttrVec.push_back(PAL.getParamAttributes(i)); 761 HasLiveReturnedArg |= PAL.hasParamAttribute(i, Attribute::Returned); 762 } else { 763 ++NumArgumentsEliminated; 764 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Removing argument " 765 << i << " (" << I->getName() << ") from " 766 << F->getName() << "\n"); 767 } 768 } 769 770 // Find out the new return value. 771 Type *RetTy = FTy->getReturnType(); 772 Type *NRetTy = nullptr; 773 unsigned RetCount = NumRetVals(F); 774 775 // -1 means unused, other numbers are the new index 776 SmallVector<int, 5> NewRetIdxs(RetCount, -1); 777 std::vector<Type*> RetTypes; 778 779 // If there is a function with a live 'returned' argument but a dead return 780 // value, then there are two possible actions: 781 // 1) Eliminate the return value and take off the 'returned' attribute on the 782 // argument. 783 // 2) Retain the 'returned' attribute and treat the return value (but not the 784 // entire function) as live so that it is not eliminated. 785 // 786 // It's not clear in the general case which option is more profitable because, 787 // even in the absence of explicit uses of the return value, code generation 788 // is free to use the 'returned' attribute to do things like eliding 789 // save/restores of registers across calls. Whether or not this happens is 790 // target and ABI-specific as well as depending on the amount of register 791 // pressure, so there's no good way for an IR-level pass to figure this out. 792 // 793 // Fortunately, the only places where 'returned' is currently generated by 794 // the FE are places where 'returned' is basically free and almost always a 795 // performance win, so the second option can just be used always for now. 796 // 797 // This should be revisited if 'returned' is ever applied more liberally. 798 if (RetTy->isVoidTy() || HasLiveReturnedArg) { 799 NRetTy = RetTy; 800 } else { 801 // Look at each of the original return values individually. 802 for (unsigned i = 0; i != RetCount; ++i) { 803 RetOrArg Ret = CreateRet(F, i); 804 if (LiveValues.erase(Ret)) { 805 RetTypes.push_back(getRetComponentType(F, i)); 806 NewRetIdxs[i] = RetTypes.size() - 1; 807 } else { 808 ++NumRetValsEliminated; 809 LLVM_DEBUG( 810 dbgs() << "DeadArgumentEliminationPass - Removing return value " 811 << i << " from " << F->getName() << "\n"); 812 } 813 } 814 if (RetTypes.size() > 1) { 815 // More than one return type? Reduce it down to size. 816 if (StructType *STy = dyn_cast<StructType>(RetTy)) { 817 // Make the new struct packed if we used to return a packed struct 818 // already. 819 NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked()); 820 } else { 821 assert(isa<ArrayType>(RetTy) && "unexpected multi-value return"); 822 NRetTy = ArrayType::get(RetTypes[0], RetTypes.size()); 823 } 824 } else if (RetTypes.size() == 1) 825 // One return type? Just a simple value then, but only if we didn't use to 826 // return a struct with that simple value before. 827 NRetTy = RetTypes.front(); 828 else if (RetTypes.empty()) 829 // No return types? Make it void, but only if we didn't use to return {}. 830 NRetTy = Type::getVoidTy(F->getContext()); 831 } 832 833 assert(NRetTy && "No new return type found?"); 834 835 // The existing function return attributes. 836 AttrBuilder RAttrs(PAL.getRetAttributes()); 837 838 // Remove any incompatible attributes, but only if we removed all return 839 // values. Otherwise, ensure that we don't have any conflicting attributes 840 // here. Currently, this should not be possible, but special handling might be 841 // required when new return value attributes are added. 842 if (NRetTy->isVoidTy()) 843 RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy)); 844 else 845 assert(!RAttrs.overlaps(AttributeFuncs::typeIncompatible(NRetTy)) && 846 "Return attributes no longer compatible?"); 847 848 AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs); 849 850 // Strip allocsize attributes. They might refer to the deleted arguments. 851 AttributeSet FnAttrs = PAL.getFnAttributes().removeAttribute( 852 F->getContext(), Attribute::AllocSize); 853 854 // Reconstruct the AttributesList based on the vector we constructed. 855 assert(ArgAttrVec.size() == Params.size()); 856 AttributeList NewPAL = 857 AttributeList::get(F->getContext(), FnAttrs, RetAttrs, ArgAttrVec); 858 859 // Create the new function type based on the recomputed parameters. 860 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg()); 861 862 // No change? 863 if (NFTy == FTy) 864 return false; 865 866 // Create the new function body and insert it into the module... 867 Function *NF = Function::Create(NFTy, F->getLinkage()); 868 NF->copyAttributesFrom(F); 869 NF->setComdat(F->getComdat()); 870 NF->setAttributes(NewPAL); 871 // Insert the new function before the old function, so we won't be processing 872 // it again. 873 F->getParent()->getFunctionList().insert(F->getIterator(), NF); 874 NF->takeName(F); 875 876 // Loop over all of the callers of the function, transforming the call sites 877 // to pass in a smaller number of arguments into the new function. 878 std::vector<Value*> Args; 879 while (!F->use_empty()) { 880 CallSite CS(F->user_back()); 881 Instruction *Call = CS.getInstruction(); 882 883 ArgAttrVec.clear(); 884 const AttributeList &CallPAL = CS.getAttributes(); 885 886 // Adjust the call return attributes in case the function was changed to 887 // return void. 888 AttrBuilder RAttrs(CallPAL.getRetAttributes()); 889 RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy)); 890 AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs); 891 892 // Declare these outside of the loops, so we can reuse them for the second 893 // loop, which loops the varargs. 894 CallSite::arg_iterator I = CS.arg_begin(); 895 unsigned i = 0; 896 // Loop over those operands, corresponding to the normal arguments to the 897 // original function, and add those that are still alive. 898 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i) 899 if (ArgAlive[i]) { 900 Args.push_back(*I); 901 // Get original parameter attributes, but skip return attributes. 902 AttributeSet Attrs = CallPAL.getParamAttributes(i); 903 if (NRetTy != RetTy && Attrs.hasAttribute(Attribute::Returned)) { 904 // If the return type has changed, then get rid of 'returned' on the 905 // call site. The alternative is to make all 'returned' attributes on 906 // call sites keep the return value alive just like 'returned' 907 // attributes on function declaration but it's less clearly a win and 908 // this is not an expected case anyway 909 ArgAttrVec.push_back(AttributeSet::get( 910 F->getContext(), 911 AttrBuilder(Attrs).removeAttribute(Attribute::Returned))); 912 } else { 913 // Otherwise, use the original attributes. 914 ArgAttrVec.push_back(Attrs); 915 } 916 } 917 918 // Push any varargs arguments on the list. Don't forget their attributes. 919 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) { 920 Args.push_back(*I); 921 ArgAttrVec.push_back(CallPAL.getParamAttributes(i)); 922 } 923 924 // Reconstruct the AttributesList based on the vector we constructed. 925 assert(ArgAttrVec.size() == Args.size()); 926 927 // Again, be sure to remove any allocsize attributes, since their indices 928 // may now be incorrect. 929 AttributeSet FnAttrs = CallPAL.getFnAttributes().removeAttribute( 930 F->getContext(), Attribute::AllocSize); 931 932 AttributeList NewCallPAL = AttributeList::get( 933 F->getContext(), FnAttrs, RetAttrs, ArgAttrVec); 934 935 SmallVector<OperandBundleDef, 1> OpBundles; 936 CS.getOperandBundlesAsDefs(OpBundles); 937 938 CallSite NewCS; 939 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 940 NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 941 Args, OpBundles, "", Call->getParent()); 942 } else { 943 NewCS = CallInst::Create(NF, Args, OpBundles, "", Call); 944 cast<CallInst>(NewCS.getInstruction()) 945 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind()); 946 } 947 NewCS.setCallingConv(CS.getCallingConv()); 948 NewCS.setAttributes(NewCallPAL); 949 NewCS->setDebugLoc(Call->getDebugLoc()); 950 uint64_t W; 951 if (Call->extractProfTotalWeight(W)) 952 NewCS->setProfWeight(W); 953 Args.clear(); 954 ArgAttrVec.clear(); 955 956 Instruction *New = NewCS.getInstruction(); 957 if (!Call->use_empty()) { 958 if (New->getType() == Call->getType()) { 959 // Return type not changed? Just replace users then. 960 Call->replaceAllUsesWith(New); 961 New->takeName(Call); 962 } else if (New->getType()->isVoidTy()) { 963 // Our return value has uses, but they will get removed later on. 964 // Replace by null for now. 965 if (!Call->getType()->isX86_MMXTy()) 966 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType())); 967 } else { 968 assert((RetTy->isStructTy() || RetTy->isArrayTy()) && 969 "Return type changed, but not into a void. The old return type" 970 " must have been a struct or an array!"); 971 Instruction *InsertPt = Call; 972 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 973 BasicBlock *NewEdge = SplitEdge(New->getParent(), II->getNormalDest()); 974 InsertPt = &*NewEdge->getFirstInsertionPt(); 975 } 976 977 // We used to return a struct or array. Instead of doing smart stuff 978 // with all the uses, we will just rebuild it using extract/insertvalue 979 // chaining and let instcombine clean that up. 980 // 981 // Start out building up our return value from undef 982 Value *RetVal = UndefValue::get(RetTy); 983 for (unsigned i = 0; i != RetCount; ++i) 984 if (NewRetIdxs[i] != -1) { 985 Value *V; 986 if (RetTypes.size() > 1) 987 // We are still returning a struct, so extract the value from our 988 // return value 989 V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret", 990 InsertPt); 991 else 992 // We are now returning a single element, so just insert that 993 V = New; 994 // Insert the value at the old position 995 RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt); 996 } 997 // Now, replace all uses of the old call instruction with the return 998 // struct we built 999 Call->replaceAllUsesWith(RetVal); 1000 New->takeName(Call); 1001 } 1002 } 1003 1004 // Finally, remove the old call from the program, reducing the use-count of 1005 // F. 1006 Call->eraseFromParent(); 1007 } 1008 1009 // Since we have now created the new function, splice the body of the old 1010 // function right into the new function, leaving the old rotting hulk of the 1011 // function empty. 1012 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 1013 1014 // Loop over the argument list, transferring uses of the old arguments over to 1015 // the new arguments, also transferring over the names as well. 1016 i = 0; 1017 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 1018 I2 = NF->arg_begin(); I != E; ++I, ++i) 1019 if (ArgAlive[i]) { 1020 // If this is a live argument, move the name and users over to the new 1021 // version. 1022 I->replaceAllUsesWith(&*I2); 1023 I2->takeName(&*I); 1024 ++I2; 1025 } else { 1026 // If this argument is dead, replace any uses of it with null constants 1027 // (these are guaranteed to become unused later on). 1028 if (!I->getType()->isX86_MMXTy()) 1029 I->replaceAllUsesWith(Constant::getNullValue(I->getType())); 1030 } 1031 1032 // If we change the return value of the function we must rewrite any return 1033 // instructions. Check this now. 1034 if (F->getReturnType() != NF->getReturnType()) 1035 for (BasicBlock &BB : *NF) 1036 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) { 1037 Value *RetVal; 1038 1039 if (NFTy->getReturnType()->isVoidTy()) { 1040 RetVal = nullptr; 1041 } else { 1042 assert(RetTy->isStructTy() || RetTy->isArrayTy()); 1043 // The original return value was a struct or array, insert 1044 // extractvalue/insertvalue chains to extract only the values we need 1045 // to return and insert them into our new result. 1046 // This does generate messy code, but we'll let it to instcombine to 1047 // clean that up. 1048 Value *OldRet = RI->getOperand(0); 1049 // Start out building up our return value from undef 1050 RetVal = UndefValue::get(NRetTy); 1051 for (unsigned i = 0; i != RetCount; ++i) 1052 if (NewRetIdxs[i] != -1) { 1053 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i, 1054 "oldret", RI); 1055 if (RetTypes.size() > 1) { 1056 // We're still returning a struct, so reinsert the value into 1057 // our new return value at the new index 1058 1059 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i], 1060 "newret", RI); 1061 } else { 1062 // We are now only returning a simple value, so just return the 1063 // extracted value. 1064 RetVal = EV; 1065 } 1066 } 1067 } 1068 // Replace the return instruction with one returning the new return 1069 // value (possibly 0 if we became void). 1070 ReturnInst::Create(F->getContext(), RetVal, RI); 1071 BB.getInstList().erase(RI); 1072 } 1073 1074 // Clone metadatas from the old function, including debug info descriptor. 1075 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1076 F->getAllMetadata(MDs); 1077 for (auto MD : MDs) 1078 NF->addMetadata(MD.first, *MD.second); 1079 1080 // Now that the old function is dead, delete it. 1081 F->eraseFromParent(); 1082 1083 return true; 1084 } 1085 1086 PreservedAnalyses DeadArgumentEliminationPass::run(Module &M, 1087 ModuleAnalysisManager &) { 1088 bool Changed = false; 1089 1090 // First pass: Do a simple check to see if any functions can have their "..." 1091 // removed. We can do this if they never call va_start. This loop cannot be 1092 // fused with the next loop, because deleting a function invalidates 1093 // information computed while surveying other functions. 1094 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Deleting dead varargs\n"); 1095 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 1096 Function &F = *I++; 1097 if (F.getFunctionType()->isVarArg()) 1098 Changed |= DeleteDeadVarargs(F); 1099 } 1100 1101 // Second phase:loop through the module, determining which arguments are live. 1102 // We assume all arguments are dead unless proven otherwise (allowing us to 1103 // determine that dead arguments passed into recursive functions are dead). 1104 // 1105 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Determining liveness\n"); 1106 for (auto &F : M) 1107 SurveyFunction(F); 1108 1109 // Now, remove all dead arguments and return values from each function in 1110 // turn. 1111 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 1112 // Increment now, because the function will probably get removed (ie. 1113 // replaced by a new one). 1114 Function *F = &*I++; 1115 Changed |= RemoveDeadStuffFromFunction(F); 1116 } 1117 1118 // Finally, look for any unused parameters in functions with non-local 1119 // linkage and replace the passed in parameters with undef. 1120 for (auto &F : M) 1121 Changed |= RemoveDeadArgumentsFromCallers(F); 1122 1123 if (!Changed) 1124 return PreservedAnalyses::all(); 1125 return PreservedAnalyses::none(); 1126 } 1127