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