1*1b637458SDan Gohman //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
2*1b637458SDan Gohman //
3*1b637458SDan Gohman //                     The LLVM Compiler Infrastructure
4*1b637458SDan Gohman //
5*1b637458SDan Gohman // This file is distributed under the University of Illinois Open Source
6*1b637458SDan Gohman // License. See LICENSE.TXT for details.
7*1b637458SDan Gohman //
8*1b637458SDan Gohman //===----------------------------------------------------------------------===//
9*1b637458SDan Gohman ///
10*1b637458SDan Gohman /// \file
11*1b637458SDan Gohman /// \brief Fix bitcasted functions.
12*1b637458SDan Gohman ///
13*1b637458SDan Gohman /// WebAssembly requires caller and callee signatures to match, however in LLVM,
14*1b637458SDan Gohman /// some amount of slop is vaguely permitted. Detect mismatch by looking for
15*1b637458SDan Gohman /// bitcasts of functions and rewrite them to use wrapper functions instead.
16*1b637458SDan Gohman ///
17*1b637458SDan Gohman /// This doesn't catch all cases, such as when a function's address is taken in
18*1b637458SDan Gohman /// one place and casted in another, but it works for many common cases.
19*1b637458SDan Gohman ///
20*1b637458SDan Gohman /// Note that LLVM already optimizes away function bitcasts in common cases by
21*1b637458SDan Gohman /// dropping arguments as needed, so this pass only ends up getting used in less
22*1b637458SDan Gohman /// common cases.
23*1b637458SDan Gohman ///
24*1b637458SDan Gohman //===----------------------------------------------------------------------===//
25*1b637458SDan Gohman 
26*1b637458SDan Gohman #include "WebAssembly.h"
27*1b637458SDan Gohman #include "llvm/IR/Constants.h"
28*1b637458SDan Gohman #include "llvm/IR/Instructions.h"
29*1b637458SDan Gohman #include "llvm/IR/Module.h"
30*1b637458SDan Gohman #include "llvm/IR/Operator.h"
31*1b637458SDan Gohman #include "llvm/Pass.h"
32*1b637458SDan Gohman #include "llvm/Support/Debug.h"
33*1b637458SDan Gohman #include "llvm/Support/raw_ostream.h"
34*1b637458SDan Gohman using namespace llvm;
35*1b637458SDan Gohman 
36*1b637458SDan Gohman #define DEBUG_TYPE "wasm-fix-function-bitcasts"
37*1b637458SDan Gohman 
38*1b637458SDan Gohman namespace {
39*1b637458SDan Gohman class FixFunctionBitcasts final : public ModulePass {
40*1b637458SDan Gohman   StringRef getPassName() const override {
41*1b637458SDan Gohman     return "WebAssembly Fix Function Bitcasts";
42*1b637458SDan Gohman   }
43*1b637458SDan Gohman 
44*1b637458SDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
45*1b637458SDan Gohman     AU.setPreservesCFG();
46*1b637458SDan Gohman     ModulePass::getAnalysisUsage(AU);
47*1b637458SDan Gohman   }
48*1b637458SDan Gohman 
49*1b637458SDan Gohman   bool runOnModule(Module &M) override;
50*1b637458SDan Gohman 
51*1b637458SDan Gohman   SmallVector<std::pair<Use *, Function *>, 0> Uses;
52*1b637458SDan Gohman 
53*1b637458SDan Gohman public:
54*1b637458SDan Gohman   static char ID;
55*1b637458SDan Gohman   FixFunctionBitcasts() : ModulePass(ID) {}
56*1b637458SDan Gohman };
57*1b637458SDan Gohman } // End anonymous namespace
58*1b637458SDan Gohman 
59*1b637458SDan Gohman char FixFunctionBitcasts::ID = 0;
60*1b637458SDan Gohman ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
61*1b637458SDan Gohman   return new FixFunctionBitcasts();
62*1b637458SDan Gohman }
63*1b637458SDan Gohman 
64*1b637458SDan Gohman // Recursively descend the def-use lists from V to find non-bitcast users of
65*1b637458SDan Gohman // bitcasts of V.
66*1b637458SDan Gohman static void FindUses(Value *V, Function &F,
67*1b637458SDan Gohman                      SmallVectorImpl<std::pair<Use *, Function *>> &Uses) {
68*1b637458SDan Gohman   for (Use &U : V->uses()) {
69*1b637458SDan Gohman     if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser()))
70*1b637458SDan Gohman       FindUses(BC, F, Uses);
71*1b637458SDan Gohman     else if (U.get()->getType() != F.getType())
72*1b637458SDan Gohman       Uses.push_back(std::make_pair(&U, &F));
73*1b637458SDan Gohman   }
74*1b637458SDan Gohman }
75*1b637458SDan Gohman 
76*1b637458SDan Gohman // Create a wrapper function with type Ty that calls F (which may have a
77*1b637458SDan Gohman // different type). Attempt to support common bitcasted function idioms:
78*1b637458SDan Gohman //  - Call with more arguments than needed: arguments are dropped
79*1b637458SDan Gohman //  - Call with fewer arguments than needed: arguments are filled in with undef
80*1b637458SDan Gohman //  - Return value is not needed: drop it
81*1b637458SDan Gohman //  - Return value needed but not present: supply an undef
82*1b637458SDan Gohman static Function *CreateWrapper(Function *F, FunctionType *Ty) {
83*1b637458SDan Gohman   Module *M = F->getParent();
84*1b637458SDan Gohman 
85*1b637458SDan Gohman   Function *Wrapper =
86*1b637458SDan Gohman       Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
87*1b637458SDan Gohman   BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
88*1b637458SDan Gohman 
89*1b637458SDan Gohman   // Determine what arguments to pass.
90*1b637458SDan Gohman   SmallVector<Value *, 4> Args;
91*1b637458SDan Gohman   Function::arg_iterator AI = Wrapper->arg_begin();
92*1b637458SDan Gohman   FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
93*1b637458SDan Gohman   FunctionType::param_iterator PE = F->getFunctionType()->param_end();
94*1b637458SDan Gohman   for (; AI != Wrapper->arg_end() && PI != PE; ++AI, ++PI) {
95*1b637458SDan Gohman     assert(AI->getType() == *PI &&
96*1b637458SDan Gohman            "mismatched argument types not supported yet");
97*1b637458SDan Gohman     Args.push_back(&*AI);
98*1b637458SDan Gohman   }
99*1b637458SDan Gohman   for (; PI != PE; ++PI)
100*1b637458SDan Gohman     Args.push_back(UndefValue::get(*PI));
101*1b637458SDan Gohman 
102*1b637458SDan Gohman   CallInst *Call = CallInst::Create(F, Args, "", BB);
103*1b637458SDan Gohman 
104*1b637458SDan Gohman   // Determine what value to return.
105*1b637458SDan Gohman   if (Ty->getReturnType()->isVoidTy())
106*1b637458SDan Gohman     ReturnInst::Create(M->getContext(), BB);
107*1b637458SDan Gohman   else if (F->getFunctionType()->getReturnType()->isVoidTy())
108*1b637458SDan Gohman     ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
109*1b637458SDan Gohman                        BB);
110*1b637458SDan Gohman   else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
111*1b637458SDan Gohman     ReturnInst::Create(M->getContext(), Call, BB);
112*1b637458SDan Gohman   else
113*1b637458SDan Gohman     llvm_unreachable("mismatched return types not supported yet");
114*1b637458SDan Gohman 
115*1b637458SDan Gohman   return Wrapper;
116*1b637458SDan Gohman }
117*1b637458SDan Gohman 
118*1b637458SDan Gohman bool FixFunctionBitcasts::runOnModule(Module &M) {
119*1b637458SDan Gohman   // Collect all the places that need wrappers.
120*1b637458SDan Gohman   for (Function &F : M)
121*1b637458SDan Gohman     FindUses(&F, F, Uses);
122*1b637458SDan Gohman 
123*1b637458SDan Gohman   DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
124*1b637458SDan Gohman 
125*1b637458SDan Gohman   for (auto &UseFunc : Uses) {
126*1b637458SDan Gohman     Use *U = UseFunc.first;
127*1b637458SDan Gohman     Function *F = UseFunc.second;
128*1b637458SDan Gohman     PointerType *PTy = cast<PointerType>(U->get()->getType());
129*1b637458SDan Gohman     FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType());
130*1b637458SDan Gohman 
131*1b637458SDan Gohman     // If the function is casted to something like i8* as a "generic pointer"
132*1b637458SDan Gohman     // to be later casted to something else, we can't generate a wrapper for it.
133*1b637458SDan Gohman     // Just ignore such casts for now.
134*1b637458SDan Gohman     if (!Ty)
135*1b637458SDan Gohman       continue;
136*1b637458SDan Gohman 
137*1b637458SDan Gohman     auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
138*1b637458SDan Gohman     if (Pair.second)
139*1b637458SDan Gohman       Pair.first->second = CreateWrapper(F, Ty);
140*1b637458SDan Gohman 
141*1b637458SDan Gohman     if (isa<Constant>(U->get()))
142*1b637458SDan Gohman       U->get()->replaceAllUsesWith(Pair.first->second);
143*1b637458SDan Gohman     else
144*1b637458SDan Gohman       U->set(Pair.first->second);
145*1b637458SDan Gohman   }
146*1b637458SDan Gohman 
147*1b637458SDan Gohman   return true;
148*1b637458SDan Gohman }
149