11b637458SDan Gohman //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===// 21b637458SDan Gohman // 31b637458SDan Gohman // The LLVM Compiler Infrastructure 41b637458SDan Gohman // 51b637458SDan Gohman // This file is distributed under the University of Illinois Open Source 61b637458SDan Gohman // License. See LICENSE.TXT for details. 71b637458SDan Gohman // 81b637458SDan Gohman //===----------------------------------------------------------------------===// 91b637458SDan Gohman /// 101b637458SDan Gohman /// \file 115f8f34e4SAdrian Prantl /// Fix bitcasted functions. 121b637458SDan Gohman /// 131b637458SDan Gohman /// WebAssembly requires caller and callee signatures to match, however in LLVM, 141b637458SDan Gohman /// some amount of slop is vaguely permitted. Detect mismatch by looking for 151b637458SDan Gohman /// bitcasts of functions and rewrite them to use wrapper functions instead. 161b637458SDan Gohman /// 171b637458SDan Gohman /// This doesn't catch all cases, such as when a function's address is taken in 181b637458SDan Gohman /// one place and casted in another, but it works for many common cases. 191b637458SDan Gohman /// 201b637458SDan Gohman /// Note that LLVM already optimizes away function bitcasts in common cases by 211b637458SDan Gohman /// dropping arguments as needed, so this pass only ends up getting used in less 221b637458SDan Gohman /// common cases. 231b637458SDan Gohman /// 241b637458SDan Gohman //===----------------------------------------------------------------------===// 251b637458SDan Gohman 261b637458SDan Gohman #include "WebAssembly.h" 2737af00e7SJacob Gravelle #include "llvm/IR/CallSite.h" 281b637458SDan Gohman #include "llvm/IR/Constants.h" 291b637458SDan Gohman #include "llvm/IR/Instructions.h" 301b637458SDan Gohman #include "llvm/IR/Module.h" 311b637458SDan Gohman #include "llvm/IR/Operator.h" 321b637458SDan Gohman #include "llvm/Pass.h" 331b637458SDan Gohman #include "llvm/Support/Debug.h" 341b637458SDan Gohman #include "llvm/Support/raw_ostream.h" 351b637458SDan Gohman using namespace llvm; 361b637458SDan Gohman 371b637458SDan Gohman #define DEBUG_TYPE "wasm-fix-function-bitcasts" 381b637458SDan Gohman 396736f590SDan Gohman static cl::opt<bool> TemporaryWorkarounds( 406736f590SDan Gohman "wasm-temporary-workarounds", 416736f590SDan Gohman cl::desc("Apply certain temporary workarounds"), 426736f590SDan Gohman cl::init(true), cl::Hidden); 436736f590SDan Gohman 441b637458SDan Gohman namespace { 451b637458SDan Gohman class FixFunctionBitcasts final : public ModulePass { 461b637458SDan Gohman StringRef getPassName() const override { 471b637458SDan Gohman return "WebAssembly Fix Function Bitcasts"; 481b637458SDan Gohman } 491b637458SDan Gohman 501b637458SDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 511b637458SDan Gohman AU.setPreservesCFG(); 521b637458SDan Gohman ModulePass::getAnalysisUsage(AU); 531b637458SDan Gohman } 541b637458SDan Gohman 551b637458SDan Gohman bool runOnModule(Module &M) override; 561b637458SDan Gohman 571b637458SDan Gohman public: 581b637458SDan Gohman static char ID; 591b637458SDan Gohman FixFunctionBitcasts() : ModulePass(ID) {} 601b637458SDan Gohman }; 611b637458SDan Gohman } // End anonymous namespace 621b637458SDan Gohman 631b637458SDan Gohman char FixFunctionBitcasts::ID = 0; 6440926451SJacob Gravelle INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE, 6540926451SJacob Gravelle "Fix mismatching bitcasts for WebAssembly", false, false) 6640926451SJacob Gravelle 671b637458SDan Gohman ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() { 681b637458SDan Gohman return new FixFunctionBitcasts(); 691b637458SDan Gohman } 701b637458SDan Gohman 711b637458SDan Gohman // Recursively descend the def-use lists from V to find non-bitcast users of 721b637458SDan Gohman // bitcasts of V. 731b637458SDan Gohman static void FindUses(Value *V, Function &F, 747acb42a4SDerek Schuff SmallVectorImpl<std::pair<Use *, Function *>> &Uses, 757acb42a4SDerek Schuff SmallPtrSetImpl<Constant *> &ConstantBCs) { 761b637458SDan Gohman for (Use &U : V->uses()) { 771b637458SDan Gohman if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser())) 787acb42a4SDerek Schuff FindUses(BC, F, Uses, ConstantBCs); 797acb42a4SDerek Schuff else if (U.get()->getType() != F.getType()) { 8037af00e7SJacob Gravelle CallSite CS(U.getUser()); 8137af00e7SJacob Gravelle if (!CS) 8237af00e7SJacob Gravelle // Skip uses that aren't immediately called 8337af00e7SJacob Gravelle continue; 8437af00e7SJacob Gravelle Value *Callee = CS.getCalledValue(); 8537af00e7SJacob Gravelle if (Callee != V) 8637af00e7SJacob Gravelle // Skip calls where the function isn't the callee 8737af00e7SJacob Gravelle continue; 887acb42a4SDerek Schuff if (isa<Constant>(U.get())) { 897acb42a4SDerek Schuff // Only add constant bitcasts to the list once; they get RAUW'd 907acb42a4SDerek Schuff auto c = ConstantBCs.insert(cast<Constant>(U.get())); 9137af00e7SJacob Gravelle if (!c.second) 9237af00e7SJacob Gravelle continue; 937acb42a4SDerek Schuff } 941b637458SDan Gohman Uses.push_back(std::make_pair(&U, &F)); 951b637458SDan Gohman } 961b637458SDan Gohman } 977acb42a4SDerek Schuff } 981b637458SDan Gohman 991b637458SDan Gohman // Create a wrapper function with type Ty that calls F (which may have a 1001b637458SDan Gohman // different type). Attempt to support common bitcasted function idioms: 1011b637458SDan Gohman // - Call with more arguments than needed: arguments are dropped 1021b637458SDan Gohman // - Call with fewer arguments than needed: arguments are filled in with undef 1031b637458SDan Gohman // - Return value is not needed: drop it 1041b637458SDan Gohman // - Return value needed but not present: supply an undef 1050e2ceb81SDan Gohman // 106*41d7047dSSam Clegg // If the all the argument types of trivially castable to one another (i.e. 107*41d7047dSSam Clegg // I32 vs pointer type) then we don't create a wrapper at all (return nullptr 108*41d7047dSSam Clegg // instead). 109*41d7047dSSam Clegg // 110*41d7047dSSam Clegg // If there is a type mismatch that would result in an invalid wasm module 111*41d7047dSSam Clegg // being written then generate wrapper that contains unreachable (i.e. abort 112*41d7047dSSam Clegg // at runtime). Such programs are deep into undefined behaviour territory, 113*41d7047dSSam Clegg // but we choose to fail at runtime rather than generate and invalid module 114*41d7047dSSam Clegg // or fail at compiler time. The reason we delay the error is that we want 115*41d7047dSSam Clegg // to support the CMake which expects to be able to compile and link programs 116*41d7047dSSam Clegg // that refer to functions with entirely incorrect signatures (this is how 117*41d7047dSSam Clegg // CMake detects the existence of a function in a toolchain). 1181b637458SDan Gohman static Function *CreateWrapper(Function *F, FunctionType *Ty) { 1191b637458SDan Gohman Module *M = F->getParent(); 1201b637458SDan Gohman 121*41d7047dSSam Clegg Function *Wrapper = Function::Create(Ty, Function::PrivateLinkage, 122*41d7047dSSam Clegg F->getName() + "_bitcast", M); 1231b637458SDan Gohman BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper); 124*41d7047dSSam Clegg const DataLayout &DL = BB->getModule()->getDataLayout(); 1251b637458SDan Gohman 1261b637458SDan Gohman // Determine what arguments to pass. 1271b637458SDan Gohman SmallVector<Value *, 4> Args; 1281b637458SDan Gohman Function::arg_iterator AI = Wrapper->arg_begin(); 1292803bfafSDan Gohman Function::arg_iterator AE = Wrapper->arg_end(); 1301b637458SDan Gohman FunctionType::param_iterator PI = F->getFunctionType()->param_begin(); 1311b637458SDan Gohman FunctionType::param_iterator PE = F->getFunctionType()->param_end(); 132*41d7047dSSam Clegg bool TypeMismatch = false; 133*41d7047dSSam Clegg bool WrapperNeeded = false; 134*41d7047dSSam Clegg 135*41d7047dSSam Clegg if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) || 136*41d7047dSSam Clegg (F->getFunctionType()->isVarArg() != Ty->isVarArg())) 137*41d7047dSSam Clegg WrapperNeeded = true; 138*41d7047dSSam Clegg 1392803bfafSDan Gohman for (; AI != AE && PI != PE; ++AI, ++PI) { 140*41d7047dSSam Clegg Type *ArgType = AI->getType(); 141*41d7047dSSam Clegg Type *ParamType = *PI; 142*41d7047dSSam Clegg 143*41d7047dSSam Clegg if (ArgType == ParamType) { 1441b637458SDan Gohman Args.push_back(&*AI); 145*41d7047dSSam Clegg } else { 146*41d7047dSSam Clegg if (CastInst::isBitOrNoopPointerCastable(ArgType, ParamType, DL)) { 147*41d7047dSSam Clegg Instruction *PtrCast = 148*41d7047dSSam Clegg CastInst::CreateBitOrPointerCast(AI, ParamType, "cast"); 149*41d7047dSSam Clegg BB->getInstList().push_back(PtrCast); 150*41d7047dSSam Clegg Args.push_back(PtrCast); 151*41d7047dSSam Clegg } else { 152*41d7047dSSam Clegg LLVM_DEBUG(dbgs() << "CreateWrapper: arg type mismatch calling: " 153*41d7047dSSam Clegg << F->getName() << "\n"); 154*41d7047dSSam Clegg LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: " 155*41d7047dSSam Clegg << *ParamType << " Got: " << *ArgType << "\n"); 156*41d7047dSSam Clegg TypeMismatch = true; 157*41d7047dSSam Clegg break; 1581b637458SDan Gohman } 159*41d7047dSSam Clegg } 160*41d7047dSSam Clegg } 161*41d7047dSSam Clegg 162*41d7047dSSam Clegg if (!TypeMismatch) { 1631b637458SDan Gohman for (; PI != PE; ++PI) 1641b637458SDan Gohman Args.push_back(UndefValue::get(*PI)); 1652803bfafSDan Gohman if (F->isVarArg()) 1662803bfafSDan Gohman for (; AI != AE; ++AI) 1672803bfafSDan Gohman Args.push_back(&*AI); 1681b637458SDan Gohman 1691b637458SDan Gohman CallInst *Call = CallInst::Create(F, Args, "", BB); 1701b637458SDan Gohman 171*41d7047dSSam Clegg Type *ExpectedRtnType = F->getFunctionType()->getReturnType(); 172*41d7047dSSam Clegg Type *RtnType = Ty->getReturnType(); 1731b637458SDan Gohman // Determine what value to return. 174*41d7047dSSam Clegg if (RtnType->isVoidTy()) { 1751b637458SDan Gohman ReturnInst::Create(M->getContext(), BB); 176*41d7047dSSam Clegg WrapperNeeded = true; 177*41d7047dSSam Clegg } else if (ExpectedRtnType->isVoidTy()) { 178*41d7047dSSam Clegg ReturnInst::Create(M->getContext(), UndefValue::get(RtnType), BB); 179*41d7047dSSam Clegg WrapperNeeded = true; 180*41d7047dSSam Clegg } else if (RtnType == ExpectedRtnType) { 1811b637458SDan Gohman ReturnInst::Create(M->getContext(), Call, BB); 182*41d7047dSSam Clegg } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType, 183*41d7047dSSam Clegg DL)) { 184*41d7047dSSam Clegg Instruction *Cast = 185*41d7047dSSam Clegg CastInst::CreateBitOrPointerCast(Call, RtnType, "cast"); 186*41d7047dSSam Clegg BB->getInstList().push_back(Cast); 187*41d7047dSSam Clegg ReturnInst::Create(M->getContext(), Cast, BB); 188*41d7047dSSam Clegg } else { 189*41d7047dSSam Clegg LLVM_DEBUG(dbgs() << "CreateWrapper: return type mismatch calling: " 190*41d7047dSSam Clegg << F->getName() << "\n"); 191*41d7047dSSam Clegg LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType 192*41d7047dSSam Clegg << " Got: " << *RtnType << "\n"); 193*41d7047dSSam Clegg TypeMismatch = true; 194*41d7047dSSam Clegg } 195*41d7047dSSam Clegg } 196*41d7047dSSam Clegg 197*41d7047dSSam Clegg if (TypeMismatch) { 198*41d7047dSSam Clegg new UnreachableInst(M->getContext(), BB); 199*41d7047dSSam Clegg Wrapper->setName(F->getName() + "_bitcast_invalid"); 200*41d7047dSSam Clegg } else if (!WrapperNeeded) { 201*41d7047dSSam Clegg LLVM_DEBUG(dbgs() << "CreateWrapper: no wrapper needed: " << F->getName() 202*41d7047dSSam Clegg << "\n"); 2030e2ceb81SDan Gohman Wrapper->eraseFromParent(); 2040e2ceb81SDan Gohman return nullptr; 2050e2ceb81SDan Gohman } 2061b637458SDan Gohman return Wrapper; 2071b637458SDan Gohman } 2081b637458SDan Gohman 2091b637458SDan Gohman bool FixFunctionBitcasts::runOnModule(Module &M) { 2106736f590SDan Gohman Function *Main = nullptr; 2116736f590SDan Gohman CallInst *CallMain = nullptr; 212d5eda355SDan Gohman SmallVector<std::pair<Use *, Function *>, 0> Uses; 2137acb42a4SDerek Schuff SmallPtrSet<Constant *, 2> ConstantBCs; 214d5eda355SDan Gohman 2151b637458SDan Gohman // Collect all the places that need wrappers. 2166736f590SDan Gohman for (Function &F : M) { 2176736f590SDan Gohman FindUses(&F, F, Uses, ConstantBCs); 2186736f590SDan Gohman 2196736f590SDan Gohman // If we have a "main" function, and its type isn't 2206736f590SDan Gohman // "int main(int argc, char *argv[])", create an artificial call with it 2216736f590SDan Gohman // bitcasted to that type so that we generate a wrapper for it, so that 2226736f590SDan Gohman // the C runtime can call it. 2236736f590SDan Gohman if (!TemporaryWorkarounds && !F.isDeclaration() && F.getName() == "main") { 2246736f590SDan Gohman Main = &F; 2256736f590SDan Gohman LLVMContext &C = M.getContext(); 2266736f590SDan Gohman Type *MainArgTys[] = { 2276736f590SDan Gohman PointerType::get(Type::getInt8PtrTy(C), 0), 2286736f590SDan Gohman Type::getInt32Ty(C) 2296736f590SDan Gohman }; 2306736f590SDan Gohman FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys, 2316736f590SDan Gohman /*isVarArg=*/false); 2326736f590SDan Gohman if (F.getFunctionType() != MainTy) { 2336736f590SDan Gohman Value *Args[] = { 2346736f590SDan Gohman UndefValue::get(MainArgTys[0]), 2356736f590SDan Gohman UndefValue::get(MainArgTys[1]) 2366736f590SDan Gohman }; 2376736f590SDan Gohman Value *Casted = ConstantExpr::getBitCast(Main, 2386736f590SDan Gohman PointerType::get(MainTy, 0)); 2396736f590SDan Gohman CallMain = CallInst::Create(Casted, Args, "call_main"); 2406736f590SDan Gohman Use *UseMain = &CallMain->getOperandUse(2); 2416736f590SDan Gohman Uses.push_back(std::make_pair(UseMain, &F)); 2426736f590SDan Gohman } 2436736f590SDan Gohman } 2446736f590SDan Gohman } 2451b637458SDan Gohman 2461b637458SDan Gohman DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers; 2471b637458SDan Gohman 2481b637458SDan Gohman for (auto &UseFunc : Uses) { 2491b637458SDan Gohman Use *U = UseFunc.first; 2501b637458SDan Gohman Function *F = UseFunc.second; 2511b637458SDan Gohman PointerType *PTy = cast<PointerType>(U->get()->getType()); 2521b637458SDan Gohman FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType()); 2531b637458SDan Gohman 2541b637458SDan Gohman // If the function is casted to something like i8* as a "generic pointer" 2551b637458SDan Gohman // to be later casted to something else, we can't generate a wrapper for it. 2561b637458SDan Gohman // Just ignore such casts for now. 2571b637458SDan Gohman if (!Ty) 2581b637458SDan Gohman continue; 2591b637458SDan Gohman 26078c19d60SDan Gohman // Bitcasted vararg functions occur in Emscripten's implementation of 26178c19d60SDan Gohman // EM_ASM, so suppress wrappers for them for now. 2623a762bf9SDan Gohman if (TemporaryWorkarounds && (Ty->isVarArg() || F->isVarArg())) 26378c19d60SDan Gohman continue; 26478c19d60SDan Gohman 2651b637458SDan Gohman auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr)); 2661b637458SDan Gohman if (Pair.second) 2671b637458SDan Gohman Pair.first->second = CreateWrapper(F, Ty); 2681b637458SDan Gohman 2690e2ceb81SDan Gohman Function *Wrapper = Pair.first->second; 2700e2ceb81SDan Gohman if (!Wrapper) 2710e2ceb81SDan Gohman continue; 2720e2ceb81SDan Gohman 2731b637458SDan Gohman if (isa<Constant>(U->get())) 2740e2ceb81SDan Gohman U->get()->replaceAllUsesWith(Wrapper); 2751b637458SDan Gohman else 2760e2ceb81SDan Gohman U->set(Wrapper); 2771b637458SDan Gohman } 2781b637458SDan Gohman 2796736f590SDan Gohman // If we created a wrapper for main, rename the wrapper so that it's the 2806736f590SDan Gohman // one that gets called from startup. 2816736f590SDan Gohman if (CallMain) { 2826736f590SDan Gohman Main->setName("__original_main"); 2836736f590SDan Gohman Function *MainWrapper = 2846736f590SDan Gohman cast<Function>(CallMain->getCalledValue()->stripPointerCasts()); 2856736f590SDan Gohman MainWrapper->setName("main"); 2866736f590SDan Gohman MainWrapper->setLinkage(Main->getLinkage()); 2876736f590SDan Gohman MainWrapper->setVisibility(Main->getVisibility()); 2886736f590SDan Gohman Main->setLinkage(Function::PrivateLinkage); 2896736f590SDan Gohman Main->setVisibility(Function::DefaultVisibility); 2906736f590SDan Gohman delete CallMain; 2916736f590SDan Gohman } 2926736f590SDan Gohman 2931b637458SDan Gohman return true; 2941b637458SDan Gohman } 295