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