1 //===- InlineFunction.cpp - Code to perform function inlining -------------===// 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 file implements inlining of a function into a call site, resolving 10 // parameters and the return value as appropriate. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/DenseMap.h" 15 #include "llvm/ADT/None.h" 16 #include "llvm/ADT/Optional.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/iterator_range.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/AssumptionCache.h" 25 #include "llvm/Analysis/BlockFrequencyInfo.h" 26 #include "llvm/Analysis/CallGraph.h" 27 #include "llvm/Analysis/CaptureTracking.h" 28 #include "llvm/Analysis/EHPersonalities.h" 29 #include "llvm/Analysis/InstructionSimplify.h" 30 #include "llvm/Analysis/ObjCARCAnalysisUtils.h" 31 #include "llvm/Analysis/ObjCARCUtil.h" 32 #include "llvm/Analysis/ProfileSummaryInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/Analysis/VectorUtils.h" 35 #include "llvm/IR/Argument.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CFG.h" 38 #include "llvm/IR/Constant.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DIBuilder.h" 41 #include "llvm/IR/DataLayout.h" 42 #include "llvm/IR/DebugInfoMetadata.h" 43 #include "llvm/IR/DebugLoc.h" 44 #include "llvm/IR/DerivedTypes.h" 45 #include "llvm/IR/Dominators.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/IR/IRBuilder.h" 48 #include "llvm/IR/InlineAsm.h" 49 #include "llvm/IR/InstrTypes.h" 50 #include "llvm/IR/Instruction.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/IntrinsicInst.h" 53 #include "llvm/IR/Intrinsics.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/MDBuilder.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/Type.h" 59 #include "llvm/IR/User.h" 60 #include "llvm/IR/Value.h" 61 #include "llvm/Support/Casting.h" 62 #include "llvm/Support/CommandLine.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 65 #include "llvm/Transforms/Utils/Cloning.h" 66 #include "llvm/Transforms/Utils/Local.h" 67 #include "llvm/Transforms/Utils/ValueMapper.h" 68 #include <algorithm> 69 #include <cassert> 70 #include <cstdint> 71 #include <iterator> 72 #include <limits> 73 #include <string> 74 #include <utility> 75 #include <vector> 76 77 using namespace llvm; 78 using ProfileCount = Function::ProfileCount; 79 80 static cl::opt<bool> 81 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true), 82 cl::Hidden, 83 cl::desc("Convert noalias attributes to metadata during inlining.")); 84 85 static cl::opt<bool> 86 UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden, 87 cl::ZeroOrMore, cl::init(true), 88 cl::desc("Use the llvm.experimental.noalias.scope.decl " 89 "intrinsic during inlining.")); 90 91 // Disabled by default, because the added alignment assumptions may increase 92 // compile-time and block optimizations. This option is not suitable for use 93 // with frontends that emit comprehensive parameter alignment annotations. 94 static cl::opt<bool> 95 PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining", 96 cl::init(false), cl::Hidden, 97 cl::desc("Convert align attributes to assumptions during inlining.")); 98 99 static cl::opt<bool> UpdateReturnAttributes( 100 "update-return-attrs", cl::init(true), cl::Hidden, 101 cl::desc("Update return attributes on calls within inlined body")); 102 103 static cl::opt<unsigned> InlinerAttributeWindow( 104 "max-inst-checked-for-throw-during-inlining", cl::Hidden, 105 cl::desc("the maximum number of instructions analyzed for may throw during " 106 "attribute inference in inlined body"), 107 cl::init(4)); 108 109 namespace { 110 111 /// A class for recording information about inlining a landing pad. 112 class LandingPadInliningInfo { 113 /// Destination of the invoke's unwind. 114 BasicBlock *OuterResumeDest; 115 116 /// Destination for the callee's resume. 117 BasicBlock *InnerResumeDest = nullptr; 118 119 /// LandingPadInst associated with the invoke. 120 LandingPadInst *CallerLPad = nullptr; 121 122 /// PHI for EH values from landingpad insts. 123 PHINode *InnerEHValuesPHI = nullptr; 124 125 SmallVector<Value*, 8> UnwindDestPHIValues; 126 127 public: 128 LandingPadInliningInfo(InvokeInst *II) 129 : OuterResumeDest(II->getUnwindDest()) { 130 // If there are PHI nodes in the unwind destination block, we need to keep 131 // track of which values came into them from the invoke before removing 132 // the edge from this block. 133 BasicBlock *InvokeBB = II->getParent(); 134 BasicBlock::iterator I = OuterResumeDest->begin(); 135 for (; isa<PHINode>(I); ++I) { 136 // Save the value to use for this edge. 137 PHINode *PHI = cast<PHINode>(I); 138 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB)); 139 } 140 141 CallerLPad = cast<LandingPadInst>(I); 142 } 143 144 /// The outer unwind destination is the target of 145 /// unwind edges introduced for calls within the inlined function. 146 BasicBlock *getOuterResumeDest() const { 147 return OuterResumeDest; 148 } 149 150 BasicBlock *getInnerResumeDest(); 151 152 LandingPadInst *getLandingPadInst() const { return CallerLPad; } 153 154 /// Forward the 'resume' instruction to the caller's landing pad block. 155 /// When the landing pad block has only one predecessor, this is 156 /// a simple branch. When there is more than one predecessor, we need to 157 /// split the landing pad block after the landingpad instruction and jump 158 /// to there. 159 void forwardResume(ResumeInst *RI, 160 SmallPtrSetImpl<LandingPadInst*> &InlinedLPads); 161 162 /// Add incoming-PHI values to the unwind destination block for the given 163 /// basic block, using the values for the original invoke's source block. 164 void addIncomingPHIValuesFor(BasicBlock *BB) const { 165 addIncomingPHIValuesForInto(BB, OuterResumeDest); 166 } 167 168 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const { 169 BasicBlock::iterator I = dest->begin(); 170 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { 171 PHINode *phi = cast<PHINode>(I); 172 phi->addIncoming(UnwindDestPHIValues[i], src); 173 } 174 } 175 }; 176 177 } // end anonymous namespace 178 179 /// Get or create a target for the branch from ResumeInsts. 180 BasicBlock *LandingPadInliningInfo::getInnerResumeDest() { 181 if (InnerResumeDest) return InnerResumeDest; 182 183 // Split the landing pad. 184 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator(); 185 InnerResumeDest = 186 OuterResumeDest->splitBasicBlock(SplitPoint, 187 OuterResumeDest->getName() + ".body"); 188 189 // The number of incoming edges we expect to the inner landing pad. 190 const unsigned PHICapacity = 2; 191 192 // Create corresponding new PHIs for all the PHIs in the outer landing pad. 193 Instruction *InsertPoint = &InnerResumeDest->front(); 194 BasicBlock::iterator I = OuterResumeDest->begin(); 195 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { 196 PHINode *OuterPHI = cast<PHINode>(I); 197 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity, 198 OuterPHI->getName() + ".lpad-body", 199 InsertPoint); 200 OuterPHI->replaceAllUsesWith(InnerPHI); 201 InnerPHI->addIncoming(OuterPHI, OuterResumeDest); 202 } 203 204 // Create a PHI for the exception values. 205 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity, 206 "eh.lpad-body", InsertPoint); 207 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI); 208 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest); 209 210 // All done. 211 return InnerResumeDest; 212 } 213 214 /// Forward the 'resume' instruction to the caller's landing pad block. 215 /// When the landing pad block has only one predecessor, this is a simple 216 /// branch. When there is more than one predecessor, we need to split the 217 /// landing pad block after the landingpad instruction and jump to there. 218 void LandingPadInliningInfo::forwardResume( 219 ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) { 220 BasicBlock *Dest = getInnerResumeDest(); 221 BasicBlock *Src = RI->getParent(); 222 223 BranchInst::Create(Dest, Src); 224 225 // Update the PHIs in the destination. They were inserted in an order which 226 // makes this work. 227 addIncomingPHIValuesForInto(Src, Dest); 228 229 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src); 230 RI->eraseFromParent(); 231 } 232 233 /// Helper for getUnwindDestToken/getUnwindDestTokenHelper. 234 static Value *getParentPad(Value *EHPad) { 235 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 236 return FPI->getParentPad(); 237 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 238 } 239 240 using UnwindDestMemoTy = DenseMap<Instruction *, Value *>; 241 242 /// Helper for getUnwindDestToken that does the descendant-ward part of 243 /// the search. 244 static Value *getUnwindDestTokenHelper(Instruction *EHPad, 245 UnwindDestMemoTy &MemoMap) { 246 SmallVector<Instruction *, 8> Worklist(1, EHPad); 247 248 while (!Worklist.empty()) { 249 Instruction *CurrentPad = Worklist.pop_back_val(); 250 // We only put pads on the worklist that aren't in the MemoMap. When 251 // we find an unwind dest for a pad we may update its ancestors, but 252 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad, 253 // so they should never get updated while queued on the worklist. 254 assert(!MemoMap.count(CurrentPad)); 255 Value *UnwindDestToken = nullptr; 256 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) { 257 if (CatchSwitch->hasUnwindDest()) { 258 UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI(); 259 } else { 260 // Catchswitch doesn't have a 'nounwind' variant, and one might be 261 // annotated as "unwinds to caller" when really it's nounwind (see 262 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the 263 // parent's unwind dest from this. We can check its catchpads' 264 // descendants, since they might include a cleanuppad with an 265 // "unwinds to caller" cleanupret, which can be trusted. 266 for (auto HI = CatchSwitch->handler_begin(), 267 HE = CatchSwitch->handler_end(); 268 HI != HE && !UnwindDestToken; ++HI) { 269 BasicBlock *HandlerBlock = *HI; 270 auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI()); 271 for (User *Child : CatchPad->users()) { 272 // Intentionally ignore invokes here -- since the catchswitch is 273 // marked "unwind to caller", it would be a verifier error if it 274 // contained an invoke which unwinds out of it, so any invoke we'd 275 // encounter must unwind to some child of the catch. 276 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child)) 277 continue; 278 279 Instruction *ChildPad = cast<Instruction>(Child); 280 auto Memo = MemoMap.find(ChildPad); 281 if (Memo == MemoMap.end()) { 282 // Haven't figured out this child pad yet; queue it. 283 Worklist.push_back(ChildPad); 284 continue; 285 } 286 // We've already checked this child, but might have found that 287 // it offers no proof either way. 288 Value *ChildUnwindDestToken = Memo->second; 289 if (!ChildUnwindDestToken) 290 continue; 291 // We already know the child's unwind dest, which can either 292 // be ConstantTokenNone to indicate unwind to caller, or can 293 // be another child of the catchpad. Only the former indicates 294 // the unwind dest of the catchswitch. 295 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) { 296 UnwindDestToken = ChildUnwindDestToken; 297 break; 298 } 299 assert(getParentPad(ChildUnwindDestToken) == CatchPad); 300 } 301 } 302 } 303 } else { 304 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad); 305 for (User *U : CleanupPad->users()) { 306 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) { 307 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest()) 308 UnwindDestToken = RetUnwindDest->getFirstNonPHI(); 309 else 310 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext()); 311 break; 312 } 313 Value *ChildUnwindDestToken; 314 if (auto *Invoke = dyn_cast<InvokeInst>(U)) { 315 ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI(); 316 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) { 317 Instruction *ChildPad = cast<Instruction>(U); 318 auto Memo = MemoMap.find(ChildPad); 319 if (Memo == MemoMap.end()) { 320 // Haven't resolved this child yet; queue it and keep searching. 321 Worklist.push_back(ChildPad); 322 continue; 323 } 324 // We've checked this child, but still need to ignore it if it 325 // had no proof either way. 326 ChildUnwindDestToken = Memo->second; 327 if (!ChildUnwindDestToken) 328 continue; 329 } else { 330 // Not a relevant user of the cleanuppad 331 continue; 332 } 333 // In a well-formed program, the child/invoke must either unwind to 334 // an(other) child of the cleanup, or exit the cleanup. In the 335 // first case, continue searching. 336 if (isa<Instruction>(ChildUnwindDestToken) && 337 getParentPad(ChildUnwindDestToken) == CleanupPad) 338 continue; 339 UnwindDestToken = ChildUnwindDestToken; 340 break; 341 } 342 } 343 // If we haven't found an unwind dest for CurrentPad, we may have queued its 344 // children, so move on to the next in the worklist. 345 if (!UnwindDestToken) 346 continue; 347 348 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits 349 // any ancestors of CurrentPad up to but not including UnwindDestToken's 350 // parent pad. Record this in the memo map, and check to see if the 351 // original EHPad being queried is one of the ones exited. 352 Value *UnwindParent; 353 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken)) 354 UnwindParent = getParentPad(UnwindPad); 355 else 356 UnwindParent = nullptr; 357 bool ExitedOriginalPad = false; 358 for (Instruction *ExitedPad = CurrentPad; 359 ExitedPad && ExitedPad != UnwindParent; 360 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) { 361 // Skip over catchpads since they just follow their catchswitches. 362 if (isa<CatchPadInst>(ExitedPad)) 363 continue; 364 MemoMap[ExitedPad] = UnwindDestToken; 365 ExitedOriginalPad |= (ExitedPad == EHPad); 366 } 367 368 if (ExitedOriginalPad) 369 return UnwindDestToken; 370 371 // Continue the search. 372 } 373 374 // No definitive information is contained within this funclet. 375 return nullptr; 376 } 377 378 /// Given an EH pad, find where it unwinds. If it unwinds to an EH pad, 379 /// return that pad instruction. If it unwinds to caller, return 380 /// ConstantTokenNone. If it does not have a definitive unwind destination, 381 /// return nullptr. 382 /// 383 /// This routine gets invoked for calls in funclets in inlinees when inlining 384 /// an invoke. Since many funclets don't have calls inside them, it's queried 385 /// on-demand rather than building a map of pads to unwind dests up front. 386 /// Determining a funclet's unwind dest may require recursively searching its 387 /// descendants, and also ancestors and cousins if the descendants don't provide 388 /// an answer. Since most funclets will have their unwind dest immediately 389 /// available as the unwind dest of a catchswitch or cleanupret, this routine 390 /// searches top-down from the given pad and then up. To avoid worst-case 391 /// quadratic run-time given that approach, it uses a memo map to avoid 392 /// re-processing funclet trees. The callers that rewrite the IR as they go 393 /// take advantage of this, for correctness, by checking/forcing rewritten 394 /// pads' entries to match the original callee view. 395 static Value *getUnwindDestToken(Instruction *EHPad, 396 UnwindDestMemoTy &MemoMap) { 397 // Catchpads unwind to the same place as their catchswitch; 398 // redirct any queries on catchpads so the code below can 399 // deal with just catchswitches and cleanuppads. 400 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad)) 401 EHPad = CPI->getCatchSwitch(); 402 403 // Check if we've already determined the unwind dest for this pad. 404 auto Memo = MemoMap.find(EHPad); 405 if (Memo != MemoMap.end()) 406 return Memo->second; 407 408 // Search EHPad and, if necessary, its descendants. 409 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap); 410 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0)); 411 if (UnwindDestToken) 412 return UnwindDestToken; 413 414 // No information is available for this EHPad from itself or any of its 415 // descendants. An unwind all the way out to a pad in the caller would 416 // need also to agree with the unwind dest of the parent funclet, so 417 // search up the chain to try to find a funclet with information. Put 418 // null entries in the memo map to avoid re-processing as we go up. 419 MemoMap[EHPad] = nullptr; 420 #ifndef NDEBUG 421 SmallPtrSet<Instruction *, 4> TempMemos; 422 TempMemos.insert(EHPad); 423 #endif 424 Instruction *LastUselessPad = EHPad; 425 Value *AncestorToken; 426 for (AncestorToken = getParentPad(EHPad); 427 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken); 428 AncestorToken = getParentPad(AncestorToken)) { 429 // Skip over catchpads since they just follow their catchswitches. 430 if (isa<CatchPadInst>(AncestorPad)) 431 continue; 432 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we 433 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this 434 // call to getUnwindDestToken, that would mean that AncestorPad had no 435 // information in itself, its descendants, or its ancestors. If that 436 // were the case, then we should also have recorded the lack of information 437 // for the descendant that we're coming from. So assert that we don't 438 // find a null entry in the MemoMap for AncestorPad. 439 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]); 440 auto AncestorMemo = MemoMap.find(AncestorPad); 441 if (AncestorMemo == MemoMap.end()) { 442 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap); 443 } else { 444 UnwindDestToken = AncestorMemo->second; 445 } 446 if (UnwindDestToken) 447 break; 448 LastUselessPad = AncestorPad; 449 MemoMap[LastUselessPad] = nullptr; 450 #ifndef NDEBUG 451 TempMemos.insert(LastUselessPad); 452 #endif 453 } 454 455 // We know that getUnwindDestTokenHelper was called on LastUselessPad and 456 // returned nullptr (and likewise for EHPad and any of its ancestors up to 457 // LastUselessPad), so LastUselessPad has no information from below. Since 458 // getUnwindDestTokenHelper must investigate all downward paths through 459 // no-information nodes to prove that a node has no information like this, 460 // and since any time it finds information it records it in the MemoMap for 461 // not just the immediately-containing funclet but also any ancestors also 462 // exited, it must be the case that, walking downward from LastUselessPad, 463 // visiting just those nodes which have not been mapped to an unwind dest 464 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since 465 // they are just used to keep getUnwindDestTokenHelper from repeating work), 466 // any node visited must have been exhaustively searched with no information 467 // for it found. 468 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad); 469 while (!Worklist.empty()) { 470 Instruction *UselessPad = Worklist.pop_back_val(); 471 auto Memo = MemoMap.find(UselessPad); 472 if (Memo != MemoMap.end() && Memo->second) { 473 // Here the name 'UselessPad' is a bit of a misnomer, because we've found 474 // that it is a funclet that does have information about unwinding to 475 // a particular destination; its parent was a useless pad. 476 // Since its parent has no information, the unwind edge must not escape 477 // the parent, and must target a sibling of this pad. This local unwind 478 // gives us no information about EHPad. Leave it and the subtree rooted 479 // at it alone. 480 assert(getParentPad(Memo->second) == getParentPad(UselessPad)); 481 continue; 482 } 483 // We know we don't have information for UselesPad. If it has an entry in 484 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos 485 // added on this invocation of getUnwindDestToken; if a previous invocation 486 // recorded nullptr, it would have had to prove that the ancestors of 487 // UselessPad, which include LastUselessPad, had no information, and that 488 // in turn would have required proving that the descendants of 489 // LastUselesPad, which include EHPad, have no information about 490 // LastUselessPad, which would imply that EHPad was mapped to nullptr in 491 // the MemoMap on that invocation, which isn't the case if we got here. 492 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad)); 493 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind 494 // information that we'd be contradicting by making a map entry for it 495 // (which is something that getUnwindDestTokenHelper must have proved for 496 // us to get here). Just assert on is direct users here; the checks in 497 // this downward walk at its descendants will verify that they don't have 498 // any unwind edges that exit 'UselessPad' either (i.e. they either have no 499 // unwind edges or unwind to a sibling). 500 MemoMap[UselessPad] = UnwindDestToken; 501 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) { 502 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad"); 503 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) { 504 auto *CatchPad = HandlerBlock->getFirstNonPHI(); 505 for (User *U : CatchPad->users()) { 506 assert( 507 (!isa<InvokeInst>(U) || 508 (getParentPad( 509 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == 510 CatchPad)) && 511 "Expected useless pad"); 512 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) 513 Worklist.push_back(cast<Instruction>(U)); 514 } 515 } 516 } else { 517 assert(isa<CleanupPadInst>(UselessPad)); 518 for (User *U : UselessPad->users()) { 519 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad"); 520 assert((!isa<InvokeInst>(U) || 521 (getParentPad( 522 cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == 523 UselessPad)) && 524 "Expected useless pad"); 525 if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) 526 Worklist.push_back(cast<Instruction>(U)); 527 } 528 } 529 } 530 531 return UnwindDestToken; 532 } 533 534 /// When we inline a basic block into an invoke, 535 /// we have to turn all of the calls that can throw into invokes. 536 /// This function analyze BB to see if there are any calls, and if so, 537 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI 538 /// nodes in that block with the values specified in InvokeDestPHIValues. 539 static BasicBlock *HandleCallsInBlockInlinedThroughInvoke( 540 BasicBlock *BB, BasicBlock *UnwindEdge, 541 UnwindDestMemoTy *FuncletUnwindMap = nullptr) { 542 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 543 Instruction *I = &*BBI++; 544 545 // We only need to check for function calls: inlined invoke 546 // instructions require no special handling. 547 CallInst *CI = dyn_cast<CallInst>(I); 548 549 if (!CI || CI->doesNotThrow()) 550 continue; 551 552 if (CI->isInlineAsm()) { 553 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand()); 554 if (!IA->canThrow()) { 555 continue; 556 } 557 } 558 559 // We do not need to (and in fact, cannot) convert possibly throwing calls 560 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into 561 // invokes. The caller's "segment" of the deoptimization continuation 562 // attached to the newly inlined @llvm.experimental_deoptimize 563 // (resp. @llvm.experimental.guard) call should contain the exception 564 // handling logic, if any. 565 if (auto *F = CI->getCalledFunction()) 566 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize || 567 F->getIntrinsicID() == Intrinsic::experimental_guard) 568 continue; 569 570 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) { 571 // This call is nested inside a funclet. If that funclet has an unwind 572 // destination within the inlinee, then unwinding out of this call would 573 // be UB. Rewriting this call to an invoke which targets the inlined 574 // invoke's unwind dest would give the call's parent funclet multiple 575 // unwind destinations, which is something that subsequent EH table 576 // generation can't handle and that the veirifer rejects. So when we 577 // see such a call, leave it as a call. 578 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]); 579 Value *UnwindDestToken = 580 getUnwindDestToken(FuncletPad, *FuncletUnwindMap); 581 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) 582 continue; 583 #ifndef NDEBUG 584 Instruction *MemoKey; 585 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad)) 586 MemoKey = CatchPad->getCatchSwitch(); 587 else 588 MemoKey = FuncletPad; 589 assert(FuncletUnwindMap->count(MemoKey) && 590 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken && 591 "must get memoized to avoid confusing later searches"); 592 #endif // NDEBUG 593 } 594 595 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge); 596 return BB; 597 } 598 return nullptr; 599 } 600 601 /// If we inlined an invoke site, we need to convert calls 602 /// in the body of the inlined function into invokes. 603 /// 604 /// II is the invoke instruction being inlined. FirstNewBlock is the first 605 /// block of the inlined code (the last block is the end of the function), 606 /// and InlineCodeInfo is information about the code that got inlined. 607 static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock, 608 ClonedCodeInfo &InlinedCodeInfo) { 609 BasicBlock *InvokeDest = II->getUnwindDest(); 610 611 Function *Caller = FirstNewBlock->getParent(); 612 613 // The inlined code is currently at the end of the function, scan from the 614 // start of the inlined code to its end, checking for stuff we need to 615 // rewrite. 616 LandingPadInliningInfo Invoke(II); 617 618 // Get all of the inlined landing pad instructions. 619 SmallPtrSet<LandingPadInst*, 16> InlinedLPads; 620 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end(); 621 I != E; ++I) 622 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) 623 InlinedLPads.insert(II->getLandingPadInst()); 624 625 // Append the clauses from the outer landing pad instruction into the inlined 626 // landing pad instructions. 627 LandingPadInst *OuterLPad = Invoke.getLandingPadInst(); 628 for (LandingPadInst *InlinedLPad : InlinedLPads) { 629 unsigned OuterNum = OuterLPad->getNumClauses(); 630 InlinedLPad->reserveClauses(OuterNum); 631 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx) 632 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx)); 633 if (OuterLPad->isCleanup()) 634 InlinedLPad->setCleanup(true); 635 } 636 637 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); 638 BB != E; ++BB) { 639 if (InlinedCodeInfo.ContainsCalls) 640 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( 641 &*BB, Invoke.getOuterResumeDest())) 642 // Update any PHI nodes in the exceptional block to indicate that there 643 // is now a new entry in them. 644 Invoke.addIncomingPHIValuesFor(NewBB); 645 646 // Forward any resumes that are remaining here. 647 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) 648 Invoke.forwardResume(RI, InlinedLPads); 649 } 650 651 // Now that everything is happy, we have one final detail. The PHI nodes in 652 // the exception destination block still have entries due to the original 653 // invoke instruction. Eliminate these entries (which might even delete the 654 // PHI node) now. 655 InvokeDest->removePredecessor(II->getParent()); 656 } 657 658 /// If we inlined an invoke site, we need to convert calls 659 /// in the body of the inlined function into invokes. 660 /// 661 /// II is the invoke instruction being inlined. FirstNewBlock is the first 662 /// block of the inlined code (the last block is the end of the function), 663 /// and InlineCodeInfo is information about the code that got inlined. 664 static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock, 665 ClonedCodeInfo &InlinedCodeInfo) { 666 BasicBlock *UnwindDest = II->getUnwindDest(); 667 Function *Caller = FirstNewBlock->getParent(); 668 669 assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!"); 670 671 // If there are PHI nodes in the unwind destination block, we need to keep 672 // track of which values came into them from the invoke before removing the 673 // edge from this block. 674 SmallVector<Value *, 8> UnwindDestPHIValues; 675 BasicBlock *InvokeBB = II->getParent(); 676 for (Instruction &I : *UnwindDest) { 677 // Save the value to use for this edge. 678 PHINode *PHI = dyn_cast<PHINode>(&I); 679 if (!PHI) 680 break; 681 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB)); 682 } 683 684 // Add incoming-PHI values to the unwind destination block for the given basic 685 // block, using the values for the original invoke's source block. 686 auto UpdatePHINodes = [&](BasicBlock *Src) { 687 BasicBlock::iterator I = UnwindDest->begin(); 688 for (Value *V : UnwindDestPHIValues) { 689 PHINode *PHI = cast<PHINode>(I); 690 PHI->addIncoming(V, Src); 691 ++I; 692 } 693 }; 694 695 // This connects all the instructions which 'unwind to caller' to the invoke 696 // destination. 697 UnwindDestMemoTy FuncletUnwindMap; 698 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); 699 BB != E; ++BB) { 700 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) { 701 if (CRI->unwindsToCaller()) { 702 auto *CleanupPad = CRI->getCleanupPad(); 703 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI); 704 CRI->eraseFromParent(); 705 UpdatePHINodes(&*BB); 706 // Finding a cleanupret with an unwind destination would confuse 707 // subsequent calls to getUnwindDestToken, so map the cleanuppad 708 // to short-circuit any such calls and recognize this as an "unwind 709 // to caller" cleanup. 710 assert(!FuncletUnwindMap.count(CleanupPad) || 711 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad])); 712 FuncletUnwindMap[CleanupPad] = 713 ConstantTokenNone::get(Caller->getContext()); 714 } 715 } 716 717 Instruction *I = BB->getFirstNonPHI(); 718 if (!I->isEHPad()) 719 continue; 720 721 Instruction *Replacement = nullptr; 722 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { 723 if (CatchSwitch->unwindsToCaller()) { 724 Value *UnwindDestToken; 725 if (auto *ParentPad = 726 dyn_cast<Instruction>(CatchSwitch->getParentPad())) { 727 // This catchswitch is nested inside another funclet. If that 728 // funclet has an unwind destination within the inlinee, then 729 // unwinding out of this catchswitch would be UB. Rewriting this 730 // catchswitch to unwind to the inlined invoke's unwind dest would 731 // give the parent funclet multiple unwind destinations, which is 732 // something that subsequent EH table generation can't handle and 733 // that the veirifer rejects. So when we see such a call, leave it 734 // as "unwind to caller". 735 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap); 736 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) 737 continue; 738 } else { 739 // This catchswitch has no parent to inherit constraints from, and 740 // none of its descendants can have an unwind edge that exits it and 741 // targets another funclet in the inlinee. It may or may not have a 742 // descendant that definitively has an unwind to caller. In either 743 // case, we'll have to assume that any unwinds out of it may need to 744 // be routed to the caller, so treat it as though it has a definitive 745 // unwind to caller. 746 UnwindDestToken = ConstantTokenNone::get(Caller->getContext()); 747 } 748 auto *NewCatchSwitch = CatchSwitchInst::Create( 749 CatchSwitch->getParentPad(), UnwindDest, 750 CatchSwitch->getNumHandlers(), CatchSwitch->getName(), 751 CatchSwitch); 752 for (BasicBlock *PadBB : CatchSwitch->handlers()) 753 NewCatchSwitch->addHandler(PadBB); 754 // Propagate info for the old catchswitch over to the new one in 755 // the unwind map. This also serves to short-circuit any subsequent 756 // checks for the unwind dest of this catchswitch, which would get 757 // confused if they found the outer handler in the callee. 758 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken; 759 Replacement = NewCatchSwitch; 760 } 761 } else if (!isa<FuncletPadInst>(I)) { 762 llvm_unreachable("unexpected EHPad!"); 763 } 764 765 if (Replacement) { 766 Replacement->takeName(I); 767 I->replaceAllUsesWith(Replacement); 768 I->eraseFromParent(); 769 UpdatePHINodes(&*BB); 770 } 771 } 772 773 if (InlinedCodeInfo.ContainsCalls) 774 for (Function::iterator BB = FirstNewBlock->getIterator(), 775 E = Caller->end(); 776 BB != E; ++BB) 777 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( 778 &*BB, UnwindDest, &FuncletUnwindMap)) 779 // Update any PHI nodes in the exceptional block to indicate that there 780 // is now a new entry in them. 781 UpdatePHINodes(NewBB); 782 783 // Now that everything is happy, we have one final detail. The PHI nodes in 784 // the exception destination block still have entries due to the original 785 // invoke instruction. Eliminate these entries (which might even delete the 786 // PHI node) now. 787 UnwindDest->removePredecessor(InvokeBB); 788 } 789 790 /// When inlining a call site that has !llvm.mem.parallel_loop_access, 791 /// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should 792 /// be propagated to all memory-accessing cloned instructions. 793 static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart, 794 Function::iterator FEnd) { 795 MDNode *MemParallelLoopAccess = 796 CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access); 797 MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group); 798 MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope); 799 MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias); 800 if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias) 801 return; 802 803 for (BasicBlock &BB : make_range(FStart, FEnd)) { 804 for (Instruction &I : BB) { 805 // This metadata is only relevant for instructions that access memory. 806 if (!I.mayReadOrWriteMemory()) 807 continue; 808 809 if (MemParallelLoopAccess) { 810 // TODO: This probably should not overwrite MemParalleLoopAccess. 811 MemParallelLoopAccess = MDNode::concatenate( 812 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access), 813 MemParallelLoopAccess); 814 I.setMetadata(LLVMContext::MD_mem_parallel_loop_access, 815 MemParallelLoopAccess); 816 } 817 818 if (AccessGroup) 819 I.setMetadata(LLVMContext::MD_access_group, uniteAccessGroups( 820 I.getMetadata(LLVMContext::MD_access_group), AccessGroup)); 821 822 if (AliasScope) 823 I.setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate( 824 I.getMetadata(LLVMContext::MD_alias_scope), AliasScope)); 825 826 if (NoAlias) 827 I.setMetadata(LLVMContext::MD_noalias, MDNode::concatenate( 828 I.getMetadata(LLVMContext::MD_noalias), NoAlias)); 829 } 830 } 831 } 832 833 /// Utility for cloning !noalias and !alias.scope metadata. When a code region 834 /// using scoped alias metadata is inlined, the aliasing relationships may not 835 /// hold between the two version. It is necessary to create a deep clone of the 836 /// metadata, putting the two versions in separate scope domains. 837 class ScopedAliasMetadataDeepCloner { 838 using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>; 839 SetVector<const MDNode *> MD; 840 MetadataMap MDMap; 841 void addRecursiveMetadataUses(); 842 843 public: 844 ScopedAliasMetadataDeepCloner(const Function *F); 845 846 /// Create a new clone of the scoped alias metadata, which will be used by 847 /// subsequent remap() calls. 848 void clone(); 849 850 /// Remap instructions in the given range from the original to the cloned 851 /// metadata. 852 void remap(Function::iterator FStart, Function::iterator FEnd); 853 }; 854 855 ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner( 856 const Function *F) { 857 for (const BasicBlock &BB : *F) { 858 for (const Instruction &I : BB) { 859 if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) 860 MD.insert(M); 861 if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) 862 MD.insert(M); 863 864 // We also need to clone the metadata in noalias intrinsics. 865 if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 866 MD.insert(Decl->getScopeList()); 867 } 868 } 869 addRecursiveMetadataUses(); 870 } 871 872 void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() { 873 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end()); 874 while (!Queue.empty()) { 875 const MDNode *M = cast<MDNode>(Queue.pop_back_val()); 876 for (const Metadata *Op : M->operands()) 877 if (const MDNode *OpMD = dyn_cast<MDNode>(Op)) 878 if (MD.insert(OpMD)) 879 Queue.push_back(OpMD); 880 } 881 } 882 883 void ScopedAliasMetadataDeepCloner::clone() { 884 assert(MDMap.empty() && "clone() already called ?"); 885 886 SmallVector<TempMDTuple, 16> DummyNodes; 887 for (const MDNode *I : MD) { 888 DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), None)); 889 MDMap[I].reset(DummyNodes.back().get()); 890 } 891 892 // Create new metadata nodes to replace the dummy nodes, replacing old 893 // metadata references with either a dummy node or an already-created new 894 // node. 895 SmallVector<Metadata *, 4> NewOps; 896 for (const MDNode *I : MD) { 897 for (const Metadata *Op : I->operands()) { 898 if (const MDNode *M = dyn_cast<MDNode>(Op)) 899 NewOps.push_back(MDMap[M]); 900 else 901 NewOps.push_back(const_cast<Metadata *>(Op)); 902 } 903 904 MDNode *NewM = MDNode::get(I->getContext(), NewOps); 905 MDTuple *TempM = cast<MDTuple>(MDMap[I]); 906 assert(TempM->isTemporary() && "Expected temporary node"); 907 908 TempM->replaceAllUsesWith(NewM); 909 NewOps.clear(); 910 } 911 } 912 913 void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart, 914 Function::iterator FEnd) { 915 if (MDMap.empty()) 916 return; // Nothing to do. 917 918 for (BasicBlock &BB : make_range(FStart, FEnd)) { 919 for (Instruction &I : BB) { 920 // TODO: The null checks for the MDMap.lookup() results should no longer 921 // be necessary. 922 if (MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) 923 if (MDNode *MNew = MDMap.lookup(M)) 924 I.setMetadata(LLVMContext::MD_alias_scope, MNew); 925 926 if (MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) 927 if (MDNode *MNew = MDMap.lookup(M)) 928 I.setMetadata(LLVMContext::MD_noalias, MNew); 929 930 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 931 if (MDNode *MNew = MDMap.lookup(Decl->getScopeList())) 932 Decl->setScopeList(MNew); 933 } 934 } 935 } 936 937 /// If the inlined function has noalias arguments, 938 /// then add new alias scopes for each noalias argument, tag the mapped noalias 939 /// parameters with noalias metadata specifying the new scope, and tag all 940 /// non-derived loads, stores and memory intrinsics with the new alias scopes. 941 static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap, 942 const DataLayout &DL, AAResults *CalleeAAR) { 943 if (!EnableNoAliasConversion) 944 return; 945 946 const Function *CalledFunc = CB.getCalledFunction(); 947 SmallVector<const Argument *, 4> NoAliasArgs; 948 949 for (const Argument &Arg : CalledFunc->args()) 950 if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty()) 951 NoAliasArgs.push_back(&Arg); 952 953 if (NoAliasArgs.empty()) 954 return; 955 956 // To do a good job, if a noalias variable is captured, we need to know if 957 // the capture point dominates the particular use we're considering. 958 DominatorTree DT; 959 DT.recalculate(const_cast<Function&>(*CalledFunc)); 960 961 // noalias indicates that pointer values based on the argument do not alias 962 // pointer values which are not based on it. So we add a new "scope" for each 963 // noalias function argument. Accesses using pointers based on that argument 964 // become part of that alias scope, accesses using pointers not based on that 965 // argument are tagged as noalias with that scope. 966 967 DenseMap<const Argument *, MDNode *> NewScopes; 968 MDBuilder MDB(CalledFunc->getContext()); 969 970 // Create a new scope domain for this function. 971 MDNode *NewDomain = 972 MDB.createAnonymousAliasScopeDomain(CalledFunc->getName()); 973 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) { 974 const Argument *A = NoAliasArgs[i]; 975 976 std::string Name = std::string(CalledFunc->getName()); 977 if (A->hasName()) { 978 Name += ": %"; 979 Name += A->getName(); 980 } else { 981 Name += ": argument "; 982 Name += utostr(i); 983 } 984 985 // Note: We always create a new anonymous root here. This is true regardless 986 // of the linkage of the callee because the aliasing "scope" is not just a 987 // property of the callee, but also all control dependencies in the caller. 988 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name); 989 NewScopes.insert(std::make_pair(A, NewScope)); 990 991 if (UseNoAliasIntrinsic) { 992 // Introduce a llvm.experimental.noalias.scope.decl for the noalias 993 // argument. 994 MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope); 995 auto *NoAliasDecl = 996 IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList); 997 // Ignore the result for now. The result will be used when the 998 // llvm.noalias intrinsic is introduced. 999 (void)NoAliasDecl; 1000 } 1001 } 1002 1003 // Iterate over all new instructions in the map; for all memory-access 1004 // instructions, add the alias scope metadata. 1005 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end(); 1006 VMI != VMIE; ++VMI) { 1007 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) { 1008 if (!VMI->second) 1009 continue; 1010 1011 Instruction *NI = dyn_cast<Instruction>(VMI->second); 1012 if (!NI) 1013 continue; 1014 1015 bool IsArgMemOnlyCall = false, IsFuncCall = false; 1016 SmallVector<const Value *, 2> PtrArgs; 1017 1018 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) 1019 PtrArgs.push_back(LI->getPointerOperand()); 1020 else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) 1021 PtrArgs.push_back(SI->getPointerOperand()); 1022 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I)) 1023 PtrArgs.push_back(VAAI->getPointerOperand()); 1024 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I)) 1025 PtrArgs.push_back(CXI->getPointerOperand()); 1026 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) 1027 PtrArgs.push_back(RMWI->getPointerOperand()); 1028 else if (const auto *Call = dyn_cast<CallBase>(I)) { 1029 // If we know that the call does not access memory, then we'll still 1030 // know that about the inlined clone of this call site, and we don't 1031 // need to add metadata. 1032 if (Call->doesNotAccessMemory()) 1033 continue; 1034 1035 IsFuncCall = true; 1036 if (CalleeAAR) { 1037 FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call); 1038 1039 // We'll retain this knowledge without additional metadata. 1040 if (AAResults::onlyAccessesInaccessibleMem(MRB)) 1041 continue; 1042 1043 if (AAResults::onlyAccessesArgPointees(MRB)) 1044 IsArgMemOnlyCall = true; 1045 } 1046 1047 for (Value *Arg : Call->args()) { 1048 // We need to check the underlying objects of all arguments, not just 1049 // the pointer arguments, because we might be passing pointers as 1050 // integers, etc. 1051 // However, if we know that the call only accesses pointer arguments, 1052 // then we only need to check the pointer arguments. 1053 if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy()) 1054 continue; 1055 1056 PtrArgs.push_back(Arg); 1057 } 1058 } 1059 1060 // If we found no pointers, then this instruction is not suitable for 1061 // pairing with an instruction to receive aliasing metadata. 1062 // However, if this is a call, this we might just alias with none of the 1063 // noalias arguments. 1064 if (PtrArgs.empty() && !IsFuncCall) 1065 continue; 1066 1067 // It is possible that there is only one underlying object, but you 1068 // need to go through several PHIs to see it, and thus could be 1069 // repeated in the Objects list. 1070 SmallPtrSet<const Value *, 4> ObjSet; 1071 SmallVector<Metadata *, 4> Scopes, NoAliases; 1072 1073 SmallSetVector<const Argument *, 4> NAPtrArgs; 1074 for (const Value *V : PtrArgs) { 1075 SmallVector<const Value *, 4> Objects; 1076 getUnderlyingObjects(V, Objects, /* LI = */ nullptr); 1077 1078 for (const Value *O : Objects) 1079 ObjSet.insert(O); 1080 } 1081 1082 // Figure out if we're derived from anything that is not a noalias 1083 // argument. 1084 bool CanDeriveViaCapture = false, UsesAliasingPtr = false; 1085 for (const Value *V : ObjSet) { 1086 // Is this value a constant that cannot be derived from any pointer 1087 // value (we need to exclude constant expressions, for example, that 1088 // are formed from arithmetic on global symbols). 1089 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) || 1090 isa<ConstantPointerNull>(V) || 1091 isa<ConstantDataVector>(V) || isa<UndefValue>(V); 1092 if (IsNonPtrConst) 1093 continue; 1094 1095 // If this is anything other than a noalias argument, then we cannot 1096 // completely describe the aliasing properties using alias.scope 1097 // metadata (and, thus, won't add any). 1098 if (const Argument *A = dyn_cast<Argument>(V)) { 1099 if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias)) 1100 UsesAliasingPtr = true; 1101 } else { 1102 UsesAliasingPtr = true; 1103 } 1104 1105 // If this is not some identified function-local object (which cannot 1106 // directly alias a noalias argument), or some other argument (which, 1107 // by definition, also cannot alias a noalias argument), then we could 1108 // alias a noalias argument that has been captured). 1109 if (!isa<Argument>(V) && 1110 !isIdentifiedFunctionLocal(const_cast<Value*>(V))) 1111 CanDeriveViaCapture = true; 1112 } 1113 1114 // A function call can always get captured noalias pointers (via other 1115 // parameters, globals, etc.). 1116 if (IsFuncCall && !IsArgMemOnlyCall) 1117 CanDeriveViaCapture = true; 1118 1119 // First, we want to figure out all of the sets with which we definitely 1120 // don't alias. Iterate over all noalias set, and add those for which: 1121 // 1. The noalias argument is not in the set of objects from which we 1122 // definitely derive. 1123 // 2. The noalias argument has not yet been captured. 1124 // An arbitrary function that might load pointers could see captured 1125 // noalias arguments via other noalias arguments or globals, and so we 1126 // must always check for prior capture. 1127 for (const Argument *A : NoAliasArgs) { 1128 if (!ObjSet.count(A) && (!CanDeriveViaCapture || 1129 // It might be tempting to skip the 1130 // PointerMayBeCapturedBefore check if 1131 // A->hasNoCaptureAttr() is true, but this is 1132 // incorrect because nocapture only guarantees 1133 // that no copies outlive the function, not 1134 // that the value cannot be locally captured. 1135 !PointerMayBeCapturedBefore(A, 1136 /* ReturnCaptures */ false, 1137 /* StoreCaptures */ false, I, &DT))) 1138 NoAliases.push_back(NewScopes[A]); 1139 } 1140 1141 if (!NoAliases.empty()) 1142 NI->setMetadata(LLVMContext::MD_noalias, 1143 MDNode::concatenate( 1144 NI->getMetadata(LLVMContext::MD_noalias), 1145 MDNode::get(CalledFunc->getContext(), NoAliases))); 1146 1147 // Next, we want to figure out all of the sets to which we might belong. 1148 // We might belong to a set if the noalias argument is in the set of 1149 // underlying objects. If there is some non-noalias argument in our list 1150 // of underlying objects, then we cannot add a scope because the fact 1151 // that some access does not alias with any set of our noalias arguments 1152 // cannot itself guarantee that it does not alias with this access 1153 // (because there is some pointer of unknown origin involved and the 1154 // other access might also depend on this pointer). We also cannot add 1155 // scopes to arbitrary functions unless we know they don't access any 1156 // non-parameter pointer-values. 1157 bool CanAddScopes = !UsesAliasingPtr; 1158 if (CanAddScopes && IsFuncCall) 1159 CanAddScopes = IsArgMemOnlyCall; 1160 1161 if (CanAddScopes) 1162 for (const Argument *A : NoAliasArgs) { 1163 if (ObjSet.count(A)) 1164 Scopes.push_back(NewScopes[A]); 1165 } 1166 1167 if (!Scopes.empty()) 1168 NI->setMetadata( 1169 LLVMContext::MD_alias_scope, 1170 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope), 1171 MDNode::get(CalledFunc->getContext(), Scopes))); 1172 } 1173 } 1174 } 1175 1176 static bool MayContainThrowingOrExitingCall(Instruction *Begin, 1177 Instruction *End) { 1178 1179 assert(Begin->getParent() == End->getParent() && 1180 "Expected to be in same basic block!"); 1181 unsigned NumInstChecked = 0; 1182 // Check that all instructions in the range [Begin, End) are guaranteed to 1183 // transfer execution to successor. 1184 for (auto &I : make_range(Begin->getIterator(), End->getIterator())) 1185 if (NumInstChecked++ > InlinerAttributeWindow || 1186 !isGuaranteedToTransferExecutionToSuccessor(&I)) 1187 return true; 1188 return false; 1189 } 1190 1191 static AttrBuilder IdentifyValidAttributes(CallBase &CB) { 1192 1193 AttrBuilder AB(CB.getAttributes(), AttributeList::ReturnIndex); 1194 if (AB.empty()) 1195 return AB; 1196 AttrBuilder Valid; 1197 // Only allow these white listed attributes to be propagated back to the 1198 // callee. This is because other attributes may only be valid on the call 1199 // itself, i.e. attributes such as signext and zeroext. 1200 if (auto DerefBytes = AB.getDereferenceableBytes()) 1201 Valid.addDereferenceableAttr(DerefBytes); 1202 if (auto DerefOrNullBytes = AB.getDereferenceableOrNullBytes()) 1203 Valid.addDereferenceableOrNullAttr(DerefOrNullBytes); 1204 if (AB.contains(Attribute::NoAlias)) 1205 Valid.addAttribute(Attribute::NoAlias); 1206 if (AB.contains(Attribute::NonNull)) 1207 Valid.addAttribute(Attribute::NonNull); 1208 return Valid; 1209 } 1210 1211 static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap) { 1212 if (!UpdateReturnAttributes) 1213 return; 1214 1215 AttrBuilder Valid = IdentifyValidAttributes(CB); 1216 if (Valid.empty()) 1217 return; 1218 auto *CalledFunction = CB.getCalledFunction(); 1219 auto &Context = CalledFunction->getContext(); 1220 1221 for (auto &BB : *CalledFunction) { 1222 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()); 1223 if (!RI || !isa<CallBase>(RI->getOperand(0))) 1224 continue; 1225 auto *RetVal = cast<CallBase>(RI->getOperand(0)); 1226 // Sanity check that the cloned RetVal exists and is a call, otherwise we 1227 // cannot add the attributes on the cloned RetVal. 1228 // Simplification during inlining could have transformed the cloned 1229 // instruction. 1230 auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal)); 1231 if (!NewRetVal) 1232 continue; 1233 // Backward propagation of attributes to the returned value may be incorrect 1234 // if it is control flow dependent. 1235 // Consider: 1236 // @callee { 1237 // %rv = call @foo() 1238 // %rv2 = call @bar() 1239 // if (%rv2 != null) 1240 // return %rv2 1241 // if (%rv == null) 1242 // exit() 1243 // return %rv 1244 // } 1245 // caller() { 1246 // %val = call nonnull @callee() 1247 // } 1248 // Here we cannot add the nonnull attribute on either foo or bar. So, we 1249 // limit the check to both RetVal and RI are in the same basic block and 1250 // there are no throwing/exiting instructions between these instructions. 1251 if (RI->getParent() != RetVal->getParent() || 1252 MayContainThrowingOrExitingCall(RetVal, RI)) 1253 continue; 1254 // Add to the existing attributes of NewRetVal, i.e. the cloned call 1255 // instruction. 1256 // NB! When we have the same attribute already existing on NewRetVal, but 1257 // with a differing value, the AttributeList's merge API honours the already 1258 // existing attribute value (i.e. attributes such as dereferenceable, 1259 // dereferenceable_or_null etc). See AttrBuilder::merge for more details. 1260 AttributeList AL = NewRetVal->getAttributes(); 1261 AttributeList NewAL = 1262 AL.addAttributes(Context, AttributeList::ReturnIndex, Valid); 1263 NewRetVal->setAttributes(NewAL); 1264 } 1265 } 1266 1267 /// If the inlined function has non-byval align arguments, then 1268 /// add @llvm.assume-based alignment assumptions to preserve this information. 1269 static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) { 1270 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache) 1271 return; 1272 1273 AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller()); 1274 auto &DL = CB.getCaller()->getParent()->getDataLayout(); 1275 1276 // To avoid inserting redundant assumptions, we should check for assumptions 1277 // already in the caller. To do this, we might need a DT of the caller. 1278 DominatorTree DT; 1279 bool DTCalculated = false; 1280 1281 Function *CalledFunc = CB.getCalledFunction(); 1282 for (Argument &Arg : CalledFunc->args()) { 1283 unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0; 1284 if (Align && !Arg.hasPassPointeeByValueCopyAttr() && !Arg.hasNUses(0)) { 1285 if (!DTCalculated) { 1286 DT.recalculate(*CB.getCaller()); 1287 DTCalculated = true; 1288 } 1289 1290 // If we can already prove the asserted alignment in the context of the 1291 // caller, then don't bother inserting the assumption. 1292 Value *ArgVal = CB.getArgOperand(Arg.getArgNo()); 1293 if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= Align) 1294 continue; 1295 1296 CallInst *NewAsmp = 1297 IRBuilder<>(&CB).CreateAlignmentAssumption(DL, ArgVal, Align); 1298 AC->registerAssumption(cast<AssumeInst>(NewAsmp)); 1299 } 1300 } 1301 } 1302 1303 /// Once we have cloned code over from a callee into the caller, 1304 /// update the specified callgraph to reflect the changes we made. 1305 /// Note that it's possible that not all code was copied over, so only 1306 /// some edges of the callgraph may remain. 1307 static void UpdateCallGraphAfterInlining(CallBase &CB, 1308 Function::iterator FirstNewBlock, 1309 ValueToValueMapTy &VMap, 1310 InlineFunctionInfo &IFI) { 1311 CallGraph &CG = *IFI.CG; 1312 const Function *Caller = CB.getCaller(); 1313 const Function *Callee = CB.getCalledFunction(); 1314 CallGraphNode *CalleeNode = CG[Callee]; 1315 CallGraphNode *CallerNode = CG[Caller]; 1316 1317 // Since we inlined some uninlined call sites in the callee into the caller, 1318 // add edges from the caller to all of the callees of the callee. 1319 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end(); 1320 1321 // Consider the case where CalleeNode == CallerNode. 1322 CallGraphNode::CalledFunctionsVector CallCache; 1323 if (CalleeNode == CallerNode) { 1324 CallCache.assign(I, E); 1325 I = CallCache.begin(); 1326 E = CallCache.end(); 1327 } 1328 1329 for (; I != E; ++I) { 1330 // Skip 'refererence' call records. 1331 if (!I->first) 1332 continue; 1333 1334 const Value *OrigCall = *I->first; 1335 1336 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall); 1337 // Only copy the edge if the call was inlined! 1338 if (VMI == VMap.end() || VMI->second == nullptr) 1339 continue; 1340 1341 // If the call was inlined, but then constant folded, there is no edge to 1342 // add. Check for this case. 1343 auto *NewCall = dyn_cast<CallBase>(VMI->second); 1344 if (!NewCall) 1345 continue; 1346 1347 // We do not treat intrinsic calls like real function calls because we 1348 // expect them to become inline code; do not add an edge for an intrinsic. 1349 if (NewCall->getCalledFunction() && 1350 NewCall->getCalledFunction()->isIntrinsic()) 1351 continue; 1352 1353 // Remember that this call site got inlined for the client of 1354 // InlineFunction. 1355 IFI.InlinedCalls.push_back(NewCall); 1356 1357 // It's possible that inlining the callsite will cause it to go from an 1358 // indirect to a direct call by resolving a function pointer. If this 1359 // happens, set the callee of the new call site to a more precise 1360 // destination. This can also happen if the call graph node of the caller 1361 // was just unnecessarily imprecise. 1362 if (!I->second->getFunction()) 1363 if (Function *F = NewCall->getCalledFunction()) { 1364 // Indirect call site resolved to direct call. 1365 CallerNode->addCalledFunction(NewCall, CG[F]); 1366 1367 continue; 1368 } 1369 1370 CallerNode->addCalledFunction(NewCall, I->second); 1371 } 1372 1373 // Update the call graph by deleting the edge from Callee to Caller. We must 1374 // do this after the loop above in case Caller and Callee are the same. 1375 CallerNode->removeCallEdgeFor(*cast<CallBase>(&CB)); 1376 } 1377 1378 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M, 1379 BasicBlock *InsertBlock, 1380 InlineFunctionInfo &IFI) { 1381 Type *AggTy = cast<PointerType>(Src->getType())->getElementType(); 1382 IRBuilder<> Builder(InsertBlock, InsertBlock->begin()); 1383 1384 Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy)); 1385 1386 // Always generate a memcpy of alignment 1 here because we don't know 1387 // the alignment of the src pointer. Other optimizations can infer 1388 // better alignment. 1389 Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src, 1390 /*SrcAlign*/ Align(1), Size); 1391 } 1392 1393 /// When inlining a call site that has a byval argument, 1394 /// we have to make the implicit memcpy explicit by adding it. 1395 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall, 1396 const Function *CalledFunc, 1397 InlineFunctionInfo &IFI, 1398 unsigned ByValAlignment) { 1399 PointerType *ArgTy = cast<PointerType>(Arg->getType()); 1400 Type *AggTy = ArgTy->getElementType(); 1401 1402 Function *Caller = TheCall->getFunction(); 1403 const DataLayout &DL = Caller->getParent()->getDataLayout(); 1404 1405 // If the called function is readonly, then it could not mutate the caller's 1406 // copy of the byval'd memory. In this case, it is safe to elide the copy and 1407 // temporary. 1408 if (CalledFunc->onlyReadsMemory()) { 1409 // If the byval argument has a specified alignment that is greater than the 1410 // passed in pointer, then we either have to round up the input pointer or 1411 // give up on this transformation. 1412 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment. 1413 return Arg; 1414 1415 AssumptionCache *AC = 1416 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 1417 1418 // If the pointer is already known to be sufficiently aligned, or if we can 1419 // round it up to a larger alignment, then we don't need a temporary. 1420 if (getOrEnforceKnownAlignment(Arg, Align(ByValAlignment), DL, TheCall, 1421 AC) >= ByValAlignment) 1422 return Arg; 1423 1424 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad 1425 // for code quality, but rarely happens and is required for correctness. 1426 } 1427 1428 // Create the alloca. If we have DataLayout, use nice alignment. 1429 Align Alignment(DL.getPrefTypeAlignment(AggTy)); 1430 1431 // If the byval had an alignment specified, we *must* use at least that 1432 // alignment, as it is required by the byval argument (and uses of the 1433 // pointer inside the callee). 1434 Alignment = max(Alignment, MaybeAlign(ByValAlignment)); 1435 1436 Value *NewAlloca = 1437 new AllocaInst(AggTy, DL.getAllocaAddrSpace(), nullptr, Alignment, 1438 Arg->getName(), &*Caller->begin()->begin()); 1439 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca)); 1440 1441 // Uses of the argument in the function should use our new alloca 1442 // instead. 1443 return NewAlloca; 1444 } 1445 1446 // Check whether this Value is used by a lifetime intrinsic. 1447 static bool isUsedByLifetimeMarker(Value *V) { 1448 for (User *U : V->users()) 1449 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) 1450 if (II->isLifetimeStartOrEnd()) 1451 return true; 1452 return false; 1453 } 1454 1455 // Check whether the given alloca already has 1456 // lifetime.start or lifetime.end intrinsics. 1457 static bool hasLifetimeMarkers(AllocaInst *AI) { 1458 Type *Ty = AI->getType(); 1459 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(), 1460 Ty->getPointerAddressSpace()); 1461 if (Ty == Int8PtrTy) 1462 return isUsedByLifetimeMarker(AI); 1463 1464 // Do a scan to find all the casts to i8*. 1465 for (User *U : AI->users()) { 1466 if (U->getType() != Int8PtrTy) continue; 1467 if (U->stripPointerCasts() != AI) continue; 1468 if (isUsedByLifetimeMarker(U)) 1469 return true; 1470 } 1471 return false; 1472 } 1473 1474 /// Return the result of AI->isStaticAlloca() if AI were moved to the entry 1475 /// block. Allocas used in inalloca calls and allocas of dynamic array size 1476 /// cannot be static. 1477 static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) { 1478 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca(); 1479 } 1480 1481 /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL 1482 /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache. 1483 static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt, 1484 LLVMContext &Ctx, 1485 DenseMap<const MDNode *, MDNode *> &IANodes) { 1486 auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes); 1487 return DILocation::get(Ctx, OrigDL.getLine(), OrigDL.getCol(), 1488 OrigDL.getScope(), IA); 1489 } 1490 1491 /// Update inlined instructions' line numbers to 1492 /// to encode location where these instructions are inlined. 1493 static void fixupLineNumbers(Function *Fn, Function::iterator FI, 1494 Instruction *TheCall, bool CalleeHasDebugInfo) { 1495 const DebugLoc &TheCallDL = TheCall->getDebugLoc(); 1496 if (!TheCallDL) 1497 return; 1498 1499 auto &Ctx = Fn->getContext(); 1500 DILocation *InlinedAtNode = TheCallDL; 1501 1502 // Create a unique call site, not to be confused with any other call from the 1503 // same location. 1504 InlinedAtNode = DILocation::getDistinct( 1505 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(), 1506 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt()); 1507 1508 // Cache the inlined-at nodes as they're built so they are reused, without 1509 // this every instruction's inlined-at chain would become distinct from each 1510 // other. 1511 DenseMap<const MDNode *, MDNode *> IANodes; 1512 1513 // Check if we are not generating inline line tables and want to use 1514 // the call site location instead. 1515 bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables"); 1516 1517 for (; FI != Fn->end(); ++FI) { 1518 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); 1519 BI != BE; ++BI) { 1520 // Loop metadata needs to be updated so that the start and end locs 1521 // reference inlined-at locations. 1522 auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes]( 1523 const DILocation &Loc) -> DILocation * { 1524 return inlineDebugLoc(&Loc, InlinedAtNode, Ctx, IANodes).get(); 1525 }; 1526 updateLoopMetadataDebugLocations(*BI, updateLoopInfoLoc); 1527 1528 if (!NoInlineLineTables) 1529 if (DebugLoc DL = BI->getDebugLoc()) { 1530 DebugLoc IDL = 1531 inlineDebugLoc(DL, InlinedAtNode, BI->getContext(), IANodes); 1532 BI->setDebugLoc(IDL); 1533 continue; 1534 } 1535 1536 if (CalleeHasDebugInfo && !NoInlineLineTables) 1537 continue; 1538 1539 // If the inlined instruction has no line number, or if inline info 1540 // is not being generated, make it look as if it originates from the call 1541 // location. This is important for ((__always_inline, __nodebug__)) 1542 // functions which must use caller location for all instructions in their 1543 // function body. 1544 1545 // Don't update static allocas, as they may get moved later. 1546 if (auto *AI = dyn_cast<AllocaInst>(BI)) 1547 if (allocaWouldBeStaticInEntry(AI)) 1548 continue; 1549 1550 BI->setDebugLoc(TheCallDL); 1551 } 1552 1553 // Remove debug info intrinsics if we're not keeping inline info. 1554 if (NoInlineLineTables) { 1555 BasicBlock::iterator BI = FI->begin(); 1556 while (BI != FI->end()) { 1557 if (isa<DbgInfoIntrinsic>(BI)) { 1558 BI = BI->eraseFromParent(); 1559 continue; 1560 } 1561 ++BI; 1562 } 1563 } 1564 1565 } 1566 } 1567 1568 /// Update the block frequencies of the caller after a callee has been inlined. 1569 /// 1570 /// Each block cloned into the caller has its block frequency scaled by the 1571 /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of 1572 /// callee's entry block gets the same frequency as the callsite block and the 1573 /// relative frequencies of all cloned blocks remain the same after cloning. 1574 static void updateCallerBFI(BasicBlock *CallSiteBlock, 1575 const ValueToValueMapTy &VMap, 1576 BlockFrequencyInfo *CallerBFI, 1577 BlockFrequencyInfo *CalleeBFI, 1578 const BasicBlock &CalleeEntryBlock) { 1579 SmallPtrSet<BasicBlock *, 16> ClonedBBs; 1580 for (auto Entry : VMap) { 1581 if (!isa<BasicBlock>(Entry.first) || !Entry.second) 1582 continue; 1583 auto *OrigBB = cast<BasicBlock>(Entry.first); 1584 auto *ClonedBB = cast<BasicBlock>(Entry.second); 1585 uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency(); 1586 if (!ClonedBBs.insert(ClonedBB).second) { 1587 // Multiple blocks in the callee might get mapped to one cloned block in 1588 // the caller since we prune the callee as we clone it. When that happens, 1589 // we want to use the maximum among the original blocks' frequencies. 1590 uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency(); 1591 if (NewFreq > Freq) 1592 Freq = NewFreq; 1593 } 1594 CallerBFI->setBlockFreq(ClonedBB, Freq); 1595 } 1596 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock)); 1597 CallerBFI->setBlockFreqAndScale( 1598 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(), 1599 ClonedBBs); 1600 } 1601 1602 /// Update the branch metadata for cloned call instructions. 1603 static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap, 1604 const ProfileCount &CalleeEntryCount, 1605 const CallBase &TheCall, ProfileSummaryInfo *PSI, 1606 BlockFrequencyInfo *CallerBFI) { 1607 if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() || 1608 CalleeEntryCount.getCount() < 1) 1609 return; 1610 auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None; 1611 int64_t CallCount = 1612 std::min(CallSiteCount.getValueOr(0), CalleeEntryCount.getCount()); 1613 updateProfileCallee(Callee, -CallCount, &VMap); 1614 } 1615 1616 void llvm::updateProfileCallee( 1617 Function *Callee, int64_t entryDelta, 1618 const ValueMap<const Value *, WeakTrackingVH> *VMap) { 1619 auto CalleeCount = Callee->getEntryCount(); 1620 if (!CalleeCount.hasValue()) 1621 return; 1622 1623 uint64_t priorEntryCount = CalleeCount.getCount(); 1624 uint64_t newEntryCount; 1625 1626 // Since CallSiteCount is an estimate, it could exceed the original callee 1627 // count and has to be set to 0 so guard against underflow. 1628 if (entryDelta < 0 && static_cast<uint64_t>(-entryDelta) > priorEntryCount) 1629 newEntryCount = 0; 1630 else 1631 newEntryCount = priorEntryCount + entryDelta; 1632 1633 // During inlining ? 1634 if (VMap) { 1635 uint64_t cloneEntryCount = priorEntryCount - newEntryCount; 1636 for (auto Entry : *VMap) 1637 if (isa<CallInst>(Entry.first)) 1638 if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second)) 1639 CI->updateProfWeight(cloneEntryCount, priorEntryCount); 1640 } 1641 1642 if (entryDelta) { 1643 Callee->setEntryCount(newEntryCount); 1644 1645 for (BasicBlock &BB : *Callee) 1646 // No need to update the callsite if it is pruned during inlining. 1647 if (!VMap || VMap->count(&BB)) 1648 for (Instruction &I : BB) 1649 if (CallInst *CI = dyn_cast<CallInst>(&I)) 1650 CI->updateProfWeight(newEntryCount, priorEntryCount); 1651 } 1652 } 1653 1654 /// An operand bundle "clang.arc.attachedcall" on a call indicates the call 1655 /// result is implicitly consumed by a call to retainRV or claimRV immediately 1656 /// after the call. This function inlines the retainRV/claimRV calls. 1657 /// 1658 /// There are three cases to consider: 1659 /// 1660 /// 1. If there is a call to autoreleaseRV that takes a pointer to the returned 1661 /// object in the callee return block, the autoreleaseRV call and the 1662 /// retainRV/claimRV call in the caller cancel out. If the call in the caller 1663 /// is a claimRV call, a call to objc_release is emitted. 1664 /// 1665 /// 2. If there is a call in the callee return block that doesn't have operand 1666 /// bundle "clang.arc.attachedcall", the operand bundle on the original call 1667 /// is transferred to the call in the callee. 1668 /// 1669 /// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is 1670 /// a retainRV call. 1671 static void 1672 inlineRetainOrClaimRVCalls(CallBase &CB, 1673 const SmallVectorImpl<ReturnInst *> &Returns) { 1674 Module *Mod = CB.getModule(); 1675 bool IsRetainRV = objcarc::hasAttachedCallOpBundle(&CB, true), 1676 IsClaimRV = !IsRetainRV; 1677 1678 for (auto *RI : Returns) { 1679 Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0)); 1680 BasicBlock::reverse_iterator I = ++(RI->getIterator().getReverse()); 1681 BasicBlock::reverse_iterator EI = RI->getParent()->rend(); 1682 bool InsertRetainCall = IsRetainRV; 1683 IRBuilder<> Builder(RI->getContext()); 1684 1685 // Walk backwards through the basic block looking for either a matching 1686 // autoreleaseRV call or an unannotated call. 1687 for (; I != EI;) { 1688 auto CurI = I++; 1689 1690 // Ignore casts. 1691 if (isa<CastInst>(*CurI)) 1692 continue; 1693 1694 if (auto *II = dyn_cast<IntrinsicInst>(&*CurI)) { 1695 if (II->getIntrinsicID() == Intrinsic::objc_autoreleaseReturnValue && 1696 II->hasNUses(0) && 1697 objcarc::GetRCIdentityRoot(II->getOperand(0)) == RetOpnd) { 1698 // If we've found a matching authoreleaseRV call: 1699 // - If claimRV is attached to the call, insert a call to objc_release 1700 // and erase the autoreleaseRV call. 1701 // - If retainRV is attached to the call, just erase the autoreleaseRV 1702 // call. 1703 if (IsClaimRV) { 1704 Builder.SetInsertPoint(II); 1705 Function *IFn = 1706 Intrinsic::getDeclaration(Mod, Intrinsic::objc_release); 1707 Value *BC = 1708 Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType()); 1709 Builder.CreateCall(IFn, BC, ""); 1710 } 1711 II->eraseFromParent(); 1712 InsertRetainCall = false; 1713 } 1714 } else if (auto *CI = dyn_cast<CallInst>(&*CurI)) { 1715 if (objcarc::GetRCIdentityRoot(CI) == RetOpnd && 1716 !objcarc::hasAttachedCallOpBundle(CI)) { 1717 // If we've found an unannotated call that defines RetOpnd, add a 1718 // "clang.arc.attachedcall" operand bundle. 1719 Value *BundleArgs[] = {ConstantInt::get( 1720 Builder.getInt64Ty(), 1721 objcarc::getAttachedCallOperandBundleEnum(IsRetainRV))}; 1722 OperandBundleDef OB("clang.arc.attachedcall", BundleArgs); 1723 auto *NewCall = CallBase::addOperandBundle( 1724 CI, LLVMContext::OB_clang_arc_attachedcall, OB, CI); 1725 NewCall->copyMetadata(*CI); 1726 CI->replaceAllUsesWith(NewCall); 1727 CI->eraseFromParent(); 1728 InsertRetainCall = false; 1729 } 1730 } 1731 1732 break; 1733 } 1734 1735 if (InsertRetainCall) { 1736 // The retainRV is attached to the call and we've failed to find a 1737 // matching autoreleaseRV or an annotated call in the callee. Emit a call 1738 // to objc_retain. 1739 Builder.SetInsertPoint(RI); 1740 Function *IFn = Intrinsic::getDeclaration(Mod, Intrinsic::objc_retain); 1741 Value *BC = Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType()); 1742 Builder.CreateCall(IFn, BC, ""); 1743 } 1744 } 1745 } 1746 1747 /// This function inlines the called function into the basic block of the 1748 /// caller. This returns false if it is not possible to inline this call. 1749 /// The program is still in a well defined state if this occurs though. 1750 /// 1751 /// Note that this only does one level of inlining. For example, if the 1752 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now 1753 /// exists in the instruction stream. Similarly this will inline a recursive 1754 /// function by one level. 1755 llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, 1756 AAResults *CalleeAAR, 1757 bool InsertLifetime, 1758 Function *ForwardVarArgsTo) { 1759 assert(CB.getParent() && CB.getFunction() && "Instruction not in function!"); 1760 1761 // FIXME: we don't inline callbr yet. 1762 if (isa<CallBrInst>(CB)) 1763 return InlineResult::failure("We don't inline callbr yet."); 1764 1765 // If IFI has any state in it, zap it before we fill it in. 1766 IFI.reset(); 1767 1768 Function *CalledFunc = CB.getCalledFunction(); 1769 if (!CalledFunc || // Can't inline external function or indirect 1770 CalledFunc->isDeclaration()) // call! 1771 return InlineResult::failure("external or indirect"); 1772 1773 // The inliner does not know how to inline through calls with operand bundles 1774 // in general ... 1775 if (CB.hasOperandBundles()) { 1776 for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) { 1777 uint32_t Tag = CB.getOperandBundleAt(i).getTagID(); 1778 // ... but it knows how to inline through "deopt" operand bundles ... 1779 if (Tag == LLVMContext::OB_deopt) 1780 continue; 1781 // ... and "funclet" operand bundles. 1782 if (Tag == LLVMContext::OB_funclet) 1783 continue; 1784 if (Tag == LLVMContext::OB_clang_arc_attachedcall) 1785 continue; 1786 1787 return InlineResult::failure("unsupported operand bundle"); 1788 } 1789 } 1790 1791 // If the call to the callee cannot throw, set the 'nounwind' flag on any 1792 // calls that we inline. 1793 bool MarkNoUnwind = CB.doesNotThrow(); 1794 1795 BasicBlock *OrigBB = CB.getParent(); 1796 Function *Caller = OrigBB->getParent(); 1797 1798 // GC poses two hazards to inlining, which only occur when the callee has GC: 1799 // 1. If the caller has no GC, then the callee's GC must be propagated to the 1800 // caller. 1801 // 2. If the caller has a differing GC, it is invalid to inline. 1802 if (CalledFunc->hasGC()) { 1803 if (!Caller->hasGC()) 1804 Caller->setGC(CalledFunc->getGC()); 1805 else if (CalledFunc->getGC() != Caller->getGC()) 1806 return InlineResult::failure("incompatible GC"); 1807 } 1808 1809 // Get the personality function from the callee if it contains a landing pad. 1810 Constant *CalledPersonality = 1811 CalledFunc->hasPersonalityFn() 1812 ? CalledFunc->getPersonalityFn()->stripPointerCasts() 1813 : nullptr; 1814 1815 // Find the personality function used by the landing pads of the caller. If it 1816 // exists, then check to see that it matches the personality function used in 1817 // the callee. 1818 Constant *CallerPersonality = 1819 Caller->hasPersonalityFn() 1820 ? Caller->getPersonalityFn()->stripPointerCasts() 1821 : nullptr; 1822 if (CalledPersonality) { 1823 if (!CallerPersonality) 1824 Caller->setPersonalityFn(CalledPersonality); 1825 // If the personality functions match, then we can perform the 1826 // inlining. Otherwise, we can't inline. 1827 // TODO: This isn't 100% true. Some personality functions are proper 1828 // supersets of others and can be used in place of the other. 1829 else if (CalledPersonality != CallerPersonality) 1830 return InlineResult::failure("incompatible personality"); 1831 } 1832 1833 // We need to figure out which funclet the callsite was in so that we may 1834 // properly nest the callee. 1835 Instruction *CallSiteEHPad = nullptr; 1836 if (CallerPersonality) { 1837 EHPersonality Personality = classifyEHPersonality(CallerPersonality); 1838 if (isScopedEHPersonality(Personality)) { 1839 Optional<OperandBundleUse> ParentFunclet = 1840 CB.getOperandBundle(LLVMContext::OB_funclet); 1841 if (ParentFunclet) 1842 CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front()); 1843 1844 // OK, the inlining site is legal. What about the target function? 1845 1846 if (CallSiteEHPad) { 1847 if (Personality == EHPersonality::MSVC_CXX) { 1848 // The MSVC personality cannot tolerate catches getting inlined into 1849 // cleanup funclets. 1850 if (isa<CleanupPadInst>(CallSiteEHPad)) { 1851 // Ok, the call site is within a cleanuppad. Let's check the callee 1852 // for catchpads. 1853 for (const BasicBlock &CalledBB : *CalledFunc) { 1854 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI())) 1855 return InlineResult::failure("catch in cleanup funclet"); 1856 } 1857 } 1858 } else if (isAsynchronousEHPersonality(Personality)) { 1859 // SEH is even less tolerant, there may not be any sort of exceptional 1860 // funclet in the callee. 1861 for (const BasicBlock &CalledBB : *CalledFunc) { 1862 if (CalledBB.isEHPad()) 1863 return InlineResult::failure("SEH in cleanup funclet"); 1864 } 1865 } 1866 } 1867 } 1868 } 1869 1870 // Determine if we are dealing with a call in an EHPad which does not unwind 1871 // to caller. 1872 bool EHPadForCallUnwindsLocally = false; 1873 if (CallSiteEHPad && isa<CallInst>(CB)) { 1874 UnwindDestMemoTy FuncletUnwindMap; 1875 Value *CallSiteUnwindDestToken = 1876 getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap); 1877 1878 EHPadForCallUnwindsLocally = 1879 CallSiteUnwindDestToken && 1880 !isa<ConstantTokenNone>(CallSiteUnwindDestToken); 1881 } 1882 1883 // Get an iterator to the last basic block in the function, which will have 1884 // the new function inlined after it. 1885 Function::iterator LastBlock = --Caller->end(); 1886 1887 // Make sure to capture all of the return instructions from the cloned 1888 // function. 1889 SmallVector<ReturnInst*, 8> Returns; 1890 ClonedCodeInfo InlinedFunctionInfo; 1891 Function::iterator FirstNewBlock; 1892 1893 { // Scope to destroy VMap after cloning. 1894 ValueToValueMapTy VMap; 1895 // Keep a list of pair (dst, src) to emit byval initializations. 1896 SmallVector<std::pair<Value*, Value*>, 4> ByValInit; 1897 1898 // When inlining a function that contains noalias scope metadata, 1899 // this metadata needs to be cloned so that the inlined blocks 1900 // have different "unique scopes" at every call site. 1901 // Track the metadata that must be cloned. Do this before other changes to 1902 // the function, so that we do not get in trouble when inlining caller == 1903 // callee. 1904 ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction()); 1905 1906 auto &DL = Caller->getParent()->getDataLayout(); 1907 1908 // Calculate the vector of arguments to pass into the function cloner, which 1909 // matches up the formal to the actual argument values. 1910 auto AI = CB.arg_begin(); 1911 unsigned ArgNo = 0; 1912 for (Function::arg_iterator I = CalledFunc->arg_begin(), 1913 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) { 1914 Value *ActualArg = *AI; 1915 1916 // When byval arguments actually inlined, we need to make the copy implied 1917 // by them explicit. However, we don't do this if the callee is readonly 1918 // or readnone, because the copy would be unneeded: the callee doesn't 1919 // modify the struct. 1920 if (CB.isByValArgument(ArgNo)) { 1921 ActualArg = HandleByValArgument(ActualArg, &CB, CalledFunc, IFI, 1922 CalledFunc->getParamAlignment(ArgNo)); 1923 if (ActualArg != *AI) 1924 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI)); 1925 } 1926 1927 VMap[&*I] = ActualArg; 1928 } 1929 1930 // TODO: Remove this when users have been updated to the assume bundles. 1931 // Add alignment assumptions if necessary. We do this before the inlined 1932 // instructions are actually cloned into the caller so that we can easily 1933 // check what will be known at the start of the inlined code. 1934 AddAlignmentAssumptions(CB, IFI); 1935 1936 AssumptionCache *AC = 1937 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 1938 1939 /// Preserve all attributes on of the call and its parameters. 1940 salvageKnowledge(&CB, AC); 1941 1942 // We want the inliner to prune the code as it copies. We would LOVE to 1943 // have no dead or constant instructions leftover after inlining occurs 1944 // (which can happen, e.g., because an argument was constant), but we'll be 1945 // happy with whatever the cloner can do. 1946 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, 1947 /*ModuleLevelChanges=*/false, Returns, ".i", 1948 &InlinedFunctionInfo, &CB); 1949 // Remember the first block that is newly cloned over. 1950 FirstNewBlock = LastBlock; ++FirstNewBlock; 1951 1952 // Insert retainRV/clainRV runtime calls. 1953 if (objcarc::hasAttachedCallOpBundle(&CB)) 1954 inlineRetainOrClaimRVCalls(CB, Returns); 1955 1956 // Updated caller/callee profiles only when requested. For sample loader 1957 // inlining, the context-sensitive inlinee profile doesn't need to be 1958 // subtracted from callee profile, and the inlined clone also doesn't need 1959 // to be scaled based on call site count. 1960 if (IFI.UpdateProfile) { 1961 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr) 1962 // Update the BFI of blocks cloned into the caller. 1963 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI, 1964 CalledFunc->front()); 1965 1966 updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), CB, 1967 IFI.PSI, IFI.CallerBFI); 1968 } 1969 1970 // Inject byval arguments initialization. 1971 for (std::pair<Value*, Value*> &Init : ByValInit) 1972 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(), 1973 &*FirstNewBlock, IFI); 1974 1975 Optional<OperandBundleUse> ParentDeopt = 1976 CB.getOperandBundle(LLVMContext::OB_deopt); 1977 if (ParentDeopt) { 1978 SmallVector<OperandBundleDef, 2> OpDefs; 1979 1980 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) { 1981 CallBase *ICS = dyn_cast_or_null<CallBase>(VH); 1982 if (!ICS) 1983 continue; // instruction was DCE'd or RAUW'ed to undef 1984 1985 OpDefs.clear(); 1986 1987 OpDefs.reserve(ICS->getNumOperandBundles()); 1988 1989 for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe; 1990 ++COBi) { 1991 auto ChildOB = ICS->getOperandBundleAt(COBi); 1992 if (ChildOB.getTagID() != LLVMContext::OB_deopt) { 1993 // If the inlined call has other operand bundles, let them be 1994 OpDefs.emplace_back(ChildOB); 1995 continue; 1996 } 1997 1998 // It may be useful to separate this logic (of handling operand 1999 // bundles) out to a separate "policy" component if this gets crowded. 2000 // Prepend the parent's deoptimization continuation to the newly 2001 // inlined call's deoptimization continuation. 2002 std::vector<Value *> MergedDeoptArgs; 2003 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() + 2004 ChildOB.Inputs.size()); 2005 2006 llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs); 2007 llvm::append_range(MergedDeoptArgs, ChildOB.Inputs); 2008 2009 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs)); 2010 } 2011 2012 Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS); 2013 2014 // Note: the RAUW does the appropriate fixup in VMap, so we need to do 2015 // this even if the call returns void. 2016 ICS->replaceAllUsesWith(NewI); 2017 2018 VH = nullptr; 2019 ICS->eraseFromParent(); 2020 } 2021 } 2022 2023 // Update the callgraph if requested. 2024 if (IFI.CG) 2025 UpdateCallGraphAfterInlining(CB, FirstNewBlock, VMap, IFI); 2026 2027 // For 'nodebug' functions, the associated DISubprogram is always null. 2028 // Conservatively avoid propagating the callsite debug location to 2029 // instructions inlined from a function whose DISubprogram is not null. 2030 fixupLineNumbers(Caller, FirstNewBlock, &CB, 2031 CalledFunc->getSubprogram() != nullptr); 2032 2033 // Now clone the inlined noalias scope metadata. 2034 SAMetadataCloner.clone(); 2035 SAMetadataCloner.remap(FirstNewBlock, Caller->end()); 2036 2037 // Add noalias metadata if necessary. 2038 AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR); 2039 2040 // Clone return attributes on the callsite into the calls within the inlined 2041 // function which feed into its return value. 2042 AddReturnAttributes(CB, VMap); 2043 2044 // Propagate metadata on the callsite if necessary. 2045 PropagateCallSiteMetadata(CB, FirstNewBlock, Caller->end()); 2046 2047 // Register any cloned assumptions. 2048 if (IFI.GetAssumptionCache) 2049 for (BasicBlock &NewBlock : 2050 make_range(FirstNewBlock->getIterator(), Caller->end())) 2051 for (Instruction &I : NewBlock) 2052 if (auto *II = dyn_cast<AssumeInst>(&I)) 2053 IFI.GetAssumptionCache(*Caller).registerAssumption(II); 2054 } 2055 2056 // If there are any alloca instructions in the block that used to be the entry 2057 // block for the callee, move them to the entry block of the caller. First 2058 // calculate which instruction they should be inserted before. We insert the 2059 // instructions at the end of the current alloca list. 2060 { 2061 BasicBlock::iterator InsertPoint = Caller->begin()->begin(); 2062 for (BasicBlock::iterator I = FirstNewBlock->begin(), 2063 E = FirstNewBlock->end(); I != E; ) { 2064 AllocaInst *AI = dyn_cast<AllocaInst>(I++); 2065 if (!AI) continue; 2066 2067 // If the alloca is now dead, remove it. This often occurs due to code 2068 // specialization. 2069 if (AI->use_empty()) { 2070 AI->eraseFromParent(); 2071 continue; 2072 } 2073 2074 if (!allocaWouldBeStaticInEntry(AI)) 2075 continue; 2076 2077 // Keep track of the static allocas that we inline into the caller. 2078 IFI.StaticAllocas.push_back(AI); 2079 2080 // Scan for the block of allocas that we can move over, and move them 2081 // all at once. 2082 while (isa<AllocaInst>(I) && 2083 !cast<AllocaInst>(I)->use_empty() && 2084 allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) { 2085 IFI.StaticAllocas.push_back(cast<AllocaInst>(I)); 2086 ++I; 2087 } 2088 2089 // Transfer all of the allocas over in a block. Using splice means 2090 // that the instructions aren't removed from the symbol table, then 2091 // reinserted. 2092 Caller->getEntryBlock().getInstList().splice( 2093 InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I); 2094 } 2095 } 2096 2097 SmallVector<Value*,4> VarArgsToForward; 2098 SmallVector<AttributeSet, 4> VarArgsAttrs; 2099 for (unsigned i = CalledFunc->getFunctionType()->getNumParams(); 2100 i < CB.getNumArgOperands(); i++) { 2101 VarArgsToForward.push_back(CB.getArgOperand(i)); 2102 VarArgsAttrs.push_back(CB.getAttributes().getParamAttributes(i)); 2103 } 2104 2105 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false; 2106 if (InlinedFunctionInfo.ContainsCalls) { 2107 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None; 2108 if (CallInst *CI = dyn_cast<CallInst>(&CB)) 2109 CallSiteTailKind = CI->getTailCallKind(); 2110 2111 // For inlining purposes, the "notail" marker is the same as no marker. 2112 if (CallSiteTailKind == CallInst::TCK_NoTail) 2113 CallSiteTailKind = CallInst::TCK_None; 2114 2115 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; 2116 ++BB) { 2117 for (auto II = BB->begin(); II != BB->end();) { 2118 Instruction &I = *II++; 2119 CallInst *CI = dyn_cast<CallInst>(&I); 2120 if (!CI) 2121 continue; 2122 2123 // Forward varargs from inlined call site to calls to the 2124 // ForwardVarArgsTo function, if requested, and to musttail calls. 2125 if (!VarArgsToForward.empty() && 2126 ((ForwardVarArgsTo && 2127 CI->getCalledFunction() == ForwardVarArgsTo) || 2128 CI->isMustTailCall())) { 2129 // Collect attributes for non-vararg parameters. 2130 AttributeList Attrs = CI->getAttributes(); 2131 SmallVector<AttributeSet, 8> ArgAttrs; 2132 if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) { 2133 for (unsigned ArgNo = 0; 2134 ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo) 2135 ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo)); 2136 } 2137 2138 // Add VarArg attributes. 2139 ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end()); 2140 Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(), 2141 Attrs.getRetAttributes(), ArgAttrs); 2142 // Add VarArgs to existing parameters. 2143 SmallVector<Value *, 6> Params(CI->arg_operands()); 2144 Params.append(VarArgsToForward.begin(), VarArgsToForward.end()); 2145 CallInst *NewCI = CallInst::Create( 2146 CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI); 2147 NewCI->setDebugLoc(CI->getDebugLoc()); 2148 NewCI->setAttributes(Attrs); 2149 NewCI->setCallingConv(CI->getCallingConv()); 2150 CI->replaceAllUsesWith(NewCI); 2151 CI->eraseFromParent(); 2152 CI = NewCI; 2153 } 2154 2155 if (Function *F = CI->getCalledFunction()) 2156 InlinedDeoptimizeCalls |= 2157 F->getIntrinsicID() == Intrinsic::experimental_deoptimize; 2158 2159 // We need to reduce the strength of any inlined tail calls. For 2160 // musttail, we have to avoid introducing potential unbounded stack 2161 // growth. For example, if functions 'f' and 'g' are mutually recursive 2162 // with musttail, we can inline 'g' into 'f' so long as we preserve 2163 // musttail on the cloned call to 'f'. If either the inlined call site 2164 // or the cloned call site is *not* musttail, the program already has 2165 // one frame of stack growth, so it's safe to remove musttail. Here is 2166 // a table of example transformations: 2167 // 2168 // f -> musttail g -> musttail f ==> f -> musttail f 2169 // f -> musttail g -> tail f ==> f -> tail f 2170 // f -> g -> musttail f ==> f -> f 2171 // f -> g -> tail f ==> f -> f 2172 // 2173 // Inlined notail calls should remain notail calls. 2174 CallInst::TailCallKind ChildTCK = CI->getTailCallKind(); 2175 if (ChildTCK != CallInst::TCK_NoTail) 2176 ChildTCK = std::min(CallSiteTailKind, ChildTCK); 2177 CI->setTailCallKind(ChildTCK); 2178 InlinedMustTailCalls |= CI->isMustTailCall(); 2179 2180 // Calls inlined through a 'nounwind' call site should be marked 2181 // 'nounwind'. 2182 if (MarkNoUnwind) 2183 CI->setDoesNotThrow(); 2184 } 2185 } 2186 } 2187 2188 // Leave lifetime markers for the static alloca's, scoping them to the 2189 // function we just inlined. 2190 if (InsertLifetime && !IFI.StaticAllocas.empty()) { 2191 IRBuilder<> builder(&FirstNewBlock->front()); 2192 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) { 2193 AllocaInst *AI = IFI.StaticAllocas[ai]; 2194 // Don't mark swifterror allocas. They can't have bitcast uses. 2195 if (AI->isSwiftError()) 2196 continue; 2197 2198 // If the alloca is already scoped to something smaller than the whole 2199 // function then there's no need to add redundant, less accurate markers. 2200 if (hasLifetimeMarkers(AI)) 2201 continue; 2202 2203 // Try to determine the size of the allocation. 2204 ConstantInt *AllocaSize = nullptr; 2205 if (ConstantInt *AIArraySize = 2206 dyn_cast<ConstantInt>(AI->getArraySize())) { 2207 auto &DL = Caller->getParent()->getDataLayout(); 2208 Type *AllocaType = AI->getAllocatedType(); 2209 TypeSize AllocaTypeSize = DL.getTypeAllocSize(AllocaType); 2210 uint64_t AllocaArraySize = AIArraySize->getLimitedValue(); 2211 2212 // Don't add markers for zero-sized allocas. 2213 if (AllocaArraySize == 0) 2214 continue; 2215 2216 // Check that array size doesn't saturate uint64_t and doesn't 2217 // overflow when it's multiplied by type size. 2218 if (!AllocaTypeSize.isScalable() && 2219 AllocaArraySize != std::numeric_limits<uint64_t>::max() && 2220 std::numeric_limits<uint64_t>::max() / AllocaArraySize >= 2221 AllocaTypeSize.getFixedSize()) { 2222 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()), 2223 AllocaArraySize * AllocaTypeSize); 2224 } 2225 } 2226 2227 builder.CreateLifetimeStart(AI, AllocaSize); 2228 for (ReturnInst *RI : Returns) { 2229 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize 2230 // call and a return. The return kills all local allocas. 2231 if (InlinedMustTailCalls && 2232 RI->getParent()->getTerminatingMustTailCall()) 2233 continue; 2234 if (InlinedDeoptimizeCalls && 2235 RI->getParent()->getTerminatingDeoptimizeCall()) 2236 continue; 2237 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize); 2238 } 2239 } 2240 } 2241 2242 // If the inlined code contained dynamic alloca instructions, wrap the inlined 2243 // code with llvm.stacksave/llvm.stackrestore intrinsics. 2244 if (InlinedFunctionInfo.ContainsDynamicAllocas) { 2245 Module *M = Caller->getParent(); 2246 // Get the two intrinsics we care about. 2247 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave); 2248 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore); 2249 2250 // Insert the llvm.stacksave. 2251 CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin()) 2252 .CreateCall(StackSave, {}, "savedstack"); 2253 2254 // Insert a call to llvm.stackrestore before any return instructions in the 2255 // inlined function. 2256 for (ReturnInst *RI : Returns) { 2257 // Don't insert llvm.stackrestore calls between a musttail or deoptimize 2258 // call and a return. The return will restore the stack pointer. 2259 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall()) 2260 continue; 2261 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall()) 2262 continue; 2263 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr); 2264 } 2265 } 2266 2267 // If we are inlining for an invoke instruction, we must make sure to rewrite 2268 // any call instructions into invoke instructions. This is sensitive to which 2269 // funclet pads were top-level in the inlinee, so must be done before 2270 // rewriting the "parent pad" links. 2271 if (auto *II = dyn_cast<InvokeInst>(&CB)) { 2272 BasicBlock *UnwindDest = II->getUnwindDest(); 2273 Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI(); 2274 if (isa<LandingPadInst>(FirstNonPHI)) { 2275 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo); 2276 } else { 2277 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo); 2278 } 2279 } 2280 2281 // Update the lexical scopes of the new funclets and callsites. 2282 // Anything that had 'none' as its parent is now nested inside the callsite's 2283 // EHPad. 2284 2285 if (CallSiteEHPad) { 2286 for (Function::iterator BB = FirstNewBlock->getIterator(), 2287 E = Caller->end(); 2288 BB != E; ++BB) { 2289 // Add bundle operands to any top-level call sites. 2290 SmallVector<OperandBundleDef, 1> OpBundles; 2291 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) { 2292 CallBase *I = dyn_cast<CallBase>(&*BBI++); 2293 if (!I) 2294 continue; 2295 2296 // Skip call sites which are nounwind intrinsics. 2297 auto *CalledFn = 2298 dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts()); 2299 if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow()) 2300 continue; 2301 2302 // Skip call sites which already have a "funclet" bundle. 2303 if (I->getOperandBundle(LLVMContext::OB_funclet)) 2304 continue; 2305 2306 I->getOperandBundlesAsDefs(OpBundles); 2307 OpBundles.emplace_back("funclet", CallSiteEHPad); 2308 2309 Instruction *NewInst = CallBase::Create(I, OpBundles, I); 2310 NewInst->takeName(I); 2311 I->replaceAllUsesWith(NewInst); 2312 I->eraseFromParent(); 2313 2314 OpBundles.clear(); 2315 } 2316 2317 // It is problematic if the inlinee has a cleanupret which unwinds to 2318 // caller and we inline it into a call site which doesn't unwind but into 2319 // an EH pad that does. Such an edge must be dynamically unreachable. 2320 // As such, we replace the cleanupret with unreachable. 2321 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator())) 2322 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally) 2323 changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false); 2324 2325 Instruction *I = BB->getFirstNonPHI(); 2326 if (!I->isEHPad()) 2327 continue; 2328 2329 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { 2330 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad())) 2331 CatchSwitch->setParentPad(CallSiteEHPad); 2332 } else { 2333 auto *FPI = cast<FuncletPadInst>(I); 2334 if (isa<ConstantTokenNone>(FPI->getParentPad())) 2335 FPI->setParentPad(CallSiteEHPad); 2336 } 2337 } 2338 } 2339 2340 if (InlinedDeoptimizeCalls) { 2341 // We need to at least remove the deoptimizing returns from the Return set, 2342 // so that the control flow from those returns does not get merged into the 2343 // caller (but terminate it instead). If the caller's return type does not 2344 // match the callee's return type, we also need to change the return type of 2345 // the intrinsic. 2346 if (Caller->getReturnType() == CB.getType()) { 2347 llvm::erase_if(Returns, [](ReturnInst *RI) { 2348 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr; 2349 }); 2350 } else { 2351 SmallVector<ReturnInst *, 8> NormalReturns; 2352 Function *NewDeoptIntrinsic = Intrinsic::getDeclaration( 2353 Caller->getParent(), Intrinsic::experimental_deoptimize, 2354 {Caller->getReturnType()}); 2355 2356 for (ReturnInst *RI : Returns) { 2357 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall(); 2358 if (!DeoptCall) { 2359 NormalReturns.push_back(RI); 2360 continue; 2361 } 2362 2363 // The calling convention on the deoptimize call itself may be bogus, 2364 // since the code we're inlining may have undefined behavior (and may 2365 // never actually execute at runtime); but all 2366 // @llvm.experimental.deoptimize declarations have to have the same 2367 // calling convention in a well-formed module. 2368 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv(); 2369 NewDeoptIntrinsic->setCallingConv(CallingConv); 2370 auto *CurBB = RI->getParent(); 2371 RI->eraseFromParent(); 2372 2373 SmallVector<Value *, 4> CallArgs(DeoptCall->args()); 2374 2375 SmallVector<OperandBundleDef, 1> OpBundles; 2376 DeoptCall->getOperandBundlesAsDefs(OpBundles); 2377 DeoptCall->eraseFromParent(); 2378 assert(!OpBundles.empty() && 2379 "Expected at least the deopt operand bundle"); 2380 2381 IRBuilder<> Builder(CurBB); 2382 CallInst *NewDeoptCall = 2383 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles); 2384 NewDeoptCall->setCallingConv(CallingConv); 2385 if (NewDeoptCall->getType()->isVoidTy()) 2386 Builder.CreateRetVoid(); 2387 else 2388 Builder.CreateRet(NewDeoptCall); 2389 } 2390 2391 // Leave behind the normal returns so we can merge control flow. 2392 std::swap(Returns, NormalReturns); 2393 } 2394 } 2395 2396 // Handle any inlined musttail call sites. In order for a new call site to be 2397 // musttail, the source of the clone and the inlined call site must have been 2398 // musttail. Therefore it's safe to return without merging control into the 2399 // phi below. 2400 if (InlinedMustTailCalls) { 2401 // Check if we need to bitcast the result of any musttail calls. 2402 Type *NewRetTy = Caller->getReturnType(); 2403 bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy; 2404 2405 // Handle the returns preceded by musttail calls separately. 2406 SmallVector<ReturnInst *, 8> NormalReturns; 2407 for (ReturnInst *RI : Returns) { 2408 CallInst *ReturnedMustTail = 2409 RI->getParent()->getTerminatingMustTailCall(); 2410 if (!ReturnedMustTail) { 2411 NormalReturns.push_back(RI); 2412 continue; 2413 } 2414 if (!NeedBitCast) 2415 continue; 2416 2417 // Delete the old return and any preceding bitcast. 2418 BasicBlock *CurBB = RI->getParent(); 2419 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue()); 2420 RI->eraseFromParent(); 2421 if (OldCast) 2422 OldCast->eraseFromParent(); 2423 2424 // Insert a new bitcast and return with the right type. 2425 IRBuilder<> Builder(CurBB); 2426 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy)); 2427 } 2428 2429 // Leave behind the normal returns so we can merge control flow. 2430 std::swap(Returns, NormalReturns); 2431 } 2432 2433 // Now that all of the transforms on the inlined code have taken place but 2434 // before we splice the inlined code into the CFG and lose track of which 2435 // blocks were actually inlined, collect the call sites. We only do this if 2436 // call graph updates weren't requested, as those provide value handle based 2437 // tracking of inlined call sites instead. 2438 if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) { 2439 // Otherwise just collect the raw call sites that were inlined. 2440 for (BasicBlock &NewBB : 2441 make_range(FirstNewBlock->getIterator(), Caller->end())) 2442 for (Instruction &I : NewBB) 2443 if (auto *CB = dyn_cast<CallBase>(&I)) 2444 IFI.InlinedCallSites.push_back(CB); 2445 } 2446 2447 // If we cloned in _exactly one_ basic block, and if that block ends in a 2448 // return instruction, we splice the body of the inlined callee directly into 2449 // the calling basic block. 2450 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) { 2451 // Move all of the instructions right before the call. 2452 OrigBB->getInstList().splice(CB.getIterator(), FirstNewBlock->getInstList(), 2453 FirstNewBlock->begin(), FirstNewBlock->end()); 2454 // Remove the cloned basic block. 2455 Caller->getBasicBlockList().pop_back(); 2456 2457 // If the call site was an invoke instruction, add a branch to the normal 2458 // destination. 2459 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 2460 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), &CB); 2461 NewBr->setDebugLoc(Returns[0]->getDebugLoc()); 2462 } 2463 2464 // If the return instruction returned a value, replace uses of the call with 2465 // uses of the returned value. 2466 if (!CB.use_empty()) { 2467 ReturnInst *R = Returns[0]; 2468 if (&CB == R->getReturnValue()) 2469 CB.replaceAllUsesWith(UndefValue::get(CB.getType())); 2470 else 2471 CB.replaceAllUsesWith(R->getReturnValue()); 2472 } 2473 // Since we are now done with the Call/Invoke, we can delete it. 2474 CB.eraseFromParent(); 2475 2476 // Since we are now done with the return instruction, delete it also. 2477 Returns[0]->eraseFromParent(); 2478 2479 // We are now done with the inlining. 2480 return InlineResult::success(); 2481 } 2482 2483 // Otherwise, we have the normal case, of more than one block to inline or 2484 // multiple return sites. 2485 2486 // We want to clone the entire callee function into the hole between the 2487 // "starter" and "ender" blocks. How we accomplish this depends on whether 2488 // this is an invoke instruction or a call instruction. 2489 BasicBlock *AfterCallBB; 2490 BranchInst *CreatedBranchToNormalDest = nullptr; 2491 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 2492 2493 // Add an unconditional branch to make this look like the CallInst case... 2494 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), &CB); 2495 2496 // Split the basic block. This guarantees that no PHI nodes will have to be 2497 // updated due to new incoming edges, and make the invoke case more 2498 // symmetric to the call case. 2499 AfterCallBB = 2500 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(), 2501 CalledFunc->getName() + ".exit"); 2502 2503 } else { // It's a call 2504 // If this is a call instruction, we need to split the basic block that 2505 // the call lives in. 2506 // 2507 AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(), 2508 CalledFunc->getName() + ".exit"); 2509 } 2510 2511 if (IFI.CallerBFI) { 2512 // Copy original BB's block frequency to AfterCallBB 2513 IFI.CallerBFI->setBlockFreq( 2514 AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency()); 2515 } 2516 2517 // Change the branch that used to go to AfterCallBB to branch to the first 2518 // basic block of the inlined function. 2519 // 2520 Instruction *Br = OrigBB->getTerminator(); 2521 assert(Br && Br->getOpcode() == Instruction::Br && 2522 "splitBasicBlock broken!"); 2523 Br->setOperand(0, &*FirstNewBlock); 2524 2525 // Now that the function is correct, make it a little bit nicer. In 2526 // particular, move the basic blocks inserted from the end of the function 2527 // into the space made by splitting the source basic block. 2528 Caller->getBasicBlockList().splice(AfterCallBB->getIterator(), 2529 Caller->getBasicBlockList(), FirstNewBlock, 2530 Caller->end()); 2531 2532 // Handle all of the return instructions that we just cloned in, and eliminate 2533 // any users of the original call/invoke instruction. 2534 Type *RTy = CalledFunc->getReturnType(); 2535 2536 PHINode *PHI = nullptr; 2537 if (Returns.size() > 1) { 2538 // The PHI node should go at the front of the new basic block to merge all 2539 // possible incoming values. 2540 if (!CB.use_empty()) { 2541 PHI = PHINode::Create(RTy, Returns.size(), CB.getName(), 2542 &AfterCallBB->front()); 2543 // Anything that used the result of the function call should now use the 2544 // PHI node as their operand. 2545 CB.replaceAllUsesWith(PHI); 2546 } 2547 2548 // Loop over all of the return instructions adding entries to the PHI node 2549 // as appropriate. 2550 if (PHI) { 2551 for (unsigned i = 0, e = Returns.size(); i != e; ++i) { 2552 ReturnInst *RI = Returns[i]; 2553 assert(RI->getReturnValue()->getType() == PHI->getType() && 2554 "Ret value not consistent in function!"); 2555 PHI->addIncoming(RI->getReturnValue(), RI->getParent()); 2556 } 2557 } 2558 2559 // Add a branch to the merge points and remove return instructions. 2560 DebugLoc Loc; 2561 for (unsigned i = 0, e = Returns.size(); i != e; ++i) { 2562 ReturnInst *RI = Returns[i]; 2563 BranchInst* BI = BranchInst::Create(AfterCallBB, RI); 2564 Loc = RI->getDebugLoc(); 2565 BI->setDebugLoc(Loc); 2566 RI->eraseFromParent(); 2567 } 2568 // We need to set the debug location to *somewhere* inside the 2569 // inlined function. The line number may be nonsensical, but the 2570 // instruction will at least be associated with the right 2571 // function. 2572 if (CreatedBranchToNormalDest) 2573 CreatedBranchToNormalDest->setDebugLoc(Loc); 2574 } else if (!Returns.empty()) { 2575 // Otherwise, if there is exactly one return value, just replace anything 2576 // using the return value of the call with the computed value. 2577 if (!CB.use_empty()) { 2578 if (&CB == Returns[0]->getReturnValue()) 2579 CB.replaceAllUsesWith(UndefValue::get(CB.getType())); 2580 else 2581 CB.replaceAllUsesWith(Returns[0]->getReturnValue()); 2582 } 2583 2584 // Update PHI nodes that use the ReturnBB to use the AfterCallBB. 2585 BasicBlock *ReturnBB = Returns[0]->getParent(); 2586 ReturnBB->replaceAllUsesWith(AfterCallBB); 2587 2588 // Splice the code from the return block into the block that it will return 2589 // to, which contains the code that was after the call. 2590 AfterCallBB->getInstList().splice(AfterCallBB->begin(), 2591 ReturnBB->getInstList()); 2592 2593 if (CreatedBranchToNormalDest) 2594 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc()); 2595 2596 // Delete the return instruction now and empty ReturnBB now. 2597 Returns[0]->eraseFromParent(); 2598 ReturnBB->eraseFromParent(); 2599 } else if (!CB.use_empty()) { 2600 // No returns, but something is using the return value of the call. Just 2601 // nuke the result. 2602 CB.replaceAllUsesWith(UndefValue::get(CB.getType())); 2603 } 2604 2605 // Since we are now done with the Call/Invoke, we can delete it. 2606 CB.eraseFromParent(); 2607 2608 // If we inlined any musttail calls and the original return is now 2609 // unreachable, delete it. It can only contain a bitcast and ret. 2610 if (InlinedMustTailCalls && pred_empty(AfterCallBB)) 2611 AfterCallBB->eraseFromParent(); 2612 2613 // We should always be able to fold the entry block of the function into the 2614 // single predecessor of the block... 2615 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!"); 2616 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0); 2617 2618 // Splice the code entry block into calling block, right before the 2619 // unconditional branch. 2620 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes 2621 OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList()); 2622 2623 // Remove the unconditional branch. 2624 OrigBB->getInstList().erase(Br); 2625 2626 // Now we can remove the CalleeEntry block, which is now empty. 2627 Caller->getBasicBlockList().erase(CalleeEntry); 2628 2629 // If we inserted a phi node, check to see if it has a single value (e.g. all 2630 // the entries are the same or undef). If so, remove the PHI so it doesn't 2631 // block other optimizations. 2632 if (PHI) { 2633 AssumptionCache *AC = 2634 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 2635 auto &DL = Caller->getParent()->getDataLayout(); 2636 if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) { 2637 PHI->replaceAllUsesWith(V); 2638 PHI->eraseFromParent(); 2639 } 2640 } 2641 2642 return InlineResult::success(); 2643 } 2644