124e2fe98SDimitry Andric //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
224e2fe98SDimitry Andric //
324e2fe98SDimitry Andric //                     The LLVM Compiler Infrastructure
424e2fe98SDimitry Andric //
524e2fe98SDimitry Andric // This file is distributed under the University of Illinois Open Source
624e2fe98SDimitry Andric // License. See LICENSE.TXT for details.
724e2fe98SDimitry Andric //
824e2fe98SDimitry Andric //===----------------------------------------------------------------------===//
924e2fe98SDimitry Andric ///
1024e2fe98SDimitry Andric /// \file
1124e2fe98SDimitry Andric /// \brief Fix bitcasted functions.
1224e2fe98SDimitry Andric ///
1324e2fe98SDimitry Andric /// WebAssembly requires caller and callee signatures to match, however in LLVM,
1424e2fe98SDimitry Andric /// some amount of slop is vaguely permitted. Detect mismatch by looking for
1524e2fe98SDimitry Andric /// bitcasts of functions and rewrite them to use wrapper functions instead.
1624e2fe98SDimitry Andric ///
1724e2fe98SDimitry Andric /// This doesn't catch all cases, such as when a function's address is taken in
1824e2fe98SDimitry Andric /// one place and casted in another, but it works for many common cases.
1924e2fe98SDimitry Andric ///
2024e2fe98SDimitry Andric /// Note that LLVM already optimizes away function bitcasts in common cases by
2124e2fe98SDimitry Andric /// dropping arguments as needed, so this pass only ends up getting used in less
2224e2fe98SDimitry Andric /// common cases.
2324e2fe98SDimitry Andric ///
2424e2fe98SDimitry Andric //===----------------------------------------------------------------------===//
2524e2fe98SDimitry Andric 
2624e2fe98SDimitry Andric #include "WebAssembly.h"
272cab237bSDimitry Andric #include "llvm/IR/CallSite.h"
2824e2fe98SDimitry Andric #include "llvm/IR/Constants.h"
2924e2fe98SDimitry Andric #include "llvm/IR/Instructions.h"
3024e2fe98SDimitry Andric #include "llvm/IR/Module.h"
3124e2fe98SDimitry Andric #include "llvm/IR/Operator.h"
3224e2fe98SDimitry Andric #include "llvm/Pass.h"
3324e2fe98SDimitry Andric #include "llvm/Support/Debug.h"
3424e2fe98SDimitry Andric #include "llvm/Support/raw_ostream.h"
3524e2fe98SDimitry Andric using namespace llvm;
3624e2fe98SDimitry Andric 
3724e2fe98SDimitry Andric #define DEBUG_TYPE "wasm-fix-function-bitcasts"
3824e2fe98SDimitry Andric 
392cab237bSDimitry Andric static cl::opt<bool> TemporaryWorkarounds(
402cab237bSDimitry Andric   "wasm-temporary-workarounds",
412cab237bSDimitry Andric   cl::desc("Apply certain temporary workarounds"),
422cab237bSDimitry Andric   cl::init(true), cl::Hidden);
432cab237bSDimitry Andric 
4424e2fe98SDimitry Andric namespace {
4524e2fe98SDimitry Andric class FixFunctionBitcasts final : public ModulePass {
4624e2fe98SDimitry Andric   StringRef getPassName() const override {
4724e2fe98SDimitry Andric     return "WebAssembly Fix Function Bitcasts";
4824e2fe98SDimitry Andric   }
4924e2fe98SDimitry Andric 
5024e2fe98SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
5124e2fe98SDimitry Andric     AU.setPreservesCFG();
5224e2fe98SDimitry Andric     ModulePass::getAnalysisUsage(AU);
5324e2fe98SDimitry Andric   }
5424e2fe98SDimitry Andric 
5524e2fe98SDimitry Andric   bool runOnModule(Module &M) override;
5624e2fe98SDimitry Andric 
5724e2fe98SDimitry Andric public:
5824e2fe98SDimitry Andric   static char ID;
5924e2fe98SDimitry Andric   FixFunctionBitcasts() : ModulePass(ID) {}
6024e2fe98SDimitry Andric };
6124e2fe98SDimitry Andric } // End anonymous namespace
6224e2fe98SDimitry Andric 
6324e2fe98SDimitry Andric char FixFunctionBitcasts::ID = 0;
6424e2fe98SDimitry Andric ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
6524e2fe98SDimitry Andric   return new FixFunctionBitcasts();
6624e2fe98SDimitry Andric }
6724e2fe98SDimitry Andric 
6824e2fe98SDimitry Andric // Recursively descend the def-use lists from V to find non-bitcast users of
6924e2fe98SDimitry Andric // bitcasts of V.
7024e2fe98SDimitry Andric static void FindUses(Value *V, Function &F,
71f1a29dd3SDimitry Andric                      SmallVectorImpl<std::pair<Use *, Function *>> &Uses,
72f1a29dd3SDimitry Andric                      SmallPtrSetImpl<Constant *> &ConstantBCs) {
7324e2fe98SDimitry Andric   for (Use &U : V->uses()) {
7424e2fe98SDimitry Andric     if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser()))
75f1a29dd3SDimitry Andric       FindUses(BC, F, Uses, ConstantBCs);
76f1a29dd3SDimitry Andric     else if (U.get()->getType() != F.getType()) {
772cab237bSDimitry Andric       CallSite CS(U.getUser());
782cab237bSDimitry Andric       if (!CS)
792cab237bSDimitry Andric         // Skip uses that aren't immediately called
802cab237bSDimitry Andric         continue;
812cab237bSDimitry Andric       Value *Callee = CS.getCalledValue();
822cab237bSDimitry Andric       if (Callee != V)
832cab237bSDimitry Andric         // Skip calls where the function isn't the callee
842cab237bSDimitry Andric         continue;
85f1a29dd3SDimitry Andric       if (isa<Constant>(U.get())) {
86f1a29dd3SDimitry Andric         // Only add constant bitcasts to the list once; they get RAUW'd
87f1a29dd3SDimitry Andric         auto c = ConstantBCs.insert(cast<Constant>(U.get()));
882cab237bSDimitry Andric         if (!c.second)
892cab237bSDimitry Andric           continue;
90f1a29dd3SDimitry Andric       }
9124e2fe98SDimitry Andric       Uses.push_back(std::make_pair(&U, &F));
9224e2fe98SDimitry Andric     }
9324e2fe98SDimitry Andric   }
94f1a29dd3SDimitry Andric }
9524e2fe98SDimitry Andric 
9624e2fe98SDimitry Andric // Create a wrapper function with type Ty that calls F (which may have a
9724e2fe98SDimitry Andric // different type). Attempt to support common bitcasted function idioms:
9824e2fe98SDimitry Andric //  - Call with more arguments than needed: arguments are dropped
9924e2fe98SDimitry Andric //  - Call with fewer arguments than needed: arguments are filled in with undef
10024e2fe98SDimitry Andric //  - Return value is not needed: drop it
10124e2fe98SDimitry Andric //  - Return value needed but not present: supply an undef
10224e2fe98SDimitry Andric //
10324e2fe98SDimitry Andric // For now, return nullptr without creating a wrapper if the wrapper cannot
10424e2fe98SDimitry Andric // be generated due to incompatible types.
10524e2fe98SDimitry Andric static Function *CreateWrapper(Function *F, FunctionType *Ty) {
10624e2fe98SDimitry Andric   Module *M = F->getParent();
10724e2fe98SDimitry Andric 
10824e2fe98SDimitry Andric   Function *Wrapper =
10924e2fe98SDimitry Andric       Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
11024e2fe98SDimitry Andric   BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
11124e2fe98SDimitry Andric 
11224e2fe98SDimitry Andric   // Determine what arguments to pass.
11324e2fe98SDimitry Andric   SmallVector<Value *, 4> Args;
11424e2fe98SDimitry Andric   Function::arg_iterator AI = Wrapper->arg_begin();
1152cab237bSDimitry Andric   Function::arg_iterator AE = Wrapper->arg_end();
11624e2fe98SDimitry Andric   FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
11724e2fe98SDimitry Andric   FunctionType::param_iterator PE = F->getFunctionType()->param_end();
1182cab237bSDimitry Andric   for (; AI != AE && PI != PE; ++AI, ++PI) {
11924e2fe98SDimitry Andric     if (AI->getType() != *PI) {
12024e2fe98SDimitry Andric       Wrapper->eraseFromParent();
12124e2fe98SDimitry Andric       return nullptr;
12224e2fe98SDimitry Andric     }
12324e2fe98SDimitry Andric     Args.push_back(&*AI);
12424e2fe98SDimitry Andric   }
12524e2fe98SDimitry Andric   for (; PI != PE; ++PI)
12624e2fe98SDimitry Andric     Args.push_back(UndefValue::get(*PI));
1272cab237bSDimitry Andric   if (F->isVarArg())
1282cab237bSDimitry Andric     for (; AI != AE; ++AI)
1292cab237bSDimitry Andric       Args.push_back(&*AI);
13024e2fe98SDimitry Andric 
13124e2fe98SDimitry Andric   CallInst *Call = CallInst::Create(F, Args, "", BB);
13224e2fe98SDimitry Andric 
13324e2fe98SDimitry Andric   // Determine what value to return.
13424e2fe98SDimitry Andric   if (Ty->getReturnType()->isVoidTy())
13524e2fe98SDimitry Andric     ReturnInst::Create(M->getContext(), BB);
13624e2fe98SDimitry Andric   else if (F->getFunctionType()->getReturnType()->isVoidTy())
13724e2fe98SDimitry Andric     ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
13824e2fe98SDimitry Andric                        BB);
13924e2fe98SDimitry Andric   else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
14024e2fe98SDimitry Andric     ReturnInst::Create(M->getContext(), Call, BB);
14124e2fe98SDimitry Andric   else {
14224e2fe98SDimitry Andric     Wrapper->eraseFromParent();
14324e2fe98SDimitry Andric     return nullptr;
14424e2fe98SDimitry Andric   }
14524e2fe98SDimitry Andric 
14624e2fe98SDimitry Andric   return Wrapper;
14724e2fe98SDimitry Andric }
14824e2fe98SDimitry Andric 
14924e2fe98SDimitry Andric bool FixFunctionBitcasts::runOnModule(Module &M) {
1502cab237bSDimitry Andric   Function *Main = nullptr;
1512cab237bSDimitry Andric   CallInst *CallMain = nullptr;
15224e2fe98SDimitry Andric   SmallVector<std::pair<Use *, Function *>, 0> Uses;
153f1a29dd3SDimitry Andric   SmallPtrSet<Constant *, 2> ConstantBCs;
15424e2fe98SDimitry Andric 
15524e2fe98SDimitry Andric   // Collect all the places that need wrappers.
1562cab237bSDimitry Andric   for (Function &F : M) {
1572cab237bSDimitry Andric     FindUses(&F, F, Uses, ConstantBCs);
1582cab237bSDimitry Andric 
1592cab237bSDimitry Andric     // If we have a "main" function, and its type isn't
1602cab237bSDimitry Andric     // "int main(int argc, char *argv[])", create an artificial call with it
1612cab237bSDimitry Andric     // bitcasted to that type so that we generate a wrapper for it, so that
1622cab237bSDimitry Andric     // the C runtime can call it.
1632cab237bSDimitry Andric     if (!TemporaryWorkarounds && !F.isDeclaration() && F.getName() == "main") {
1642cab237bSDimitry Andric       Main = &F;
1652cab237bSDimitry Andric       LLVMContext &C = M.getContext();
1662cab237bSDimitry Andric       Type *MainArgTys[] = {
1672cab237bSDimitry Andric         PointerType::get(Type::getInt8PtrTy(C), 0),
1682cab237bSDimitry Andric         Type::getInt32Ty(C)
1692cab237bSDimitry Andric       };
1702cab237bSDimitry Andric       FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
1712cab237bSDimitry Andric                                                /*isVarArg=*/false);
1722cab237bSDimitry Andric       if (F.getFunctionType() != MainTy) {
1732cab237bSDimitry Andric         Value *Args[] = {
1742cab237bSDimitry Andric           UndefValue::get(MainArgTys[0]),
1752cab237bSDimitry Andric           UndefValue::get(MainArgTys[1])
1762cab237bSDimitry Andric         };
1772cab237bSDimitry Andric         Value *Casted = ConstantExpr::getBitCast(Main,
1782cab237bSDimitry Andric                                                  PointerType::get(MainTy, 0));
1792cab237bSDimitry Andric         CallMain = CallInst::Create(Casted, Args, "call_main");
1802cab237bSDimitry Andric         Use *UseMain = &CallMain->getOperandUse(2);
1812cab237bSDimitry Andric         Uses.push_back(std::make_pair(UseMain, &F));
1822cab237bSDimitry Andric       }
1832cab237bSDimitry Andric     }
1842cab237bSDimitry Andric   }
18524e2fe98SDimitry Andric 
18624e2fe98SDimitry Andric   DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
18724e2fe98SDimitry Andric 
18824e2fe98SDimitry Andric   for (auto &UseFunc : Uses) {
18924e2fe98SDimitry Andric     Use *U = UseFunc.first;
19024e2fe98SDimitry Andric     Function *F = UseFunc.second;
19124e2fe98SDimitry Andric     PointerType *PTy = cast<PointerType>(U->get()->getType());
19224e2fe98SDimitry Andric     FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType());
19324e2fe98SDimitry Andric 
19424e2fe98SDimitry Andric     // If the function is casted to something like i8* as a "generic pointer"
19524e2fe98SDimitry Andric     // to be later casted to something else, we can't generate a wrapper for it.
19624e2fe98SDimitry Andric     // Just ignore such casts for now.
19724e2fe98SDimitry Andric     if (!Ty)
1987a7e6055SDimitry Andric       continue;
1997a7e6055SDimitry Andric 
2002cab237bSDimitry Andric     // Bitcasted vararg functions occur in Emscripten's implementation of
2012cab237bSDimitry Andric     // EM_ASM, so suppress wrappers for them for now.
2022cab237bSDimitry Andric     if (TemporaryWorkarounds && (Ty->isVarArg() || F->isVarArg()))
20324e2fe98SDimitry Andric       continue;
20424e2fe98SDimitry Andric 
20524e2fe98SDimitry Andric     auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
20624e2fe98SDimitry Andric     if (Pair.second)
20724e2fe98SDimitry Andric       Pair.first->second = CreateWrapper(F, Ty);
20824e2fe98SDimitry Andric 
20924e2fe98SDimitry Andric     Function *Wrapper = Pair.first->second;
21024e2fe98SDimitry Andric     if (!Wrapper)
21124e2fe98SDimitry Andric       continue;
21224e2fe98SDimitry Andric 
21324e2fe98SDimitry Andric     if (isa<Constant>(U->get()))
21424e2fe98SDimitry Andric       U->get()->replaceAllUsesWith(Wrapper);
21524e2fe98SDimitry Andric     else
21624e2fe98SDimitry Andric       U->set(Wrapper);
21724e2fe98SDimitry Andric   }
21824e2fe98SDimitry Andric 
2192cab237bSDimitry Andric   // If we created a wrapper for main, rename the wrapper so that it's the
2202cab237bSDimitry Andric   // one that gets called from startup.
2212cab237bSDimitry Andric   if (CallMain) {
2222cab237bSDimitry Andric     Main->setName("__original_main");
2232cab237bSDimitry Andric     Function *MainWrapper =
2242cab237bSDimitry Andric         cast<Function>(CallMain->getCalledValue()->stripPointerCasts());
2252cab237bSDimitry Andric     MainWrapper->setName("main");
2262cab237bSDimitry Andric     MainWrapper->setLinkage(Main->getLinkage());
2272cab237bSDimitry Andric     MainWrapper->setVisibility(Main->getVisibility());
2282cab237bSDimitry Andric     Main->setLinkage(Function::PrivateLinkage);
2292cab237bSDimitry Andric     Main->setVisibility(Function::DefaultVisibility);
2302cab237bSDimitry Andric     delete CallMain;
2312cab237bSDimitry Andric   }
2322cab237bSDimitry Andric 
23324e2fe98SDimitry Andric   return true;
23424e2fe98SDimitry Andric }
235