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/Constants.h" |
27 | #include "llvm/IR/Instructions.h" |
28 | #include "llvm/IR/Module.h" |
29 | #include "llvm/IR/Operator.h" |
30 | #include "llvm/Pass.h" |
31 | #include "llvm/Support/Debug.h" |
32 | #include "llvm/Support/raw_ostream.h" |
33 | using namespace llvm; |
34 | |
35 | #define DEBUG_TYPE "wasm-fix-function-bitcasts" |
36 | |
37 | namespace { |
38 | class FixFunctionBitcasts final : public ModulePass { |
39 | StringRef getPassName() const override { |
40 | return "WebAssembly Fix Function Bitcasts" ; |
41 | } |
42 | |
43 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
44 | AU.setPreservesCFG(); |
45 | ModulePass::getAnalysisUsage(AU); |
46 | } |
47 | |
48 | bool runOnModule(Module &M) override; |
49 | |
50 | public: |
51 | static char ID; |
52 | FixFunctionBitcasts() : ModulePass(ID) {} |
53 | }; |
54 | } // End anonymous namespace |
55 | |
56 | char FixFunctionBitcasts::ID = 0; |
57 | INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE, |
58 | "Fix mismatching bitcasts for WebAssembly" , false, false) |
59 | |
60 | ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() { |
61 | return new FixFunctionBitcasts(); |
62 | } |
63 | |
64 | // Recursively descend the def-use lists from V to find non-bitcast users of |
65 | // bitcasts of V. |
66 | static void findUses(Value *V, Function &F, |
67 | SmallVectorImpl<std::pair<CallBase *, Function *>> &Uses) { |
68 | for (User *U : V->users()) { |
69 | if (auto *BC = dyn_cast<BitCastOperator>(Val: U)) |
70 | findUses(V: BC, F, Uses); |
71 | else if (auto *A = dyn_cast<GlobalAlias>(Val: U)) |
72 | findUses(V: A, F, Uses); |
73 | else if (auto *CB = dyn_cast<CallBase>(Val: U)) { |
74 | Value *Callee = CB->getCalledOperand(); |
75 | if (Callee != V) |
76 | // Skip calls where the function isn't the callee |
77 | continue; |
78 | if (CB->getFunctionType() == F.getValueType()) |
79 | // Skip uses that are immediately called |
80 | continue; |
81 | Uses.push_back(Elt: std::make_pair(x&: CB, y: &F)); |
82 | } |
83 | } |
84 | } |
85 | |
86 | // Create a wrapper function with type Ty that calls F (which may have a |
87 | // different type). Attempt to support common bitcasted function idioms: |
88 | // - Call with more arguments than needed: arguments are dropped |
89 | // - Call with fewer arguments than needed: arguments are filled in with poison |
90 | // - Return value is not needed: drop it |
91 | // - Return value needed but not present: supply a poison value |
92 | // |
93 | // If the all the argument types of trivially castable to one another (i.e. |
94 | // I32 vs pointer type) then we don't create a wrapper at all (return nullptr |
95 | // instead). |
96 | // |
97 | // If there is a type mismatch that we know would result in an invalid wasm |
98 | // module then generate wrapper that contains unreachable (i.e. abort at |
99 | // runtime). Such programs are deep into undefined behaviour territory, |
100 | // but we choose to fail at runtime rather than generate and invalid module |
101 | // or fail at compiler time. The reason we delay the error is that we want |
102 | // to support the CMake which expects to be able to compile and link programs |
103 | // that refer to functions with entirely incorrect signatures (this is how |
104 | // CMake detects the existence of a function in a toolchain). |
105 | // |
106 | // For bitcasts that involve struct types we don't know at this stage if they |
107 | // would be equivalent at the wasm level and so we can't know if we need to |
108 | // generate a wrapper. |
109 | static Function *createWrapper(Function *F, FunctionType *Ty) { |
110 | Module *M = F->getParent(); |
111 | |
112 | Function *Wrapper = Function::Create(Ty, Linkage: Function::PrivateLinkage, |
113 | N: F->getName() + "_bitcast" , M); |
114 | Wrapper->setAttributes(F->getAttributes()); |
115 | BasicBlock *BB = BasicBlock::Create(Context&: M->getContext(), Name: "body" , Parent: Wrapper); |
116 | const DataLayout &DL = BB->getDataLayout(); |
117 | |
118 | // Determine what arguments to pass. |
119 | SmallVector<Value *, 4> Args; |
120 | Function::arg_iterator AI = Wrapper->arg_begin(); |
121 | Function::arg_iterator AE = Wrapper->arg_end(); |
122 | FunctionType::param_iterator PI = F->getFunctionType()->param_begin(); |
123 | FunctionType::param_iterator PE = F->getFunctionType()->param_end(); |
124 | bool TypeMismatch = false; |
125 | bool WrapperNeeded = false; |
126 | |
127 | Type *ExpectedRtnType = F->getFunctionType()->getReturnType(); |
128 | Type *RtnType = Ty->getReturnType(); |
129 | |
130 | if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) || |
131 | (F->getFunctionType()->isVarArg() != Ty->isVarArg()) || |
132 | (ExpectedRtnType != RtnType)) |
133 | WrapperNeeded = true; |
134 | |
135 | for (; AI != AE && PI != PE; ++AI, ++PI) { |
136 | Type *ArgType = AI->getType(); |
137 | Type *ParamType = *PI; |
138 | |
139 | if (ArgType == ParamType) { |
140 | Args.push_back(Elt: &*AI); |
141 | } else { |
142 | if (CastInst::isBitOrNoopPointerCastable(SrcTy: ArgType, DestTy: ParamType, DL)) { |
143 | Instruction *PtrCast = |
144 | CastInst::CreateBitOrPointerCast(S: AI, Ty: ParamType, Name: "cast" ); |
145 | PtrCast->insertInto(ParentBB: BB, It: BB->end()); |
146 | Args.push_back(Elt: PtrCast); |
147 | } else if (ArgType->isStructTy() || ParamType->isStructTy()) { |
148 | LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: " |
149 | << F->getName() << "\n" ); |
150 | WrapperNeeded = false; |
151 | } else { |
152 | LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: " |
153 | << F->getName() << "\n" ); |
154 | LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: " |
155 | << *ParamType << " Got: " << *ArgType << "\n" ); |
156 | TypeMismatch = true; |
157 | break; |
158 | } |
159 | } |
160 | } |
161 | |
162 | if (WrapperNeeded && !TypeMismatch) { |
163 | for (; PI != PE; ++PI) |
164 | Args.push_back(Elt: PoisonValue::get(T: *PI)); |
165 | if (F->isVarArg()) |
166 | for (; AI != AE; ++AI) |
167 | Args.push_back(Elt: &*AI); |
168 | |
169 | CallInst *Call = CallInst::Create(Func: F, Args, NameStr: "" , InsertBefore: BB); |
170 | |
171 | Type *ExpectedRtnType = F->getFunctionType()->getReturnType(); |
172 | Type *RtnType = Ty->getReturnType(); |
173 | // Determine what value to return. |
174 | if (RtnType->isVoidTy()) { |
175 | ReturnInst::Create(C&: M->getContext(), InsertAtEnd: BB); |
176 | } else if (ExpectedRtnType->isVoidTy()) { |
177 | LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n" ); |
178 | ReturnInst::Create(C&: M->getContext(), retVal: PoisonValue::get(T: RtnType), InsertBefore: BB); |
179 | } else if (RtnType == ExpectedRtnType) { |
180 | ReturnInst::Create(C&: M->getContext(), retVal: Call, InsertBefore: BB); |
181 | } else if (CastInst::isBitOrNoopPointerCastable(SrcTy: ExpectedRtnType, DestTy: RtnType, |
182 | DL)) { |
183 | Instruction *Cast = |
184 | CastInst::CreateBitOrPointerCast(S: Call, Ty: RtnType, Name: "cast" ); |
185 | Cast->insertInto(ParentBB: BB, It: BB->end()); |
186 | ReturnInst::Create(C&: M->getContext(), retVal: Cast, InsertBefore: BB); |
187 | } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) { |
188 | LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: " |
189 | << F->getName() << "\n" ); |
190 | WrapperNeeded = false; |
191 | } else { |
192 | LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: " |
193 | << F->getName() << "\n" ); |
194 | LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType |
195 | << " Got: " << *RtnType << "\n" ); |
196 | TypeMismatch = true; |
197 | } |
198 | } |
199 | |
200 | if (TypeMismatch) { |
201 | // Create a new wrapper that simply contains `unreachable`. |
202 | Wrapper->eraseFromParent(); |
203 | Wrapper = Function::Create(Ty, Linkage: Function::PrivateLinkage, |
204 | N: F->getName() + "_bitcast_invalid" , M); |
205 | Wrapper->setAttributes(F->getAttributes()); |
206 | BasicBlock *BB = BasicBlock::Create(Context&: M->getContext(), Name: "body" , Parent: Wrapper); |
207 | new UnreachableInst(M->getContext(), BB); |
208 | Wrapper->setName(F->getName() + "_bitcast_invalid" ); |
209 | } else if (!WrapperNeeded) { |
210 | LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F->getName() |
211 | << "\n" ); |
212 | Wrapper->eraseFromParent(); |
213 | return nullptr; |
214 | } |
215 | LLVM_DEBUG(dbgs() << "createWrapper: " << F->getName() << "\n" ); |
216 | return Wrapper; |
217 | } |
218 | |
219 | // Test whether a main function with type FuncTy should be rewritten to have |
220 | // type MainTy. |
221 | static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy) { |
222 | // Only fix the main function if it's the standard zero-arg form. That way, |
223 | // the standard cases will work as expected, and users will see signature |
224 | // mismatches from the linker for non-standard cases. |
225 | return FuncTy->getReturnType() == MainTy->getReturnType() && |
226 | FuncTy->getNumParams() == 0 && |
227 | !FuncTy->isVarArg(); |
228 | } |
229 | |
230 | bool FixFunctionBitcasts::runOnModule(Module &M) { |
231 | LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n" ); |
232 | |
233 | Function *Main = nullptr; |
234 | CallInst *CallMain = nullptr; |
235 | SmallVector<std::pair<CallBase *, Function *>, 0> Uses; |
236 | |
237 | // Collect all the places that need wrappers. |
238 | for (Function &F : M) { |
239 | // Skip to fix when the function is swiftcc because swiftcc allows |
240 | // bitcast type difference for swiftself and swifterror. |
241 | if (F.getCallingConv() == CallingConv::Swift) |
242 | continue; |
243 | findUses(V: &F, F, Uses); |
244 | |
245 | // If we have a "main" function, and its type isn't |
246 | // "int main(int argc, char *argv[])", create an artificial call with it |
247 | // bitcasted to that type so that we generate a wrapper for it, so that |
248 | // the C runtime can call it. |
249 | if (F.getName() == "main" ) { |
250 | Main = &F; |
251 | LLVMContext &C = M.getContext(); |
252 | Type *MainArgTys[] = {Type::getInt32Ty(C), PointerType::get(C, AddressSpace: 0)}; |
253 | FunctionType *MainTy = FunctionType::get(Result: Type::getInt32Ty(C), Params: MainArgTys, |
254 | /*isVarArg=*/false); |
255 | if (shouldFixMainFunction(FuncTy: F.getFunctionType(), MainTy)) { |
256 | LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: " |
257 | << *F.getFunctionType() << "\n" ); |
258 | Value *Args[] = {PoisonValue::get(T: MainArgTys[0]), |
259 | PoisonValue::get(T: MainArgTys[1])}; |
260 | CallMain = CallInst::Create(Ty: MainTy, Func: Main, Args, NameStr: "call_main" ); |
261 | Uses.push_back(Elt: std::make_pair(x&: CallMain, y: &F)); |
262 | } |
263 | } |
264 | } |
265 | |
266 | DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers; |
267 | |
268 | for (auto &UseFunc : Uses) { |
269 | CallBase *CB = UseFunc.first; |
270 | Function *F = UseFunc.second; |
271 | FunctionType *Ty = CB->getFunctionType(); |
272 | |
273 | auto Pair = Wrappers.try_emplace(Key: std::make_pair(x&: F, y&: Ty)); |
274 | if (Pair.second) |
275 | Pair.first->second = createWrapper(F, Ty); |
276 | |
277 | Function *Wrapper = Pair.first->second; |
278 | if (!Wrapper) |
279 | continue; |
280 | |
281 | CB->setCalledOperand(Wrapper); |
282 | } |
283 | |
284 | // If we created a wrapper for main, rename the wrapper so that it's the |
285 | // one that gets called from startup. |
286 | if (CallMain) { |
287 | Main->setName("__original_main" ); |
288 | auto *MainWrapper = |
289 | cast<Function>(Val: CallMain->getCalledOperand()->stripPointerCasts()); |
290 | delete CallMain; |
291 | if (Main->isDeclaration()) { |
292 | // The wrapper is not needed in this case as we don't need to export |
293 | // it to anyone else. |
294 | MainWrapper->eraseFromParent(); |
295 | } else { |
296 | // Otherwise give the wrapper the same linkage as the original main |
297 | // function, so that it can be called from the same places. |
298 | MainWrapper->setName("main" ); |
299 | MainWrapper->setLinkage(Main->getLinkage()); |
300 | MainWrapper->setVisibility(Main->getVisibility()); |
301 | } |
302 | } |
303 | |
304 | return true; |
305 | } |
306 | |