1e363d2ceSMatthew Simpson //===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===// 2e363d2ceSMatthew Simpson // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e363d2ceSMatthew Simpson // 7e363d2ceSMatthew Simpson //===----------------------------------------------------------------------===// 8e363d2ceSMatthew Simpson // 9e363d2ceSMatthew Simpson // This file implements utilities useful for promoting indirect call sites to 10e363d2ceSMatthew Simpson // direct call sites. 11e363d2ceSMatthew Simpson // 12e363d2ceSMatthew Simpson //===----------------------------------------------------------------------===// 13e363d2ceSMatthew Simpson 14e363d2ceSMatthew Simpson #include "llvm/Transforms/Utils/CallPromotionUtils.h" 15bb383ae6SHiroshi Yamauchi #include "llvm/Analysis/Loads.h" 16bb383ae6SHiroshi Yamauchi #include "llvm/Analysis/TypeMetadataUtils.h" 17e363d2ceSMatthew Simpson #include "llvm/IR/IRBuilder.h" 18d2f1cd5dSMircea Trofin #include "llvm/IR/Instructions.h" 19e363d2ceSMatthew Simpson #include "llvm/Transforms/Utils/BasicBlockUtils.h" 20e363d2ceSMatthew Simpson 21e363d2ceSMatthew Simpson using namespace llvm; 22e363d2ceSMatthew Simpson 23e363d2ceSMatthew Simpson #define DEBUG_TYPE "call-promotion-utils" 24e363d2ceSMatthew Simpson 25e363d2ceSMatthew Simpson /// Fix-up phi nodes in an invoke instruction's normal destination. 26e363d2ceSMatthew Simpson /// 27e363d2ceSMatthew Simpson /// After versioning an invoke instruction, values coming from the original 28cb35c5d5SMatthew Simpson /// block will now be coming from the "merge" block. For example, in the code 29cb35c5d5SMatthew Simpson /// below: 30cb35c5d5SMatthew Simpson /// 31cb35c5d5SMatthew Simpson /// then_bb: 32cb35c5d5SMatthew Simpson /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst 33cb35c5d5SMatthew Simpson /// 34cb35c5d5SMatthew Simpson /// else_bb: 35cb35c5d5SMatthew Simpson /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst 36cb35c5d5SMatthew Simpson /// 37cb35c5d5SMatthew Simpson /// merge_bb: 38cb35c5d5SMatthew Simpson /// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ] 39cb35c5d5SMatthew Simpson /// br %normal_dst 40cb35c5d5SMatthew Simpson /// 41cb35c5d5SMatthew Simpson /// normal_dst: 42cb35c5d5SMatthew Simpson /// %t3 = phi i32 [ %x, %orig_bb ], ... 43cb35c5d5SMatthew Simpson /// 44cb35c5d5SMatthew Simpson /// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in 45cb35c5d5SMatthew Simpson /// "normal_dst" must be fixed to refer to "merge_bb": 46cb35c5d5SMatthew Simpson /// 47cb35c5d5SMatthew Simpson /// normal_dst: 48cb35c5d5SMatthew Simpson /// %t3 = phi i32 [ %x, %merge_bb ], ... 49cb35c5d5SMatthew Simpson /// 50e363d2ceSMatthew Simpson static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock, 51cb35c5d5SMatthew Simpson BasicBlock *MergeBlock) { 52c7fc81e6SBenjamin Kramer for (PHINode &Phi : Invoke->getNormalDest()->phis()) { 53c7fc81e6SBenjamin Kramer int Idx = Phi.getBasicBlockIndex(OrigBlock); 54e363d2ceSMatthew Simpson if (Idx == -1) 55e363d2ceSMatthew Simpson continue; 56c7fc81e6SBenjamin Kramer Phi.setIncomingBlock(Idx, MergeBlock); 57e363d2ceSMatthew Simpson } 58e363d2ceSMatthew Simpson } 59e363d2ceSMatthew Simpson 60e363d2ceSMatthew Simpson /// Fix-up phi nodes in an invoke instruction's unwind destination. 61e363d2ceSMatthew Simpson /// 62e363d2ceSMatthew Simpson /// After versioning an invoke instruction, values coming from the original 63e363d2ceSMatthew Simpson /// block will now be coming from either the "then" block or the "else" block. 64cb35c5d5SMatthew Simpson /// For example, in the code below: 65cb35c5d5SMatthew Simpson /// 66cb35c5d5SMatthew Simpson /// then_bb: 67cb35c5d5SMatthew Simpson /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst 68cb35c5d5SMatthew Simpson /// 69cb35c5d5SMatthew Simpson /// else_bb: 70cb35c5d5SMatthew Simpson /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst 71cb35c5d5SMatthew Simpson /// 72cb35c5d5SMatthew Simpson /// unwind_dst: 73cb35c5d5SMatthew Simpson /// %t3 = phi i32 [ %x, %orig_bb ], ... 74cb35c5d5SMatthew Simpson /// 75cb35c5d5SMatthew Simpson /// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in 76cb35c5d5SMatthew Simpson /// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb": 77cb35c5d5SMatthew Simpson /// 78cb35c5d5SMatthew Simpson /// unwind_dst: 79cb35c5d5SMatthew Simpson /// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ... 80cb35c5d5SMatthew Simpson /// 81e363d2ceSMatthew Simpson static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock, 82e363d2ceSMatthew Simpson BasicBlock *ThenBlock, 83e363d2ceSMatthew Simpson BasicBlock *ElseBlock) { 84c7fc81e6SBenjamin Kramer for (PHINode &Phi : Invoke->getUnwindDest()->phis()) { 85c7fc81e6SBenjamin Kramer int Idx = Phi.getBasicBlockIndex(OrigBlock); 86e363d2ceSMatthew Simpson if (Idx == -1) 87e363d2ceSMatthew Simpson continue; 88c7fc81e6SBenjamin Kramer auto *V = Phi.getIncomingValue(Idx); 89c7fc81e6SBenjamin Kramer Phi.setIncomingBlock(Idx, ThenBlock); 90c7fc81e6SBenjamin Kramer Phi.addIncoming(V, ElseBlock); 91e363d2ceSMatthew Simpson } 92e363d2ceSMatthew Simpson } 93e363d2ceSMatthew Simpson 94e363d2ceSMatthew Simpson /// Create a phi node for the returned value of a call or invoke instruction. 95e363d2ceSMatthew Simpson /// 96e363d2ceSMatthew Simpson /// After versioning a call or invoke instruction that returns a value, we have 97e363d2ceSMatthew Simpson /// to merge the value of the original and new instructions. We do this by 98e363d2ceSMatthew Simpson /// creating a phi node and replacing uses of the original instruction with this 99e363d2ceSMatthew Simpson /// phi node. 100cb35c5d5SMatthew Simpson /// 101cb35c5d5SMatthew Simpson /// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is 102cb35c5d5SMatthew Simpson /// defined in "then_bb", we create the following phi node: 103cb35c5d5SMatthew Simpson /// 104cb35c5d5SMatthew Simpson /// ; Uses of the original instruction are replaced by uses of the phi node. 105cb35c5d5SMatthew Simpson /// %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ], 106cb35c5d5SMatthew Simpson /// 107cb35c5d5SMatthew Simpson static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst, 108cb35c5d5SMatthew Simpson BasicBlock *MergeBlock, IRBuilder<> &Builder) { 109e363d2ceSMatthew Simpson 110e363d2ceSMatthew Simpson if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty()) 111e363d2ceSMatthew Simpson return; 112e363d2ceSMatthew Simpson 113cb35c5d5SMatthew Simpson Builder.SetInsertPoint(&MergeBlock->front()); 114e363d2ceSMatthew Simpson PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0); 1158f5da41cSKazu Hirata SmallVector<User *, 16> UsersToUpdate(OrigInst->users()); 116e363d2ceSMatthew Simpson for (User *U : UsersToUpdate) 117e363d2ceSMatthew Simpson U->replaceUsesOfWith(OrigInst, Phi); 118e363d2ceSMatthew Simpson Phi->addIncoming(OrigInst, OrigInst->getParent()); 119cb35c5d5SMatthew Simpson Phi->addIncoming(NewInst, NewInst->getParent()); 120e363d2ceSMatthew Simpson } 121e363d2ceSMatthew Simpson 122e363d2ceSMatthew Simpson /// Cast a call or invoke instruction to the given type. 123e363d2ceSMatthew Simpson /// 124e363d2ceSMatthew Simpson /// When promoting a call site, the return type of the call site might not match 125e363d2ceSMatthew Simpson /// that of the callee. If this is the case, we have to cast the returned value 126e363d2ceSMatthew Simpson /// to the correct type. The location of the cast depends on if we have a call 127e363d2ceSMatthew Simpson /// or invoke instruction. 128cb35c5d5SMatthew Simpson /// 129cb35c5d5SMatthew Simpson /// For example, if the call instruction below requires a bitcast after 130cb35c5d5SMatthew Simpson /// promotion: 131cb35c5d5SMatthew Simpson /// 132cb35c5d5SMatthew Simpson /// orig_bb: 133cb35c5d5SMatthew Simpson /// %t0 = call i32 @func() 134cb35c5d5SMatthew Simpson /// ... 135cb35c5d5SMatthew Simpson /// 136cb35c5d5SMatthew Simpson /// The bitcast is placed after the call instruction: 137cb35c5d5SMatthew Simpson /// 138cb35c5d5SMatthew Simpson /// orig_bb: 139cb35c5d5SMatthew Simpson /// ; Uses of the original return value are replaced by uses of the bitcast. 140cb35c5d5SMatthew Simpson /// %t0 = call i32 @func() 141cb35c5d5SMatthew Simpson /// %t1 = bitcast i32 %t0 to ... 142cb35c5d5SMatthew Simpson /// ... 143cb35c5d5SMatthew Simpson /// 144cb35c5d5SMatthew Simpson /// A similar transformation is performed for invoke instructions. However, 145cb35c5d5SMatthew Simpson /// since invokes are terminating, a new block is created for the bitcast. For 146cb35c5d5SMatthew Simpson /// example, if the invoke instruction below requires a bitcast after promotion: 147cb35c5d5SMatthew Simpson /// 148cb35c5d5SMatthew Simpson /// orig_bb: 149cb35c5d5SMatthew Simpson /// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst 150cb35c5d5SMatthew Simpson /// 151cb35c5d5SMatthew Simpson /// The edge between the original block and the invoke's normal destination is 152cb35c5d5SMatthew Simpson /// split, and the bitcast is placed there: 153cb35c5d5SMatthew Simpson /// 154cb35c5d5SMatthew Simpson /// orig_bb: 155cb35c5d5SMatthew Simpson /// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst 156cb35c5d5SMatthew Simpson /// 157cb35c5d5SMatthew Simpson /// split_bb: 158cb35c5d5SMatthew Simpson /// ; Uses of the original return value are replaced by uses of the bitcast. 159cb35c5d5SMatthew Simpson /// %t1 = bitcast i32 %t0 to ... 160cb35c5d5SMatthew Simpson /// br label %normal_dst 161cb35c5d5SMatthew Simpson /// 162d2f1cd5dSMircea Trofin static void createRetBitCast(CallBase &CB, Type *RetTy, CastInst **RetBitCast) { 163e363d2ceSMatthew Simpson 164e363d2ceSMatthew Simpson // Save the users of the calling instruction. These uses will be changed to 165e363d2ceSMatthew Simpson // use the bitcast after we create it. 16619aacdb7SKazu Hirata SmallVector<User *, 16> UsersToUpdate(CB.users()); 167e363d2ceSMatthew Simpson 168e363d2ceSMatthew Simpson // Determine an appropriate location to create the bitcast for the return 169e363d2ceSMatthew Simpson // value. The location depends on if we have a call or invoke instruction. 170e363d2ceSMatthew Simpson Instruction *InsertBefore = nullptr; 171d2f1cd5dSMircea Trofin if (auto *Invoke = dyn_cast<InvokeInst>(&CB)) 172cb35c5d5SMatthew Simpson InsertBefore = 173cb35c5d5SMatthew Simpson &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front(); 174e363d2ceSMatthew Simpson else 175d2f1cd5dSMircea Trofin InsertBefore = &*std::next(CB.getIterator()); 176e363d2ceSMatthew Simpson 177e363d2ceSMatthew Simpson // Bitcast the return value to the correct type. 178d2f1cd5dSMircea Trofin auto *Cast = CastInst::CreateBitOrPointerCast(&CB, RetTy, "", InsertBefore); 179cb35c5d5SMatthew Simpson if (RetBitCast) 180cb35c5d5SMatthew Simpson *RetBitCast = Cast; 181e363d2ceSMatthew Simpson 182e363d2ceSMatthew Simpson // Replace all the original uses of the calling instruction with the bitcast. 183e363d2ceSMatthew Simpson for (User *U : UsersToUpdate) 184d2f1cd5dSMircea Trofin U->replaceUsesOfWith(&CB, Cast); 185e363d2ceSMatthew Simpson } 186e363d2ceSMatthew Simpson 187e363d2ceSMatthew Simpson /// Predicate and clone the given call site. 188e363d2ceSMatthew Simpson /// 189e363d2ceSMatthew Simpson /// This function creates an if-then-else structure at the location of the call 190e363d2ceSMatthew Simpson /// site. The "if" condition compares the call site's called value to the given 191e363d2ceSMatthew Simpson /// callee. The original call site is moved into the "else" block, and a clone 192e363d2ceSMatthew Simpson /// of the call site is placed in the "then" block. The cloned instruction is 193e363d2ceSMatthew Simpson /// returned. 194cb35c5d5SMatthew Simpson /// 195cb35c5d5SMatthew Simpson /// For example, the call instruction below: 196cb35c5d5SMatthew Simpson /// 197cb35c5d5SMatthew Simpson /// orig_bb: 198cb35c5d5SMatthew Simpson /// %t0 = call i32 %ptr() 199cb35c5d5SMatthew Simpson /// ... 200cb35c5d5SMatthew Simpson /// 201cb35c5d5SMatthew Simpson /// Is replace by the following: 202cb35c5d5SMatthew Simpson /// 203cb35c5d5SMatthew Simpson /// orig_bb: 204cb35c5d5SMatthew Simpson /// %cond = icmp eq i32 ()* %ptr, @func 205cb35c5d5SMatthew Simpson /// br i1 %cond, %then_bb, %else_bb 206cb35c5d5SMatthew Simpson /// 207cb35c5d5SMatthew Simpson /// then_bb: 208cb35c5d5SMatthew Simpson /// ; The clone of the original call instruction is placed in the "then" 209cb35c5d5SMatthew Simpson /// ; block. It is not yet promoted. 210cb35c5d5SMatthew Simpson /// %t1 = call i32 %ptr() 211cb35c5d5SMatthew Simpson /// br merge_bb 212cb35c5d5SMatthew Simpson /// 213cb35c5d5SMatthew Simpson /// else_bb: 214cb35c5d5SMatthew Simpson /// ; The original call instruction is moved to the "else" block. 215cb35c5d5SMatthew Simpson /// %t0 = call i32 %ptr() 216cb35c5d5SMatthew Simpson /// br merge_bb 217cb35c5d5SMatthew Simpson /// 218cb35c5d5SMatthew Simpson /// merge_bb: 219cb35c5d5SMatthew Simpson /// ; Uses of the original call instruction are replaced by uses of the phi 220cb35c5d5SMatthew Simpson /// ; node. 221cb35c5d5SMatthew Simpson /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ] 222cb35c5d5SMatthew Simpson /// ... 223cb35c5d5SMatthew Simpson /// 224cb35c5d5SMatthew Simpson /// A similar transformation is performed for invoke instructions. However, 225cb35c5d5SMatthew Simpson /// since invokes are terminating, more work is required. For example, the 226cb35c5d5SMatthew Simpson /// invoke instruction below: 227cb35c5d5SMatthew Simpson /// 228cb35c5d5SMatthew Simpson /// orig_bb: 229cb35c5d5SMatthew Simpson /// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst 230cb35c5d5SMatthew Simpson /// 231cb35c5d5SMatthew Simpson /// Is replace by the following: 232cb35c5d5SMatthew Simpson /// 233cb35c5d5SMatthew Simpson /// orig_bb: 234cb35c5d5SMatthew Simpson /// %cond = icmp eq i32 ()* %ptr, @func 235cb35c5d5SMatthew Simpson /// br i1 %cond, %then_bb, %else_bb 236cb35c5d5SMatthew Simpson /// 237cb35c5d5SMatthew Simpson /// then_bb: 238cb35c5d5SMatthew Simpson /// ; The clone of the original invoke instruction is placed in the "then" 239cb35c5d5SMatthew Simpson /// ; block, and its normal destination is set to the "merge" block. It is 240cb35c5d5SMatthew Simpson /// ; not yet promoted. 241cb35c5d5SMatthew Simpson /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst 242cb35c5d5SMatthew Simpson /// 243cb35c5d5SMatthew Simpson /// else_bb: 244cb35c5d5SMatthew Simpson /// ; The original invoke instruction is moved into the "else" block, and 245cb35c5d5SMatthew Simpson /// ; its normal destination is set to the "merge" block. 246cb35c5d5SMatthew Simpson /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst 247cb35c5d5SMatthew Simpson /// 248cb35c5d5SMatthew Simpson /// merge_bb: 249cb35c5d5SMatthew Simpson /// ; Uses of the original invoke instruction are replaced by uses of the 250cb35c5d5SMatthew Simpson /// ; phi node, and the merge block branches to the normal destination. 251cb35c5d5SMatthew Simpson /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ] 252cb35c5d5SMatthew Simpson /// br %normal_dst 253cb35c5d5SMatthew Simpson /// 254911e06f5SHongtao Yu /// An indirect musttail call is processed slightly differently in that: 255911e06f5SHongtao Yu /// 1. No merge block needed for the orginal and the cloned callsite, since 256911e06f5SHongtao Yu /// either one ends the flow. No phi node is needed either. 257911e06f5SHongtao Yu /// 2. The return statement following the original call site is duplicated too 258911e06f5SHongtao Yu /// and placed immediately after the cloned call site per the IR convention. 259911e06f5SHongtao Yu /// 260911e06f5SHongtao Yu /// For example, the musttail call instruction below: 261911e06f5SHongtao Yu /// 262911e06f5SHongtao Yu /// orig_bb: 263911e06f5SHongtao Yu /// %t0 = musttail call i32 %ptr() 264911e06f5SHongtao Yu /// ... 265911e06f5SHongtao Yu /// 266911e06f5SHongtao Yu /// Is replaced by the following: 267911e06f5SHongtao Yu /// 268911e06f5SHongtao Yu /// cond_bb: 269911e06f5SHongtao Yu /// %cond = icmp eq i32 ()* %ptr, @func 270911e06f5SHongtao Yu /// br i1 %cond, %then_bb, %orig_bb 271911e06f5SHongtao Yu /// 272911e06f5SHongtao Yu /// then_bb: 273911e06f5SHongtao Yu /// ; The clone of the original call instruction is placed in the "then" 274911e06f5SHongtao Yu /// ; block. It is not yet promoted. 275911e06f5SHongtao Yu /// %t1 = musttail call i32 %ptr() 276911e06f5SHongtao Yu /// ret %t1 277911e06f5SHongtao Yu /// 278911e06f5SHongtao Yu /// orig_bb: 279911e06f5SHongtao Yu /// ; The original call instruction stays in its original block. 280911e06f5SHongtao Yu /// %t0 = musttail call i32 %ptr() 281911e06f5SHongtao Yu /// ret %t0 282d2f1cd5dSMircea Trofin static CallBase &versionCallSite(CallBase &CB, Value *Callee, 283cb35c5d5SMatthew Simpson MDNode *BranchWeights) { 284e363d2ceSMatthew Simpson 285d2f1cd5dSMircea Trofin IRBuilder<> Builder(&CB); 286d2f1cd5dSMircea Trofin CallBase *OrigInst = &CB; 287cb35c5d5SMatthew Simpson BasicBlock *OrigBlock = OrigInst->getParent(); 288e363d2ceSMatthew Simpson 289e363d2ceSMatthew Simpson // Create the compare. The called value and callee must have the same type to 290e363d2ceSMatthew Simpson // be compared. 291a58b62b4SCraig Topper if (CB.getCalledOperand()->getType() != Callee->getType()) 292a58b62b4SCraig Topper Callee = Builder.CreateBitCast(Callee, CB.getCalledOperand()->getType()); 293a58b62b4SCraig Topper auto *Cond = Builder.CreateICmpEQ(CB.getCalledOperand(), Callee); 294e363d2ceSMatthew Simpson 295911e06f5SHongtao Yu if (OrigInst->isMustTailCall()) { 296911e06f5SHongtao Yu // Create an if-then structure. The original instruction stays in its block, 297911e06f5SHongtao Yu // and a clone of the original instruction is placed in the "then" block. 298911e06f5SHongtao Yu Instruction *ThenTerm = 299911e06f5SHongtao Yu SplitBlockAndInsertIfThen(Cond, &CB, false, BranchWeights); 300911e06f5SHongtao Yu BasicBlock *ThenBlock = ThenTerm->getParent(); 301911e06f5SHongtao Yu ThenBlock->setName("if.true.direct_targ"); 302911e06f5SHongtao Yu CallBase *NewInst = cast<CallBase>(OrigInst->clone()); 303911e06f5SHongtao Yu NewInst->insertBefore(ThenTerm); 304911e06f5SHongtao Yu 305911e06f5SHongtao Yu // Place a clone of the optional bitcast after the new call site. 306911e06f5SHongtao Yu Value *NewRetVal = NewInst; 307911e06f5SHongtao Yu auto Next = OrigInst->getNextNode(); 308911e06f5SHongtao Yu if (auto *BitCast = dyn_cast_or_null<BitCastInst>(Next)) { 309911e06f5SHongtao Yu assert(BitCast->getOperand(0) == OrigInst && 310911e06f5SHongtao Yu "bitcast following musttail call must use the call"); 311911e06f5SHongtao Yu auto NewBitCast = BitCast->clone(); 312911e06f5SHongtao Yu NewBitCast->replaceUsesOfWith(OrigInst, NewInst); 313911e06f5SHongtao Yu NewBitCast->insertBefore(ThenTerm); 314911e06f5SHongtao Yu NewRetVal = NewBitCast; 315911e06f5SHongtao Yu Next = BitCast->getNextNode(); 316911e06f5SHongtao Yu } 317911e06f5SHongtao Yu 318911e06f5SHongtao Yu // Place a clone of the return instruction after the new call site. 319911e06f5SHongtao Yu ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 320911e06f5SHongtao Yu assert(Ret && "musttail call must precede a ret with an optional bitcast"); 321911e06f5SHongtao Yu auto NewRet = Ret->clone(); 322911e06f5SHongtao Yu if (Ret->getReturnValue()) 323911e06f5SHongtao Yu NewRet->replaceUsesOfWith(Ret->getReturnValue(), NewRetVal); 324911e06f5SHongtao Yu NewRet->insertBefore(ThenTerm); 325911e06f5SHongtao Yu 326911e06f5SHongtao Yu // A return instructions is terminating, so we don't need the terminator 327911e06f5SHongtao Yu // instruction just created. 328911e06f5SHongtao Yu ThenTerm->eraseFromParent(); 329911e06f5SHongtao Yu 330911e06f5SHongtao Yu return *NewInst; 331911e06f5SHongtao Yu } 332911e06f5SHongtao Yu 333e363d2ceSMatthew Simpson // Create an if-then-else structure. The original instruction is moved into 334e363d2ceSMatthew Simpson // the "else" block, and a clone of the original instruction is placed in the 335e363d2ceSMatthew Simpson // "then" block. 3364a2d58e1SChandler Carruth Instruction *ThenTerm = nullptr; 3374a2d58e1SChandler Carruth Instruction *ElseTerm = nullptr; 338d2f1cd5dSMircea Trofin SplitBlockAndInsertIfThenElse(Cond, &CB, &ThenTerm, &ElseTerm, BranchWeights); 339cb35c5d5SMatthew Simpson BasicBlock *ThenBlock = ThenTerm->getParent(); 340cb35c5d5SMatthew Simpson BasicBlock *ElseBlock = ElseTerm->getParent(); 341cb35c5d5SMatthew Simpson BasicBlock *MergeBlock = OrigInst->getParent(); 342e363d2ceSMatthew Simpson 343e363d2ceSMatthew Simpson ThenBlock->setName("if.true.direct_targ"); 344e363d2ceSMatthew Simpson ElseBlock->setName("if.false.orig_indirect"); 345e363d2ceSMatthew Simpson MergeBlock->setName("if.end.icp"); 346e363d2ceSMatthew Simpson 347d2f1cd5dSMircea Trofin CallBase *NewInst = cast<CallBase>(OrigInst->clone()); 348e363d2ceSMatthew Simpson OrigInst->moveBefore(ElseTerm); 349e363d2ceSMatthew Simpson NewInst->insertBefore(ThenTerm); 350e363d2ceSMatthew Simpson 351e363d2ceSMatthew Simpson // If the original call site is an invoke instruction, we have extra work to 352cb35c5d5SMatthew Simpson // do since invoke instructions are terminating. We have to fix-up phi nodes 353cb35c5d5SMatthew Simpson // in the invoke's normal and unwind destinations. 354e363d2ceSMatthew Simpson if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) { 355e363d2ceSMatthew Simpson auto *NewInvoke = cast<InvokeInst>(NewInst); 356e363d2ceSMatthew Simpson 357e363d2ceSMatthew Simpson // Invoke instructions are terminating, so we don't need the terminator 358e363d2ceSMatthew Simpson // instructions that were just created. 359e363d2ceSMatthew Simpson ThenTerm->eraseFromParent(); 360e363d2ceSMatthew Simpson ElseTerm->eraseFromParent(); 361e363d2ceSMatthew Simpson 362e363d2ceSMatthew Simpson // Branch from the "merge" block to the original normal destination. 363e363d2ceSMatthew Simpson Builder.SetInsertPoint(MergeBlock); 364e363d2ceSMatthew Simpson Builder.CreateBr(OrigInvoke->getNormalDest()); 365e363d2ceSMatthew Simpson 366cb35c5d5SMatthew Simpson // Fix-up phi nodes in the original invoke's normal and unwind destinations. 367cb35c5d5SMatthew Simpson fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock); 368cb35c5d5SMatthew Simpson fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock); 369cb35c5d5SMatthew Simpson 370cb35c5d5SMatthew Simpson // Now set the normal destinations of the invoke instructions to be the 371e363d2ceSMatthew Simpson // "merge" block. 372cb35c5d5SMatthew Simpson OrigInvoke->setNormalDest(MergeBlock); 373e363d2ceSMatthew Simpson NewInvoke->setNormalDest(MergeBlock); 374e363d2ceSMatthew Simpson } 375e363d2ceSMatthew Simpson 376cb35c5d5SMatthew Simpson // Create a phi node for the returned value of the call site. 377cb35c5d5SMatthew Simpson createRetPHINode(OrigInst, NewInst, MergeBlock, Builder); 378cb35c5d5SMatthew Simpson 379d2f1cd5dSMircea Trofin return *NewInst; 380e363d2ceSMatthew Simpson } 381e363d2ceSMatthew Simpson 382e61247c0SMircea Trofin bool llvm::isLegalToPromote(const CallBase &CB, Function *Callee, 383e363d2ceSMatthew Simpson const char **FailureReason) { 384d2f1cd5dSMircea Trofin assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted"); 385e363d2ceSMatthew Simpson 3863759efc6SScott Linder auto &DL = Callee->getParent()->getDataLayout(); 3873759efc6SScott Linder 388e363d2ceSMatthew Simpson // Check the return type. The callee's return value type must be bitcast 389e363d2ceSMatthew Simpson // compatible with the call site's type. 390d2f1cd5dSMircea Trofin Type *CallRetTy = CB.getType(); 391e363d2ceSMatthew Simpson Type *FuncRetTy = Callee->getReturnType(); 392e363d2ceSMatthew Simpson if (CallRetTy != FuncRetTy) 3933759efc6SScott Linder if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) { 394e363d2ceSMatthew Simpson if (FailureReason) 395e363d2ceSMatthew Simpson *FailureReason = "Return type mismatch"; 396e363d2ceSMatthew Simpson return false; 397e363d2ceSMatthew Simpson } 398e363d2ceSMatthew Simpson 399e363d2ceSMatthew Simpson // The number of formal arguments of the callee. 400e363d2ceSMatthew Simpson unsigned NumParams = Callee->getFunctionType()->getNumParams(); 401e363d2ceSMatthew Simpson 402fc202c5fSHans Wennborg // The number of actual arguments in the call. 403fc202c5fSHans Wennborg unsigned NumArgs = CB.arg_size(); 404fc202c5fSHans Wennborg 405e363d2ceSMatthew Simpson // Check the number of arguments. The callee and call site must agree on the 406e363d2ceSMatthew Simpson // number of arguments. 407fc202c5fSHans Wennborg if (NumArgs != NumParams && !Callee->isVarArg()) { 408e363d2ceSMatthew Simpson if (FailureReason) 409e363d2ceSMatthew Simpson *FailureReason = "The number of arguments mismatch"; 410e363d2ceSMatthew Simpson return false; 411e363d2ceSMatthew Simpson } 412e363d2ceSMatthew Simpson 413e363d2ceSMatthew Simpson // Check the argument types. The callee's formal argument types must be 414e363d2ceSMatthew Simpson // bitcast compatible with the corresponding actual argument types of the call 415e363d2ceSMatthew Simpson // site. 416fc202c5fSHans Wennborg unsigned I = 0; 417fc202c5fSHans Wennborg for (; I < NumParams; ++I) { 418e363d2ceSMatthew Simpson Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I); 419d2f1cd5dSMircea Trofin Type *ActualTy = CB.getArgOperand(I)->getType(); 420e363d2ceSMatthew Simpson if (FormalTy == ActualTy) 421e363d2ceSMatthew Simpson continue; 4223759efc6SScott Linder if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) { 423e363d2ceSMatthew Simpson if (FailureReason) 424e363d2ceSMatthew Simpson *FailureReason = "Argument type mismatch"; 425e363d2ceSMatthew Simpson return false; 426e363d2ceSMatthew Simpson } 427*c19d7f8aSArthur Eubanks // Make sure that the callee and call agree on byval/inalloca. The types do 428*c19d7f8aSArthur Eubanks // not have to match. 429*c19d7f8aSArthur Eubanks 430*c19d7f8aSArthur Eubanks if (Callee->hasParamAttribute(I, Attribute::ByVal) != 431*c19d7f8aSArthur Eubanks CB.getAttributes().hasParamAttr(I, Attribute::ByVal)) { 432*c19d7f8aSArthur Eubanks if (FailureReason) 433*c19d7f8aSArthur Eubanks *FailureReason = "byval mismatch"; 434*c19d7f8aSArthur Eubanks return false; 435*c19d7f8aSArthur Eubanks } 436*c19d7f8aSArthur Eubanks if (Callee->hasParamAttribute(I, Attribute::InAlloca) != 437*c19d7f8aSArthur Eubanks CB.getAttributes().hasParamAttr(I, Attribute::InAlloca)) { 438*c19d7f8aSArthur Eubanks if (FailureReason) 439*c19d7f8aSArthur Eubanks *FailureReason = "inalloca mismatch"; 440*c19d7f8aSArthur Eubanks return false; 441*c19d7f8aSArthur Eubanks } 442e363d2ceSMatthew Simpson } 443fc202c5fSHans Wennborg for (; I < NumArgs; I++) { 44465c6ae3bSSimon Pilgrim // Vararg functions can have more arguments than parameters. 445fc202c5fSHans Wennborg assert(Callee->isVarArg()); 446fc202c5fSHans Wennborg if (CB.paramHasAttr(I, Attribute::StructRet)) { 44765c6ae3bSSimon Pilgrim if (FailureReason) 448fc202c5fSHans Wennborg *FailureReason = "SRet arg to vararg function"; 449fc202c5fSHans Wennborg return false; 450fc202c5fSHans Wennborg } 451fc202c5fSHans Wennborg } 452e363d2ceSMatthew Simpson 453e363d2ceSMatthew Simpson return true; 454e363d2ceSMatthew Simpson } 455e363d2ceSMatthew Simpson 456d2f1cd5dSMircea Trofin CallBase &llvm::promoteCall(CallBase &CB, Function *Callee, 457cb35c5d5SMatthew Simpson CastInst **RetBitCast) { 458d2f1cd5dSMircea Trofin assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted"); 459e363d2ceSMatthew Simpson 460291f791eSJames Y Knight // Set the called function of the call site to be the given callee (but don't 461291f791eSJames Y Knight // change the type). 462d2f1cd5dSMircea Trofin CB.setCalledOperand(Callee); 463e363d2ceSMatthew Simpson 464e363d2ceSMatthew Simpson // Since the call site will no longer be direct, we must clear metadata that 465e363d2ceSMatthew Simpson // is only appropriate for indirect calls. This includes !prof and !callees 466e363d2ceSMatthew Simpson // metadata. 467d2f1cd5dSMircea Trofin CB.setMetadata(LLVMContext::MD_prof, nullptr); 468d2f1cd5dSMircea Trofin CB.setMetadata(LLVMContext::MD_callees, nullptr); 469e363d2ceSMatthew Simpson 470e363d2ceSMatthew Simpson // If the function type of the call site matches that of the callee, no 471e363d2ceSMatthew Simpson // additional work is required. 472d2f1cd5dSMircea Trofin if (CB.getFunctionType() == Callee->getFunctionType()) 473d2f1cd5dSMircea Trofin return CB; 474e363d2ceSMatthew Simpson 475e363d2ceSMatthew Simpson // Save the return types of the call site and callee. 476d2f1cd5dSMircea Trofin Type *CallSiteRetTy = CB.getType(); 477e363d2ceSMatthew Simpson Type *CalleeRetTy = Callee->getReturnType(); 478e363d2ceSMatthew Simpson 479e363d2ceSMatthew Simpson // Change the function type of the call site the match that of the callee. 480d2f1cd5dSMircea Trofin CB.mutateFunctionType(Callee->getFunctionType()); 481e363d2ceSMatthew Simpson 482e363d2ceSMatthew Simpson // Inspect the arguments of the call site. If an argument's type doesn't 483e363d2ceSMatthew Simpson // match the corresponding formal argument's type in the callee, bitcast it 484e363d2ceSMatthew Simpson // to the correct type. 485923c216dSTaewook Oh auto CalleeType = Callee->getFunctionType(); 486923c216dSTaewook Oh auto CalleeParamNum = CalleeType->getNumParams(); 48704d49779SXin Tong 48804d49779SXin Tong LLVMContext &Ctx = Callee->getContext(); 489d2f1cd5dSMircea Trofin const AttributeList &CallerPAL = CB.getAttributes(); 49004d49779SXin Tong // The new list of argument attributes. 49104d49779SXin Tong SmallVector<AttributeSet, 4> NewArgAttrs; 49204d49779SXin Tong bool AttributeChanged = false; 49304d49779SXin Tong 494923c216dSTaewook Oh for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) { 495d2f1cd5dSMircea Trofin auto *Arg = CB.getArgOperand(ArgNo); 496923c216dSTaewook Oh Type *FormalTy = CalleeType->getParamType(ArgNo); 497923c216dSTaewook Oh Type *ActualTy = Arg->getType(); 498e363d2ceSMatthew Simpson if (FormalTy != ActualTy) { 499d2f1cd5dSMircea Trofin auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "", &CB); 500d2f1cd5dSMircea Trofin CB.setArgOperand(ArgNo, Cast); 50104d49779SXin Tong 50204d49779SXin Tong // Remove any incompatible attributes for the argument. 50380ea2bb5SArthur Eubanks AttrBuilder ArgAttrs(CallerPAL.getParamAttrs(ArgNo)); 50404d49779SXin Tong ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy)); 505d7216394SReid Kleckner 506*c19d7f8aSArthur Eubanks // We may have a different byval/inalloca type. 507e4f66a10SArthur Eubanks if (ArgAttrs.getByValType()) 508e4f66a10SArthur Eubanks ArgAttrs.addByValAttr(Callee->getParamByValType(ArgNo)); 509*c19d7f8aSArthur Eubanks if (ArgAttrs.getInAllocaType()) 510*c19d7f8aSArthur Eubanks ArgAttrs.addInAllocaAttr(Callee->getParamInAllocaType(ArgNo)); 511d7216394SReid Kleckner 51204d49779SXin Tong NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs)); 51304d49779SXin Tong AttributeChanged = true; 51404d49779SXin Tong } else 51580ea2bb5SArthur Eubanks NewArgAttrs.push_back(CallerPAL.getParamAttrs(ArgNo)); 516e363d2ceSMatthew Simpson } 517e363d2ceSMatthew Simpson 518e363d2ceSMatthew Simpson // If the return type of the call site doesn't match that of the callee, cast 519e363d2ceSMatthew Simpson // the returned value to the appropriate type. 52004d49779SXin Tong // Remove any incompatible return value attribute. 52104d49779SXin Tong AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex); 52204d49779SXin Tong if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) { 523d2f1cd5dSMircea Trofin createRetBitCast(CB, CallSiteRetTy, RetBitCast); 52404d49779SXin Tong RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy)); 52504d49779SXin Tong AttributeChanged = true; 52604d49779SXin Tong } 52704d49779SXin Tong 52804d49779SXin Tong // Set the new callsite attribute. 52904d49779SXin Tong if (AttributeChanged) 53080ea2bb5SArthur Eubanks CB.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttrs(), 53104d49779SXin Tong AttributeSet::get(Ctx, RAttrs), 53204d49779SXin Tong NewArgAttrs)); 533cb35c5d5SMatthew Simpson 534d2f1cd5dSMircea Trofin return CB; 535e363d2ceSMatthew Simpson } 536e363d2ceSMatthew Simpson 537d2f1cd5dSMircea Trofin CallBase &llvm::promoteCallWithIfThenElse(CallBase &CB, Function *Callee, 538e363d2ceSMatthew Simpson MDNode *BranchWeights) { 539e363d2ceSMatthew Simpson 540e363d2ceSMatthew Simpson // Version the indirect call site. If the called value is equal to the given 541e363d2ceSMatthew Simpson // callee, 'NewInst' will be executed, otherwise the original call site will 542e363d2ceSMatthew Simpson // be executed. 543d2f1cd5dSMircea Trofin CallBase &NewInst = versionCallSite(CB, Callee, BranchWeights); 544e363d2ceSMatthew Simpson 545e363d2ceSMatthew Simpson // Promote 'NewInst' so that it directly calls the desired function. 546d2f1cd5dSMircea Trofin return promoteCall(NewInst, Callee); 547e363d2ceSMatthew Simpson } 548e363d2ceSMatthew Simpson 549d2f1cd5dSMircea Trofin bool llvm::tryPromoteCall(CallBase &CB) { 550d2f1cd5dSMircea Trofin assert(!CB.getCalledFunction()); 551d2f1cd5dSMircea Trofin Module *M = CB.getCaller()->getParent(); 552bb383ae6SHiroshi Yamauchi const DataLayout &DL = M->getDataLayout(); 553a58b62b4SCraig Topper Value *Callee = CB.getCalledOperand(); 554bb383ae6SHiroshi Yamauchi 555bb383ae6SHiroshi Yamauchi LoadInst *VTableEntryLoad = dyn_cast<LoadInst>(Callee); 556bb383ae6SHiroshi Yamauchi if (!VTableEntryLoad) 557bb383ae6SHiroshi Yamauchi return false; // Not a vtable entry load. 558bb383ae6SHiroshi Yamauchi Value *VTableEntryPtr = VTableEntryLoad->getPointerOperand(); 559bb383ae6SHiroshi Yamauchi APInt VTableOffset(DL.getTypeSizeInBits(VTableEntryPtr->getType()), 0); 560bb383ae6SHiroshi Yamauchi Value *VTableBasePtr = VTableEntryPtr->stripAndAccumulateConstantOffsets( 561bb383ae6SHiroshi Yamauchi DL, VTableOffset, /* AllowNonInbounds */ true); 562bb383ae6SHiroshi Yamauchi LoadInst *VTablePtrLoad = dyn_cast<LoadInst>(VTableBasePtr); 563bb383ae6SHiroshi Yamauchi if (!VTablePtrLoad) 564bb383ae6SHiroshi Yamauchi return false; // Not a vtable load. 565bb383ae6SHiroshi Yamauchi Value *Object = VTablePtrLoad->getPointerOperand(); 566bb383ae6SHiroshi Yamauchi APInt ObjectOffset(DL.getTypeSizeInBits(Object->getType()), 0); 567bb383ae6SHiroshi Yamauchi Value *ObjectBase = Object->stripAndAccumulateConstantOffsets( 568bb383ae6SHiroshi Yamauchi DL, ObjectOffset, /* AllowNonInbounds */ true); 569bb383ae6SHiroshi Yamauchi if (!(isa<AllocaInst>(ObjectBase) && ObjectOffset == 0)) 570bb383ae6SHiroshi Yamauchi // Not an Alloca or the offset isn't zero. 571bb383ae6SHiroshi Yamauchi return false; 572bb383ae6SHiroshi Yamauchi 573bb383ae6SHiroshi Yamauchi // Look for the vtable pointer store into the object by the ctor. 574bb383ae6SHiroshi Yamauchi BasicBlock::iterator BBI(VTablePtrLoad); 575bb383ae6SHiroshi Yamauchi Value *VTablePtr = FindAvailableLoadedValue( 576bb383ae6SHiroshi Yamauchi VTablePtrLoad, VTablePtrLoad->getParent(), BBI, 0, nullptr, nullptr); 577bb383ae6SHiroshi Yamauchi if (!VTablePtr) 578bb383ae6SHiroshi Yamauchi return false; // No vtable found. 579bb383ae6SHiroshi Yamauchi APInt VTableOffsetGVBase(DL.getTypeSizeInBits(VTablePtr->getType()), 0); 580bb383ae6SHiroshi Yamauchi Value *VTableGVBase = VTablePtr->stripAndAccumulateConstantOffsets( 581bb383ae6SHiroshi Yamauchi DL, VTableOffsetGVBase, /* AllowNonInbounds */ true); 582bb383ae6SHiroshi Yamauchi GlobalVariable *GV = dyn_cast<GlobalVariable>(VTableGVBase); 583bb383ae6SHiroshi Yamauchi if (!(GV && GV->isConstant() && GV->hasDefinitiveInitializer())) 584bb383ae6SHiroshi Yamauchi // Not in the form of a global constant variable with an initializer. 585bb383ae6SHiroshi Yamauchi return false; 586bb383ae6SHiroshi Yamauchi 587bb383ae6SHiroshi Yamauchi Constant *VTableGVInitializer = GV->getInitializer(); 588bb383ae6SHiroshi Yamauchi APInt VTableGVOffset = VTableOffsetGVBase + VTableOffset; 589bb383ae6SHiroshi Yamauchi if (!(VTableGVOffset.getActiveBits() <= 64)) 590bb383ae6SHiroshi Yamauchi return false; // Out of range. 591bb383ae6SHiroshi Yamauchi Constant *Ptr = getPointerAtOffset(VTableGVInitializer, 592bb383ae6SHiroshi Yamauchi VTableGVOffset.getZExtValue(), 593bb383ae6SHiroshi Yamauchi *M); 594bb383ae6SHiroshi Yamauchi if (!Ptr) 595bb383ae6SHiroshi Yamauchi return false; // No constant (function) pointer found. 596bb383ae6SHiroshi Yamauchi Function *DirectCallee = dyn_cast<Function>(Ptr->stripPointerCasts()); 597bb383ae6SHiroshi Yamauchi if (!DirectCallee) 598bb383ae6SHiroshi Yamauchi return false; // No function pointer found. 599bb383ae6SHiroshi Yamauchi 600d2f1cd5dSMircea Trofin if (!isLegalToPromote(CB, DirectCallee)) 60141e06ae7SHiroshi Yamauchi return false; 60241e06ae7SHiroshi Yamauchi 603bb383ae6SHiroshi Yamauchi // Success. 604d2f1cd5dSMircea Trofin promoteCall(CB, DirectCallee); 605bb383ae6SHiroshi Yamauchi return true; 606bb383ae6SHiroshi Yamauchi } 607bb383ae6SHiroshi Yamauchi 608e363d2ceSMatthew Simpson #undef DEBUG_TYPE 609