1 //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
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
7 //===----------------------------------------------------------------------===//
10 /// Fix bitcasted functions.
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.
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.
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
23 //===----------------------------------------------------------------------===//
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"
35 #define DEBUG_TYPE "wasm-fix-function-bitcasts"
38 class FixFunctionBitcasts final
: public ModulePass
{
39 StringRef
getPassName() const override
{
40 return "WebAssembly Fix Function Bitcasts";
43 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
45 ModulePass::getAnalysisUsage(AU
);
48 bool runOnModule(Module
&M
) override
;
52 FixFunctionBitcasts() : ModulePass(ID
) {}
54 } // End anonymous namespace
56 char FixFunctionBitcasts::ID
= 0;
57 INITIALIZE_PASS(FixFunctionBitcasts
, DEBUG_TYPE
,
58 "Fix mismatching bitcasts for WebAssembly", false, false)
60 ModulePass
*llvm::createWebAssemblyFixFunctionBitcasts() {
61 return new FixFunctionBitcasts();
64 // Recursively descend the def-use lists from V to find non-bitcast users of
66 static void findUses(Value
*V
, Function
&F
,
67 SmallVectorImpl
<std::pair
<Use
*, Function
*>> &Uses
,
68 SmallPtrSetImpl
<Constant
*> &ConstantBCs
) {
69 for (Use
&U
: V
->uses()) {
70 if (auto *BC
= dyn_cast
<BitCastOperator
>(U
.getUser()))
71 findUses(BC
, F
, Uses
, ConstantBCs
);
72 else if (auto *A
= dyn_cast
<GlobalAlias
>(U
.getUser()))
73 findUses(A
, F
, Uses
, ConstantBCs
);
74 else if (U
.get()->getType() != F
.getType()) {
75 CallBase
*CB
= dyn_cast
<CallBase
>(U
.getUser());
77 // Skip uses that aren't immediately called
79 Value
*Callee
= CB
->getCalledOperand();
81 // Skip calls where the function isn't the callee
83 if (isa
<Constant
>(U
.get())) {
84 // Only add constant bitcasts to the list once; they get RAUW'd
85 auto C
= ConstantBCs
.insert(cast
<Constant
>(U
.get()));
89 Uses
.push_back(std::make_pair(&U
, &F
));
94 // Create a wrapper function with type Ty that calls F (which may have a
95 // different type). Attempt to support common bitcasted function idioms:
96 // - Call with more arguments than needed: arguments are dropped
97 // - Call with fewer arguments than needed: arguments are filled in with undef
98 // - Return value is not needed: drop it
99 // - Return value needed but not present: supply an undef
101 // If the all the argument types of trivially castable to one another (i.e.
102 // I32 vs pointer type) then we don't create a wrapper at all (return nullptr
105 // If there is a type mismatch that we know would result in an invalid wasm
106 // module then generate wrapper that contains unreachable (i.e. abort at
107 // runtime). Such programs are deep into undefined behaviour territory,
108 // but we choose to fail at runtime rather than generate and invalid module
109 // or fail at compiler time. The reason we delay the error is that we want
110 // to support the CMake which expects to be able to compile and link programs
111 // that refer to functions with entirely incorrect signatures (this is how
112 // CMake detects the existence of a function in a toolchain).
114 // For bitcasts that involve struct types we don't know at this stage if they
115 // would be equivalent at the wasm level and so we can't know if we need to
116 // generate a wrapper.
117 static Function
*createWrapper(Function
*F
, FunctionType
*Ty
) {
118 Module
*M
= F
->getParent();
120 Function
*Wrapper
= Function::Create(Ty
, Function::PrivateLinkage
,
121 F
->getName() + "_bitcast", M
);
122 BasicBlock
*BB
= BasicBlock::Create(M
->getContext(), "body", Wrapper
);
123 const DataLayout
&DL
= BB
->getModule()->getDataLayout();
125 // Determine what arguments to pass.
126 SmallVector
<Value
*, 4> Args
;
127 Function::arg_iterator AI
= Wrapper
->arg_begin();
128 Function::arg_iterator AE
= Wrapper
->arg_end();
129 FunctionType::param_iterator PI
= F
->getFunctionType()->param_begin();
130 FunctionType::param_iterator PE
= F
->getFunctionType()->param_end();
131 bool TypeMismatch
= false;
132 bool WrapperNeeded
= false;
134 Type
*ExpectedRtnType
= F
->getFunctionType()->getReturnType();
135 Type
*RtnType
= Ty
->getReturnType();
137 if ((F
->getFunctionType()->getNumParams() != Ty
->getNumParams()) ||
138 (F
->getFunctionType()->isVarArg() != Ty
->isVarArg()) ||
139 (ExpectedRtnType
!= RtnType
))
140 WrapperNeeded
= true;
142 for (; AI
!= AE
&& PI
!= PE
; ++AI
, ++PI
) {
143 Type
*ArgType
= AI
->getType();
144 Type
*ParamType
= *PI
;
146 if (ArgType
== ParamType
) {
147 Args
.push_back(&*AI
);
149 if (CastInst::isBitOrNoopPointerCastable(ArgType
, ParamType
, DL
)) {
150 Instruction
*PtrCast
=
151 CastInst::CreateBitOrPointerCast(AI
, ParamType
, "cast");
152 BB
->getInstList().push_back(PtrCast
);
153 Args
.push_back(PtrCast
);
154 } else if (ArgType
->isStructTy() || ParamType
->isStructTy()) {
155 LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: "
156 << F
->getName() << "\n");
157 WrapperNeeded
= false;
159 LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: "
160 << F
->getName() << "\n");
161 LLVM_DEBUG(dbgs() << "Arg[" << Args
.size() << "] Expected: "
162 << *ParamType
<< " Got: " << *ArgType
<< "\n");
169 if (WrapperNeeded
&& !TypeMismatch
) {
170 for (; PI
!= PE
; ++PI
)
171 Args
.push_back(UndefValue::get(*PI
));
173 for (; AI
!= AE
; ++AI
)
174 Args
.push_back(&*AI
);
176 CallInst
*Call
= CallInst::Create(F
, Args
, "", BB
);
178 Type
*ExpectedRtnType
= F
->getFunctionType()->getReturnType();
179 Type
*RtnType
= Ty
->getReturnType();
180 // Determine what value to return.
181 if (RtnType
->isVoidTy()) {
182 ReturnInst::Create(M
->getContext(), BB
);
183 } else if (ExpectedRtnType
->isVoidTy()) {
184 LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType
<< "\n");
185 ReturnInst::Create(M
->getContext(), UndefValue::get(RtnType
), BB
);
186 } else if (RtnType
== ExpectedRtnType
) {
187 ReturnInst::Create(M
->getContext(), Call
, BB
);
188 } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType
, RtnType
,
191 CastInst::CreateBitOrPointerCast(Call
, RtnType
, "cast");
192 BB
->getInstList().push_back(Cast
);
193 ReturnInst::Create(M
->getContext(), Cast
, BB
);
194 } else if (RtnType
->isStructTy() || ExpectedRtnType
->isStructTy()) {
195 LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: "
196 << F
->getName() << "\n");
197 WrapperNeeded
= false;
199 LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: "
200 << F
->getName() << "\n");
201 LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType
202 << " Got: " << *RtnType
<< "\n");
208 // Create a new wrapper that simply contains `unreachable`.
209 Wrapper
->eraseFromParent();
210 Wrapper
= Function::Create(Ty
, Function::PrivateLinkage
,
211 F
->getName() + "_bitcast_invalid", M
);
212 BasicBlock
*BB
= BasicBlock::Create(M
->getContext(), "body", Wrapper
);
213 new UnreachableInst(M
->getContext(), BB
);
214 Wrapper
->setName(F
->getName() + "_bitcast_invalid");
215 } else if (!WrapperNeeded
) {
216 LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F
->getName()
218 Wrapper
->eraseFromParent();
221 LLVM_DEBUG(dbgs() << "createWrapper: " << F
->getName() << "\n");
225 // Test whether a main function with type FuncTy should be rewritten to have
227 static bool shouldFixMainFunction(FunctionType
*FuncTy
, FunctionType
*MainTy
) {
228 // Only fix the main function if it's the standard zero-arg form. That way,
229 // the standard cases will work as expected, and users will see signature
230 // mismatches from the linker for non-standard cases.
231 return FuncTy
->getReturnType() == MainTy
->getReturnType() &&
232 FuncTy
->getNumParams() == 0 &&
236 bool FixFunctionBitcasts::runOnModule(Module
&M
) {
237 LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n");
239 Function
*Main
= nullptr;
240 CallInst
*CallMain
= nullptr;
241 SmallVector
<std::pair
<Use
*, Function
*>, 0> Uses
;
242 SmallPtrSet
<Constant
*, 2> ConstantBCs
;
244 // Collect all the places that need wrappers.
245 for (Function
&F
: M
) {
246 // Skip to fix when the function is swiftcc because swiftcc allows
247 // bitcast type difference for swiftself and swifterror.
248 if (F
.getCallingConv() == CallingConv::Swift
)
250 findUses(&F
, F
, Uses
, ConstantBCs
);
252 // If we have a "main" function, and its type isn't
253 // "int main(int argc, char *argv[])", create an artificial call with it
254 // bitcasted to that type so that we generate a wrapper for it, so that
255 // the C runtime can call it.
256 if (F
.getName() == "main") {
258 LLVMContext
&C
= M
.getContext();
259 Type
*MainArgTys
[] = {Type::getInt32Ty(C
),
260 PointerType::get(Type::getInt8PtrTy(C
), 0)};
261 FunctionType
*MainTy
= FunctionType::get(Type::getInt32Ty(C
), MainArgTys
,
263 if (shouldFixMainFunction(F
.getFunctionType(), MainTy
)) {
264 LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: "
265 << *F
.getFunctionType() << "\n");
266 Value
*Args
[] = {UndefValue::get(MainArgTys
[0]),
267 UndefValue::get(MainArgTys
[1])};
269 ConstantExpr::getBitCast(Main
, PointerType::get(MainTy
, 0));
270 CallMain
= CallInst::Create(MainTy
, Casted
, Args
, "call_main");
271 Use
*UseMain
= &CallMain
->getOperandUse(2);
272 Uses
.push_back(std::make_pair(UseMain
, &F
));
277 DenseMap
<std::pair
<Function
*, FunctionType
*>, Function
*> Wrappers
;
279 for (auto &UseFunc
: Uses
) {
280 Use
*U
= UseFunc
.first
;
281 Function
*F
= UseFunc
.second
;
282 auto *PTy
= cast
<PointerType
>(U
->get()->getType());
283 auto *Ty
= dyn_cast
<FunctionType
>(PTy
->getElementType());
285 // If the function is casted to something like i8* as a "generic pointer"
286 // to be later casted to something else, we can't generate a wrapper for it.
287 // Just ignore such casts for now.
291 auto Pair
= Wrappers
.insert(std::make_pair(std::make_pair(F
, Ty
), nullptr));
293 Pair
.first
->second
= createWrapper(F
, Ty
);
295 Function
*Wrapper
= Pair
.first
->second
;
299 if (isa
<Constant
>(U
->get()))
300 U
->get()->replaceAllUsesWith(Wrapper
);
305 // If we created a wrapper for main, rename the wrapper so that it's the
306 // one that gets called from startup.
308 Main
->setName("__original_main");
310 cast
<Function
>(CallMain
->getCalledOperand()->stripPointerCasts());
312 if (Main
->isDeclaration()) {
313 // The wrapper is not needed in this case as we don't need to export
314 // it to anyone else.
315 MainWrapper
->eraseFromParent();
317 // Otherwise give the wrapper the same linkage as the original main
318 // function, so that it can be called from the same places.
319 MainWrapper
->setName("main");
320 MainWrapper
->setLinkage(Main
->getLinkage());
321 MainWrapper
->setVisibility(Main
->getVisibility());