1 //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===// 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 /// \file 10 /// Fix bitcasted functions. 11 /// 12 /// WebAssembly requires caller and callee signatures to match, however in LLVM, 13 /// some amount of slop is vaguely permitted. Detect mismatch by looking for 14 /// bitcasts of functions and rewrite them to use wrapper functions instead. 15 /// 16 /// This doesn't catch all cases, such as when a function's address is taken in 17 /// one place and casted in another, but it works for many common cases. 18 /// 19 /// Note that LLVM already optimizes away function bitcasts in common cases by 20 /// dropping arguments as needed, so this pass only ends up getting used in less 21 /// common cases. 22 /// 23 //===----------------------------------------------------------------------===// 24 25 #include "WebAssembly.h" 26 #include "llvm/IR/CallSite.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/Operator.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 using namespace llvm; 35 36 #define DEBUG_TYPE "wasm-fix-function-bitcasts" 37 38 static cl::opt<bool> 39 TemporaryWorkarounds("wasm-temporary-workarounds", 40 cl::desc("Apply certain temporary workarounds"), 41 cl::init(true), cl::Hidden); 42 43 namespace { 44 class FixFunctionBitcasts final : public ModulePass { 45 StringRef getPassName() const override { 46 return "WebAssembly Fix Function Bitcasts"; 47 } 48 49 void getAnalysisUsage(AnalysisUsage &AU) const override { 50 AU.setPreservesCFG(); 51 ModulePass::getAnalysisUsage(AU); 52 } 53 54 bool runOnModule(Module &M) override; 55 56 public: 57 static char ID; 58 FixFunctionBitcasts() : ModulePass(ID) {} 59 }; 60 } // End anonymous namespace 61 62 char FixFunctionBitcasts::ID = 0; 63 INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE, 64 "Fix mismatching bitcasts for WebAssembly", false, false) 65 66 ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() { 67 return new FixFunctionBitcasts(); 68 } 69 70 // Recursively descend the def-use lists from V to find non-bitcast users of 71 // bitcasts of V. 72 static void FindUses(Value *V, Function &F, 73 SmallVectorImpl<std::pair<Use *, Function *>> &Uses, 74 SmallPtrSetImpl<Constant *> &ConstantBCs) { 75 for (Use &U : V->uses()) { 76 if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser())) 77 FindUses(BC, F, Uses, ConstantBCs); 78 else if (U.get()->getType() != F.getType()) { 79 CallSite CS(U.getUser()); 80 if (!CS) 81 // Skip uses that aren't immediately called 82 continue; 83 Value *Callee = CS.getCalledValue(); 84 if (Callee != V) 85 // Skip calls where the function isn't the callee 86 continue; 87 if (isa<Constant>(U.get())) { 88 // Only add constant bitcasts to the list once; they get RAUW'd 89 auto c = ConstantBCs.insert(cast<Constant>(U.get())); 90 if (!c.second) 91 continue; 92 } 93 Uses.push_back(std::make_pair(&U, &F)); 94 } 95 } 96 } 97 98 // Create a wrapper function with type Ty that calls F (which may have a 99 // different type). Attempt to support common bitcasted function idioms: 100 // - Call with more arguments than needed: arguments are dropped 101 // - Call with fewer arguments than needed: arguments are filled in with undef 102 // - Return value is not needed: drop it 103 // - Return value needed but not present: supply an undef 104 // 105 // If the all the argument types of trivially castable to one another (i.e. 106 // I32 vs pointer type) then we don't create a wrapper at all (return nullptr 107 // instead). 108 // 109 // If there is a type mismatch that we know would result in an invalid wasm 110 // module then generate wrapper that contains unreachable (i.e. abort at 111 // runtime). Such programs are deep into undefined behaviour territory, 112 // but we choose to fail at runtime rather than generate and invalid module 113 // or fail at compiler time. The reason we delay the error is that we want 114 // to support the CMake which expects to be able to compile and link programs 115 // that refer to functions with entirely incorrect signatures (this is how 116 // CMake detects the existence of a function in a toolchain). 117 // 118 // For bitcasts that involve struct types we don't know at this stage if they 119 // would be equivalent at the wasm level and so we can't know if we need to 120 // generate a wrapper. 121 static Function *CreateWrapper(Function *F, FunctionType *Ty) { 122 Module *M = F->getParent(); 123 124 Function *Wrapper = Function::Create(Ty, Function::PrivateLinkage, 125 F->getName() + "_bitcast", M); 126 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper); 127 const DataLayout &DL = BB->getModule()->getDataLayout(); 128 129 // Determine what arguments to pass. 130 SmallVector<Value *, 4> Args; 131 Function::arg_iterator AI = Wrapper->arg_begin(); 132 Function::arg_iterator AE = Wrapper->arg_end(); 133 FunctionType::param_iterator PI = F->getFunctionType()->param_begin(); 134 FunctionType::param_iterator PE = F->getFunctionType()->param_end(); 135 bool TypeMismatch = false; 136 bool WrapperNeeded = false; 137 138 Type *ExpectedRtnType = F->getFunctionType()->getReturnType(); 139 Type *RtnType = Ty->getReturnType(); 140 141 if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) || 142 (F->getFunctionType()->isVarArg() != Ty->isVarArg()) || 143 (ExpectedRtnType != RtnType)) 144 WrapperNeeded = true; 145 146 for (; AI != AE && PI != PE; ++AI, ++PI) { 147 Type *ArgType = AI->getType(); 148 Type *ParamType = *PI; 149 150 if (ArgType == ParamType) { 151 Args.push_back(&*AI); 152 } else { 153 if (CastInst::isBitOrNoopPointerCastable(ArgType, ParamType, DL)) { 154 Instruction *PtrCast = 155 CastInst::CreateBitOrPointerCast(AI, ParamType, "cast"); 156 BB->getInstList().push_back(PtrCast); 157 Args.push_back(PtrCast); 158 } else if (ArgType->isStructTy() || ParamType->isStructTy()) { 159 LLVM_DEBUG(dbgs() << "CreateWrapper: struct param type in bitcast: " 160 << F->getName() << "\n"); 161 WrapperNeeded = false; 162 } else { 163 LLVM_DEBUG(dbgs() << "CreateWrapper: arg type mismatch calling: " 164 << F->getName() << "\n"); 165 LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: " 166 << *ParamType << " Got: " << *ArgType << "\n"); 167 TypeMismatch = true; 168 break; 169 } 170 } 171 } 172 173 if (WrapperNeeded && !TypeMismatch) { 174 for (; PI != PE; ++PI) 175 Args.push_back(UndefValue::get(*PI)); 176 if (F->isVarArg()) 177 for (; AI != AE; ++AI) 178 Args.push_back(&*AI); 179 180 CallInst *Call = CallInst::Create(F, Args, "", BB); 181 182 Type *ExpectedRtnType = F->getFunctionType()->getReturnType(); 183 Type *RtnType = Ty->getReturnType(); 184 // Determine what value to return. 185 if (RtnType->isVoidTy()) { 186 ReturnInst::Create(M->getContext(), BB); 187 } else if (ExpectedRtnType->isVoidTy()) { 188 LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n"); 189 ReturnInst::Create(M->getContext(), UndefValue::get(RtnType), BB); 190 } else if (RtnType == ExpectedRtnType) { 191 ReturnInst::Create(M->getContext(), Call, BB); 192 } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType, 193 DL)) { 194 Instruction *Cast = 195 CastInst::CreateBitOrPointerCast(Call, RtnType, "cast"); 196 BB->getInstList().push_back(Cast); 197 ReturnInst::Create(M->getContext(), Cast, BB); 198 } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) { 199 LLVM_DEBUG(dbgs() << "CreateWrapper: struct return type in bitcast: " 200 << F->getName() << "\n"); 201 WrapperNeeded = false; 202 } else { 203 LLVM_DEBUG(dbgs() << "CreateWrapper: return type mismatch calling: " 204 << F->getName() << "\n"); 205 LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType 206 << " Got: " << *RtnType << "\n"); 207 TypeMismatch = true; 208 } 209 } 210 211 if (TypeMismatch) { 212 // Create a new wrapper that simply contains `unreachable`. 213 Wrapper->eraseFromParent(); 214 Wrapper = Function::Create(Ty, Function::PrivateLinkage, 215 F->getName() + "_bitcast_invalid", M); 216 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper); 217 new UnreachableInst(M->getContext(), BB); 218 Wrapper->setName(F->getName() + "_bitcast_invalid"); 219 } else if (!WrapperNeeded) { 220 LLVM_DEBUG(dbgs() << "CreateWrapper: no wrapper needed: " << F->getName() 221 << "\n"); 222 Wrapper->eraseFromParent(); 223 return nullptr; 224 } 225 LLVM_DEBUG(dbgs() << "CreateWrapper: " << F->getName() << "\n"); 226 return Wrapper; 227 } 228 229 bool FixFunctionBitcasts::runOnModule(Module &M) { 230 LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n"); 231 232 Function *Main = nullptr; 233 CallInst *CallMain = nullptr; 234 SmallVector<std::pair<Use *, Function *>, 0> Uses; 235 SmallPtrSet<Constant *, 2> ConstantBCs; 236 237 // Collect all the places that need wrappers. 238 for (Function &F : M) { 239 FindUses(&F, F, Uses, ConstantBCs); 240 241 // If we have a "main" function, and its type isn't 242 // "int main(int argc, char *argv[])", create an artificial call with it 243 // bitcasted to that type so that we generate a wrapper for it, so that 244 // the C runtime can call it. 245 if (!TemporaryWorkarounds && !F.isDeclaration() && F.getName() == "main") { 246 Main = &F; 247 LLVMContext &C = M.getContext(); 248 Type *MainArgTys[] = {Type::getInt32Ty(C), 249 PointerType::get(Type::getInt8PtrTy(C), 0)}; 250 FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys, 251 /*isVarArg=*/false); 252 if (F.getFunctionType() != MainTy) { 253 LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: " 254 << *F.getFunctionType() << "\n"); 255 Value *Args[] = {UndefValue::get(MainArgTys[0]), 256 UndefValue::get(MainArgTys[1])}; 257 Value *Casted = 258 ConstantExpr::getBitCast(Main, PointerType::get(MainTy, 0)); 259 CallMain = CallInst::Create(Casted, Args, "call_main"); 260 Use *UseMain = &CallMain->getOperandUse(2); 261 Uses.push_back(std::make_pair(UseMain, &F)); 262 } 263 } 264 } 265 266 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers; 267 268 for (auto &UseFunc : Uses) { 269 Use *U = UseFunc.first; 270 Function *F = UseFunc.second; 271 PointerType *PTy = cast<PointerType>(U->get()->getType()); 272 FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType()); 273 274 // If the function is casted to something like i8* as a "generic pointer" 275 // to be later casted to something else, we can't generate a wrapper for it. 276 // Just ignore such casts for now. 277 if (!Ty) 278 continue; 279 280 auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr)); 281 if (Pair.second) 282 Pair.first->second = CreateWrapper(F, Ty); 283 284 Function *Wrapper = Pair.first->second; 285 if (!Wrapper) 286 continue; 287 288 if (isa<Constant>(U->get())) 289 U->get()->replaceAllUsesWith(Wrapper); 290 else 291 U->set(Wrapper); 292 } 293 294 // If we created a wrapper for main, rename the wrapper so that it's the 295 // one that gets called from startup. 296 if (CallMain) { 297 Main->setName("__original_main"); 298 Function *MainWrapper = 299 cast<Function>(CallMain->getCalledValue()->stripPointerCasts()); 300 MainWrapper->setName("main"); 301 MainWrapper->setLinkage(Main->getLinkage()); 302 MainWrapper->setVisibility(Main->getVisibility()); 303 Main->setLinkage(Function::PrivateLinkage); 304 Main->setVisibility(Function::DefaultVisibility); 305 delete CallMain; 306 } 307 308 return true; 309 } 310