LLVM: lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp Source File

LLVM 22.0.0git
WebAssemblyFixFunctionBitcasts.cpp
Go to the documentation of this file.
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/IRBuilder.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"
34using namespace llvm;
35
36 #define DEBUG_TYPE "wasm-fix-function-bitcasts"
37
38namespace {
39class FixFunctionBitcasts final : public ModulePass {
40 StringRef getPassName() const override {
41 return "WebAssembly Fix Function Bitcasts";
42 }
43
44 void getAnalysisUsage(AnalysisUsage &AU) const override {
45 AU.setPreservesCFG();
46 ModulePass::getAnalysisUsage(AU);
47 }
48
49 bool runOnModule(Module &M) override;
50
51public:
52 static char ID;
53 FixFunctionBitcasts() : ModulePass(ID) {}
54};
55} // End anonymous namespace
56
57char FixFunctionBitcasts::ID = 0;
58 INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE,
59 "Fix mismatching bitcasts for WebAssembly", false, false)
60
62 return new FixFunctionBitcasts();
63}
64
65// Recursively descend the def-use lists from V to find non-bitcast users of
66// bitcasts of V.
67 static void findUses(Value *V, Function &F,
68 SmallVectorImpl<std::pair<CallBase *, Function *>> &Uses) {
69 for (User *U : V->users()) {
70 if (auto *BC = dyn_cast<BitCastOperator>(U))
71 findUses(BC, F, Uses);
72 else if (auto *A = dyn_cast<GlobalAlias>(U))
73 findUses(A, F, Uses);
74 else if (auto *CB = dyn_cast<CallBase>(U)) {
75 Value *Callee = CB->getCalledOperand();
76 if (Callee != V)
77 // Skip calls where the function isn't the callee
78 continue;
79 if (CB->getFunctionType() == F.getValueType())
80 // Skip uses that are immediately called
81 continue;
82 Uses.push_back(std::make_pair(CB, &F));
83 }
84 }
85}
86
87// Create a wrapper function with type Ty that calls F (which may have a
88// different type). Attempt to support common bitcasted function idioms:
89// - Call with more arguments than needed: arguments are dropped
90// - Call with fewer arguments than needed: arguments are filled in with poison
91// - Return value is not needed: drop it
92// - Return value needed but not present: supply a poison value
93//
94// If the all the argument types of trivially castable to one another (i.e.
95// I32 vs pointer type) then we don't create a wrapper at all (return nullptr
96// instead).
97//
98// If there is a type mismatch that we know would result in an invalid wasm
99// module then generate wrapper that contains unreachable (i.e. abort at
100// runtime). Such programs are deep into undefined behaviour territory,
101// but we choose to fail at runtime rather than generate and invalid module
102// or fail at compiler time. The reason we delay the error is that we want
103// to support the CMake which expects to be able to compile and link programs
104// that refer to functions with entirely incorrect signatures (this is how
105// CMake detects the existence of a function in a toolchain).
106//
107// For bitcasts that involve struct types we don't know at this stage if they
108// would be equivalent at the wasm level and so we can't know if we need to
109// generate a wrapper.
111 Module *M = F->getParent();
112
114 F->getName() + "_bitcast", M);
115 Wrapper->setAttributes(F->getAttributes());
116 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
117 const DataLayout &DL = BB->getDataLayout();
118 IRBuilder<> Builder(BB);
119
120 // Determine what arguments to pass.
122 Function::arg_iterator AI = Wrapper->arg_begin();
123 Function::arg_iterator AE = Wrapper->arg_end();
124 FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
125 FunctionType::param_iterator PE = F->getFunctionType()->param_end();
126 bool TypeMismatch = false;
127 bool WrapperNeeded = false;
128
129 Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
130 Type *RtnType = Ty->getReturnType();
131
132 if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) ||
133 (F->getFunctionType()->isVarArg() != Ty->isVarArg()) ||
134 (ExpectedRtnType != RtnType))
135 WrapperNeeded = true;
136
137 for (; AI != AE && PI != PE; ++AI, ++PI) {
138 Type *ArgType = AI->getType();
139 Type *ParamType = *PI;
140
141 if (ArgType == ParamType) {
142 Args.push_back(&*AI);
143 } else {
144 if (CastInst::isBitOrNoopPointerCastable(ArgType, ParamType, DL)) {
145 Args.push_back(Builder.CreateBitOrPointerCast(AI, ParamType, "cast"));
146 } else if (ArgType->isStructTy() || ParamType->isStructTy()) {
147 LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: "
148 << F->getName() << "\n");
149 WrapperNeeded = false;
150 } else {
151 LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: "
152 << F->getName() << "\n");
153 LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: "
154 << *ParamType << " Got: " << *ArgType << "\n");
155 TypeMismatch = true;
156 break;
157 }
158 }
159 }
160
161 if (WrapperNeeded && !TypeMismatch) {
162 for (; PI != PE; ++PI)
163 Args.push_back(PoisonValue::get(*PI));
164 if (F->isVarArg())
165 for (; AI != AE; ++AI)
166 Args.push_back(&*AI);
167
168 CallInst *Call = Builder.CreateCall(F, Args);
169
170 // Determine what value to return.
171 if (RtnType->isVoidTy()) {
172 Builder.CreateRetVoid();
173 } else if (ExpectedRtnType->isVoidTy()) {
174 LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n");
175 Builder.CreateRet(PoisonValue::get(RtnType));
176 } else if (RtnType == ExpectedRtnType) {
177 Builder.CreateRet(Call);
178 } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType,
179 DL)) {
180 Builder.CreateRet(Builder.CreateBitOrPointerCast(Call, RtnType, "cast"));
181 } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) {
182 LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: "
183 << F->getName() << "\n");
184 WrapperNeeded = false;
185 } else {
186 LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: "
187 << F->getName() << "\n");
188 LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType
189 << " Got: " << *RtnType << "\n");
190 TypeMismatch = true;
191 }
192 }
193
194 if (TypeMismatch) {
195 // Create a new wrapper that simply contains `unreachable`.
196 Wrapper->eraseFromParent();
198 F->getName() + "_bitcast_invalid", M);
199 Wrapper->setAttributes(F->getAttributes());
200 IRBuilder<> Builder(BasicBlock::Create(M->getContext(), "body", Wrapper));
201 Builder.CreateUnreachable();
202 } else if (!WrapperNeeded) {
203 LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F->getName()
204 << "\n");
205 Wrapper->eraseFromParent();
206 return nullptr;
207 }
208 LLVM_DEBUG(dbgs() << "createWrapper: " << F->getName() << "\n");
209 return Wrapper;
210}
211
212// Test whether a main function with type FuncTy should be rewritten to have
213// type MainTy.
214 static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy) {
215 // Only fix the main function if it's the standard zero-arg form. That way,
216 // the standard cases will work as expected, and users will see signature
217 // mismatches from the linker for non-standard cases.
218 return FuncTy->getReturnType() == MainTy->getReturnType() &&
219 FuncTy->getNumParams() == 0 &&
220 !FuncTy->isVarArg();
221}
222
223bool FixFunctionBitcasts::runOnModule(Module &M) {
224 LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n");
225
226 Function *Main = nullptr;
227 CallInst *CallMain = nullptr;
228 SmallVector<std::pair<CallBase *, Function *>, 0> Uses;
229
230 // Collect all the places that need wrappers.
231 for (Function &F : M) {
232 // Skip to fix when the function is swiftcc because swiftcc allows
233 // bitcast type difference for swiftself and swifterror.
234 if (F.getCallingConv() == CallingConv::Swift)
235 continue;
236 findUses(&F, F, Uses);
237
238 // If we have a "main" function, and its type isn't
239 // "int main(int argc, char *argv[])", create an artificial call with it
240 // bitcasted to that type so that we generate a wrapper for it, so that
241 // the C runtime can call it.
242 if (F.getName() == "main") {
243 Main = &F;
244 LLVMContext &C = M.getContext();
245 Type *MainArgTys[] = {Type::getInt32Ty(C), PointerType::get(C, 0)};
246 FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
247 /*isVarArg=*/false);
248 if (shouldFixMainFunction(F.getFunctionType(), MainTy)) {
249 LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: "
250 << *F.getFunctionType() << "\n");
251 Value *Args[] = {PoisonValue::get(MainArgTys[0]),
252 PoisonValue::get(MainArgTys[1])};
253 CallMain = CallInst::Create(MainTy, Main, Args, "call_main");
254 Uses.push_back(std::make_pair(CallMain, &F));
255 }
256 }
257 }
258
259 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
260
261 for (auto &UseFunc : Uses) {
262 CallBase *CB = UseFunc.first;
263 Function *F = UseFunc.second;
264 FunctionType *Ty = CB->getFunctionType();
265
266 auto Pair = Wrappers.try_emplace(std::make_pair(F, Ty));
267 if (Pair.second)
268 Pair.first->second = createWrapper(F, Ty);
269
270 Function *Wrapper = Pair.first->second;
271 if (!Wrapper)
272 continue;
273
274 CB->setCalledOperand(Wrapper);
275 }
276
277 // If we created a wrapper for main, rename the wrapper so that it's the
278 // one that gets called from startup.
279 if (CallMain) {
280 Main->setName("__original_main");
281 auto *MainWrapper =
282 cast<Function>(CallMain->getCalledOperand()->stripPointerCasts());
283 delete CallMain;
284 if (Main->isDeclaration()) {
285 // The wrapper is not needed in this case as we don't need to export
286 // it to anyone else.
287 MainWrapper->eraseFromParent();
288 } else {
289 // Otherwise give the wrapper the same linkage as the original main
290 // function, so that it can be called from the same places.
291 MainWrapper->setName("main");
292 MainWrapper->setLinkage(Main->getLinkage());
293 MainWrapper->setVisibility(Main->getVisibility());
294 }
295 }
296
297 return true;
298}
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
A
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
F
#define F(x, y, z)
Definition MD5.cpp:55
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Remove Loads Into Fake Uses
#define LLVM_DEBUG(...)
Definition Debug.h:114
static void findUses(Value *V, Function &F, SmallVectorImpl< std::pair< CallBase *, Function * > > &Uses)
static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy)
static Function * createWrapper(Function *F, FunctionType *Ty)
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition BasicBlock.cpp:252
Value * getCalledOperand() const
Definition InstrTypes.h:1338
FunctionType * getFunctionType() const
Definition InstrTypes.h:1203
void setCalledOperand(Value *V)
Definition InstrTypes.h:1382
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:248
Type::subtype_iterator param_iterator
Definition DerivedTypes.h:128
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
VisibilityTypes getVisibility() const
Definition GlobalValue.h:250
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:328
LinkageTypes getLinkage() const
Definition GlobalValue.h:548
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition Pass.cpp:112
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition Constants.cpp:1888
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition SmallVector.h:574
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition SmallVector.h:1203
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
Definition User.h:44
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:701
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition AddressRanges.h:18
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Definition SmallVector.h:1129
ModulePass * createWebAssemblyFixFunctionBitcasts()
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559

Generated on for LLVM by doxygen 1.14.0

AltStyle によって変換されたページ (->オリジナル) /