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