1 //===- CallSiteSplitting.cpp ----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements a transformation that tries to split a call-site to pass 11 // more constrained arguments if its argument is predicated in the control flow 12 // so that we can expose better context to the later passes (e.g, inliner, jump 13 // threading, or IPA-CP based function cloning, etc.). 14 // As of now we support two cases : 15 // 16 // 1) Try to a split call-site with constrained arguments, if any constraints 17 // on any argument can be found by following the single predecessors of the 18 // all site's predecessors. Currently this pass only handles call-sites with 2 19 // predecessors. For example, in the code below, we try to split the call-site 20 // since we can predicate the argument(ptr) based on the OR condition. 21 // 22 // Split from : 23 // if (!ptr || c) 24 // callee(ptr); 25 // to : 26 // if (!ptr) 27 // callee(null) // set the known constant value 28 // else if (c) 29 // callee(nonnull ptr) // set non-null attribute in the argument 30 // 31 // 2) We can also split a call-site based on constant incoming values of a PHI 32 // For example, 33 // from : 34 // Header: 35 // %c = icmp eq i32 %i1, %i2 36 // br i1 %c, label %Tail, label %TBB 37 // TBB: 38 // br label Tail% 39 // Tail: 40 // %p = phi i32 [ 0, %Header], [ 1, %TBB] 41 // call void @bar(i32 %p) 42 // to 43 // Header: 44 // %c = icmp eq i32 %i1, %i2 45 // br i1 %c, label %Tail-split0, label %TBB 46 // TBB: 47 // br label %Tail-split1 48 // Tail-split0: 49 // call void @bar(i32 0) 50 // br label %Tail 51 // Tail-split1: 52 // call void @bar(i32 1) 53 // br label %Tail 54 // Tail: 55 // %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ] 56 // 57 //===----------------------------------------------------------------------===// 58 59 #include "llvm/Transforms/Scalar/CallSiteSplitting.h" 60 #include "llvm/ADT/Statistic.h" 61 #include "llvm/Analysis/TargetLibraryInfo.h" 62 #include "llvm/Analysis/TargetTransformInfo.h" 63 #include "llvm/Analysis/Utils/Local.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/PatternMatch.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Transforms/Scalar.h" 68 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 69 #include "llvm/Transforms/Utils/Cloning.h" 70 71 using namespace llvm; 72 using namespace PatternMatch; 73 74 #define DEBUG_TYPE "callsite-splitting" 75 76 STATISTIC(NumCallSiteSplit, "Number of call-site split"); 77 78 /// Only allow instructions before a call, if their CodeSize cost is below 79 /// DuplicationThreshold. Those instructions need to be duplicated in all 80 /// split blocks. 81 static cl::opt<unsigned> 82 DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden, 83 cl::desc("Only allow instructions before a call, if " 84 "their cost is below DuplicationThreshold"), 85 cl::init(5)); 86 87 static void addNonNullAttribute(CallSite CS, Value *Op) { 88 unsigned ArgNo = 0; 89 for (auto &I : CS.args()) { 90 if (&*I == Op) 91 CS.addParamAttr(ArgNo, Attribute::NonNull); 92 ++ArgNo; 93 } 94 } 95 96 static void setConstantInArgument(CallSite CS, Value *Op, 97 Constant *ConstValue) { 98 unsigned ArgNo = 0; 99 for (auto &I : CS.args()) { 100 if (&*I == Op) 101 CS.setArgument(ArgNo, ConstValue); 102 ++ArgNo; 103 } 104 } 105 106 static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallSite CS) { 107 assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand."); 108 Value *Op0 = Cmp->getOperand(0); 109 unsigned ArgNo = 0; 110 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; 111 ++I, ++ArgNo) { 112 // Don't consider constant or arguments that are already known non-null. 113 if (isa<Constant>(*I) || CS.paramHasAttr(ArgNo, Attribute::NonNull)) 114 continue; 115 116 if (*I == Op0) 117 return true; 118 } 119 return false; 120 } 121 122 typedef std::pair<ICmpInst *, unsigned> ConditionTy; 123 typedef SmallVector<ConditionTy, 2> ConditionsTy; 124 125 /// If From has a conditional jump to To, add the condition to Conditions, 126 /// if it is relevant to any argument at CS. 127 static void recordCondition(CallSite CS, BasicBlock *From, BasicBlock *To, 128 ConditionsTy &Conditions) { 129 auto *BI = dyn_cast<BranchInst>(From->getTerminator()); 130 if (!BI || !BI->isConditional()) 131 return; 132 133 CmpInst::Predicate Pred; 134 Value *Cond = BI->getCondition(); 135 if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant()))) 136 return; 137 138 ICmpInst *Cmp = cast<ICmpInst>(Cond); 139 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) 140 if (isCondRelevantToAnyCallArgument(Cmp, CS)) 141 Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To 142 ? Pred 143 : Cmp->getInversePredicate()}); 144 } 145 146 /// Record ICmp conditions relevant to any argument in CS following Pred's 147 /// single predecessors. If there are conflicting conditions along a path, like 148 /// x == 1 and x == 0, the first condition will be used. 149 static void recordConditions(CallSite CS, BasicBlock *Pred, 150 ConditionsTy &Conditions) { 151 recordCondition(CS, Pred, CS.getInstruction()->getParent(), Conditions); 152 BasicBlock *From = Pred; 153 BasicBlock *To = Pred; 154 SmallPtrSet<BasicBlock *, 4> Visited; 155 while (!Visited.count(From->getSinglePredecessor()) && 156 (From = From->getSinglePredecessor())) { 157 recordCondition(CS, From, To, Conditions); 158 Visited.insert(From); 159 To = From; 160 } 161 } 162 163 static void addConditions(CallSite CS, const ConditionsTy &Conditions) { 164 for (auto &Cond : Conditions) { 165 Value *Arg = Cond.first->getOperand(0); 166 Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1)); 167 if (Cond.second == ICmpInst::ICMP_EQ) 168 setConstantInArgument(CS, Arg, ConstVal); 169 else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) { 170 assert(Cond.second == ICmpInst::ICMP_NE); 171 addNonNullAttribute(CS, Arg); 172 } 173 } 174 } 175 176 static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) { 177 SmallVector<BasicBlock *, 2> Preds(predecessors((BB))); 178 assert(Preds.size() == 2 && "Expected exactly 2 predecessors!"); 179 return Preds; 180 } 181 182 static bool canSplitCallSite(CallSite CS, TargetTransformInfo &TTI) { 183 // FIXME: As of now we handle only CallInst. InvokeInst could be handled 184 // without too much effort. 185 Instruction *Instr = CS.getInstruction(); 186 if (!isa<CallInst>(Instr)) 187 return false; 188 189 BasicBlock *CallSiteBB = Instr->getParent(); 190 // Allow splitting a call-site only when the CodeSize cost of the 191 // instructions before the call is less then DuplicationThreshold. The 192 // instructions before the call will be duplicated in the split blocks and 193 // corresponding uses will be updated. 194 unsigned Cost = 0; 195 for (auto &InstBeforeCall : 196 llvm::make_range(CallSiteBB->begin(), Instr->getIterator())) { 197 Cost += TTI.getInstructionCost(&InstBeforeCall, 198 TargetTransformInfo::TCK_CodeSize); 199 if (Cost >= DuplicationThreshold) 200 return false; 201 } 202 203 // Need 2 predecessors and cannot split an edge from an IndirectBrInst. 204 SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB)); 205 if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) || 206 isa<IndirectBrInst>(Preds[1]->getTerminator())) 207 return false; 208 209 // Do not split a call-site in an exception handling block. This check 210 // prevents triggering an assertion in SplitEdge used via 211 // DuplicateInstructionsInSplitBetween. 212 if (CallSiteBB->isEHPad()) 213 return false; 214 215 return CallSiteBB->canSplitPredecessors(); 216 } 217 218 static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before, 219 Value *V) { 220 Instruction *Copy = I->clone(); 221 Copy->setName(I->getName()); 222 Copy->insertBefore(Before); 223 if (V) 224 Copy->setOperand(0, V); 225 return Copy; 226 } 227 228 /// Copy mandatory `musttail` return sequence that follows original `CI`, and 229 /// link it up to `NewCI` value instead: 230 /// 231 /// * (optional) `bitcast NewCI to ...` 232 /// * `ret bitcast or NewCI` 233 /// 234 /// Insert this sequence right before `SplitBB`'s terminator, which will be 235 /// cleaned up later in `splitCallSite` below. 236 static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI, 237 Instruction *NewCI) { 238 bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy(); 239 auto II = std::next(CI->getIterator()); 240 241 BitCastInst* BCI = dyn_cast<BitCastInst>(&*II); 242 if (BCI) 243 ++II; 244 245 ReturnInst* RI = dyn_cast<ReturnInst>(&*II); 246 assert(RI && "`musttail` call must be followed by `ret` instruction"); 247 248 TerminatorInst *TI = SplitBB->getTerminator(); 249 Value *V = NewCI; 250 if (BCI) 251 V = cloneInstForMustTail(BCI, TI, V); 252 cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V); 253 254 // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug 255 // that prevents doing this now. 256 } 257 258 /// For each (predecessor, conditions from predecessors) pair, it will split the 259 /// basic block containing the call site, hook it up to the predecessor and 260 /// replace the call instruction with new call instructions, which contain 261 /// constraints based on the conditions from their predecessors. 262 /// For example, in the IR below with an OR condition, the call-site can 263 /// be split. In this case, Preds for Tail is [(Header, a == null), 264 /// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing 265 /// CallInst1, which has constraints based on the conditions from Head and 266 /// CallInst2, which has constraints based on the conditions coming from TBB. 267 /// 268 /// From : 269 /// 270 /// Header: 271 /// %c = icmp eq i32* %a, null 272 /// br i1 %c %Tail, %TBB 273 /// TBB: 274 /// %c2 = icmp eq i32* %b, null 275 /// br i1 %c %Tail, %End 276 /// Tail: 277 /// %ca = call i1 @callee (i32* %a, i32* %b) 278 /// 279 /// to : 280 /// 281 /// Header: // PredBB1 is Header 282 /// %c = icmp eq i32* %a, null 283 /// br i1 %c %Tail-split1, %TBB 284 /// TBB: // PredBB2 is TBB 285 /// %c2 = icmp eq i32* %b, null 286 /// br i1 %c %Tail-split2, %End 287 /// Tail-split1: 288 /// %ca1 = call @callee (i32* null, i32* %b) // CallInst1 289 /// br %Tail 290 /// Tail-split2: 291 /// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2 292 /// br %Tail 293 /// Tail: 294 /// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2] 295 /// 296 /// Note that in case any arguments at the call-site are constrained by its 297 /// predecessors, new call-sites with more constrained arguments will be 298 /// created in createCallSitesOnPredicatedArgument(). 299 static void splitCallSite( 300 CallSite CS, 301 const SmallVectorImpl<std::pair<BasicBlock *, ConditionsTy>> &Preds, 302 DominatorTree *DT) { 303 Instruction *Instr = CS.getInstruction(); 304 BasicBlock *TailBB = Instr->getParent(); 305 bool IsMustTailCall = CS.isMustTailCall(); 306 307 PHINode *CallPN = nullptr; 308 309 // `musttail` calls must be followed by optional `bitcast`, and `ret`. The 310 // split blocks will be terminated right after that so there're no users for 311 // this phi in a `TailBB`. 312 if (!IsMustTailCall && !Instr->use_empty()) 313 CallPN = PHINode::Create(Instr->getType(), Preds.size(), "phi.call"); 314 315 DEBUG(dbgs() << "split call-site : " << *Instr << " into \n"); 316 317 assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2."); 318 // ValueToValueMapTy is neither copy nor moveable, so we use a simple array 319 // here. 320 ValueToValueMapTy ValueToValueMaps[2]; 321 for (unsigned i = 0; i < Preds.size(); i++) { 322 BasicBlock *PredBB = Preds[i].first; 323 BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween( 324 TailBB, PredBB, &*std::next(Instr->getIterator()), ValueToValueMaps[i], 325 DT); 326 assert(SplitBlock && "Unexpected new basic block split."); 327 328 Instruction *NewCI = 329 &*std::prev(SplitBlock->getTerminator()->getIterator()); 330 CallSite NewCS(NewCI); 331 addConditions(NewCS, Preds[i].second); 332 333 // Handle PHIs used as arguments in the call-site. 334 for (PHINode &PN : TailBB->phis()) { 335 unsigned ArgNo = 0; 336 for (auto &CI : CS.args()) { 337 if (&*CI == &PN) { 338 NewCS.setArgument(ArgNo, PN.getIncomingValueForBlock(SplitBlock)); 339 } 340 ++ArgNo; 341 } 342 } 343 DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName() 344 << "\n"); 345 if (CallPN) 346 CallPN->addIncoming(NewCI, SplitBlock); 347 348 // Clone and place bitcast and return instructions before `TI` 349 if (IsMustTailCall) 350 copyMustTailReturn(SplitBlock, Instr, NewCI); 351 } 352 353 NumCallSiteSplit++; 354 355 // FIXME: remove TI in `copyMustTailReturn` 356 if (IsMustTailCall) { 357 // Remove superfluous `br` terminators from the end of the Split blocks 358 // NOTE: Removing terminator removes the SplitBlock from the TailBB's 359 // predecessors. Therefore we must get complete list of Splits before 360 // attempting removal. 361 SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB))); 362 assert(Splits.size() == 2 && "Expected exactly 2 splits!"); 363 for (unsigned i = 0; i < Splits.size(); i++) 364 Splits[i]->getTerminator()->eraseFromParent(); 365 366 // Erase the tail block once done with musttail patching 367 TailBB->eraseFromParent(); 368 return; 369 } 370 371 auto *OriginalBegin = &*TailBB->begin(); 372 // Replace users of the original call with a PHI mering call-sites split. 373 if (CallPN) { 374 CallPN->insertBefore(OriginalBegin); 375 Instr->replaceAllUsesWith(CallPN); 376 } 377 378 // Remove instructions moved to split blocks from TailBB, from the duplicated 379 // call instruction to the beginning of the basic block. If an instruction 380 // has any uses, add a new PHI node to combine the values coming from the 381 // split blocks. The new PHI nodes are placed before the first original 382 // instruction, so we do not end up deleting them. By using reverse-order, we 383 // do not introduce unnecessary PHI nodes for def-use chains from the call 384 // instruction to the beginning of the block. 385 auto I = Instr->getReverseIterator(); 386 while (I != TailBB->rend()) { 387 Instruction *CurrentI = &*I++; 388 if (!CurrentI->use_empty()) { 389 // If an existing PHI has users after the call, there is no need to create 390 // a new one. 391 if (isa<PHINode>(CurrentI)) 392 continue; 393 PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size()); 394 for (auto &Mapping : ValueToValueMaps) 395 NewPN->addIncoming(Mapping[CurrentI], 396 cast<Instruction>(Mapping[CurrentI])->getParent()); 397 NewPN->insertBefore(&*TailBB->begin()); 398 CurrentI->replaceAllUsesWith(NewPN); 399 } 400 CurrentI->eraseFromParent(); 401 // We are done once we handled the first original instruction in TailBB. 402 if (CurrentI == OriginalBegin) 403 break; 404 } 405 } 406 407 // Return true if the call-site has an argument which is a PHI with only 408 // constant incoming values. 409 static bool isPredicatedOnPHI(CallSite CS) { 410 Instruction *Instr = CS.getInstruction(); 411 BasicBlock *Parent = Instr->getParent(); 412 if (Instr != Parent->getFirstNonPHIOrDbg()) 413 return false; 414 415 for (auto &BI : *Parent) { 416 if (PHINode *PN = dyn_cast<PHINode>(&BI)) { 417 for (auto &I : CS.args()) 418 if (&*I == PN) { 419 assert(PN->getNumIncomingValues() == 2 && 420 "Unexpected number of incoming values"); 421 if (PN->getIncomingBlock(0) == PN->getIncomingBlock(1)) 422 return false; 423 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) 424 continue; 425 if (isa<Constant>(PN->getIncomingValue(0)) && 426 isa<Constant>(PN->getIncomingValue(1))) 427 return true; 428 } 429 } 430 break; 431 } 432 return false; 433 } 434 435 static bool tryToSplitOnPHIPredicatedArgument(CallSite CS, DominatorTree *DT) { 436 if (!isPredicatedOnPHI(CS)) 437 return false; 438 439 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent()); 440 SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS = { 441 {Preds[0], {}}, {Preds[1], {}}}; 442 splitCallSite(CS, PredsCS, DT); 443 return true; 444 } 445 446 static bool tryToSplitOnPredicatedArgument(CallSite CS, DominatorTree *DT) { 447 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent()); 448 if (Preds[0] == Preds[1]) 449 return false; 450 451 SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS; 452 for (auto *Pred : make_range(Preds.rbegin(), Preds.rend())) { 453 ConditionsTy Conditions; 454 recordConditions(CS, Pred, Conditions); 455 PredsCS.push_back({Pred, Conditions}); 456 } 457 458 if (std::all_of(PredsCS.begin(), PredsCS.end(), 459 [](const std::pair<BasicBlock *, ConditionsTy> &P) { 460 return P.second.empty(); 461 })) 462 return false; 463 464 splitCallSite(CS, PredsCS, DT); 465 return true; 466 } 467 468 static bool tryToSplitCallSite(CallSite CS, TargetTransformInfo &TTI, 469 DominatorTree *DT) { 470 if (!CS.arg_size() || !canSplitCallSite(CS, TTI)) 471 return false; 472 return tryToSplitOnPredicatedArgument(CS, DT) || 473 tryToSplitOnPHIPredicatedArgument(CS, DT); 474 } 475 476 static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI, 477 TargetTransformInfo &TTI, DominatorTree *DT) { 478 bool Changed = false; 479 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE;) { 480 BasicBlock &BB = *BI++; 481 auto II = BB.getFirstNonPHIOrDbg()->getIterator(); 482 auto IE = BB.getTerminator()->getIterator(); 483 // Iterate until we reach the terminator instruction. tryToSplitCallSite 484 // can replace BB's terminator in case BB is a successor of itself. In that 485 // case, IE will be invalidated and we also have to check the current 486 // terminator. 487 while (II != IE && &*II != BB.getTerminator()) { 488 Instruction *I = &*II++; 489 CallSite CS(cast<Value>(I)); 490 if (!CS || isa<IntrinsicInst>(I) || isInstructionTriviallyDead(I, &TLI)) 491 continue; 492 493 Function *Callee = CS.getCalledFunction(); 494 if (!Callee || Callee->isDeclaration()) 495 continue; 496 497 // Successful musttail call-site splits result in erased CI and erased BB. 498 // Check if such path is possible before attempting the splitting. 499 bool IsMustTail = CS.isMustTailCall(); 500 501 Changed |= tryToSplitCallSite(CS, TTI, DT); 502 503 // There're no interesting instructions after this. The call site 504 // itself might have been erased on splitting. 505 if (IsMustTail) 506 break; 507 } 508 } 509 return Changed; 510 } 511 512 namespace { 513 struct CallSiteSplittingLegacyPass : public FunctionPass { 514 static char ID; 515 CallSiteSplittingLegacyPass() : FunctionPass(ID) { 516 initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry()); 517 } 518 519 void getAnalysisUsage(AnalysisUsage &AU) const override { 520 AU.addRequired<TargetLibraryInfoWrapperPass>(); 521 AU.addRequired<TargetTransformInfoWrapperPass>(); 522 AU.addPreserved<DominatorTreeWrapperPass>(); 523 FunctionPass::getAnalysisUsage(AU); 524 } 525 526 bool runOnFunction(Function &F) override { 527 if (skipFunction(F)) 528 return false; 529 530 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 531 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 532 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 533 return doCallSiteSplitting(F, TLI, TTI, 534 DTWP ? &DTWP->getDomTree() : nullptr); 535 } 536 }; 537 } // namespace 538 539 char CallSiteSplittingLegacyPass::ID = 0; 540 INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting", 541 "Call-site splitting", false, false) 542 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 543 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 544 INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting", 545 "Call-site splitting", false, false) 546 FunctionPass *llvm::createCallSiteSplittingPass() { 547 return new CallSiteSplittingLegacyPass(); 548 } 549 550 PreservedAnalyses CallSiteSplittingPass::run(Function &F, 551 FunctionAnalysisManager &AM) { 552 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 553 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 554 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F); 555 556 if (!doCallSiteSplitting(F, TLI, TTI, DT)) 557 return PreservedAnalyses::all(); 558 PreservedAnalyses PA; 559 PA.preserve<DominatorTreeAnalysis>(); 560 return PA; 561 } 562