11b637458SDan Gohman //===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
21b637458SDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61b637458SDan Gohman //
71b637458SDan Gohman //===----------------------------------------------------------------------===//
81b637458SDan Gohman ///
91b637458SDan Gohman /// \file
105f8f34e4SAdrian Prantl /// Fix bitcasted functions.
111b637458SDan Gohman ///
121b637458SDan Gohman /// WebAssembly requires caller and callee signatures to match, however in LLVM,
131b637458SDan Gohman /// some amount of slop is vaguely permitted. Detect mismatch by looking for
141b637458SDan Gohman /// bitcasts of functions and rewrite them to use wrapper functions instead.
151b637458SDan Gohman ///
161b637458SDan Gohman /// This doesn't catch all cases, such as when a function's address is taken in
171b637458SDan Gohman /// one place and casted in another, but it works for many common cases.
181b637458SDan Gohman ///
191b637458SDan Gohman /// Note that LLVM already optimizes away function bitcasts in common cases by
201b637458SDan Gohman /// dropping arguments as needed, so this pass only ends up getting used in less
211b637458SDan Gohman /// common cases.
221b637458SDan Gohman ///
231b637458SDan Gohman //===----------------------------------------------------------------------===//
241b637458SDan Gohman 
251b637458SDan Gohman #include "WebAssembly.h"
2637af00e7SJacob Gravelle #include "llvm/IR/CallSite.h"
271b637458SDan Gohman #include "llvm/IR/Constants.h"
281b637458SDan Gohman #include "llvm/IR/Instructions.h"
291b637458SDan Gohman #include "llvm/IR/Module.h"
301b637458SDan Gohman #include "llvm/IR/Operator.h"
311b637458SDan Gohman #include "llvm/Pass.h"
321b637458SDan Gohman #include "llvm/Support/Debug.h"
331b637458SDan Gohman #include "llvm/Support/raw_ostream.h"
341b637458SDan Gohman using namespace llvm;
351b637458SDan Gohman 
361b637458SDan Gohman #define DEBUG_TYPE "wasm-fix-function-bitcasts"
371b637458SDan Gohman 
381b637458SDan Gohman namespace {
391b637458SDan Gohman class FixFunctionBitcasts final : public ModulePass {
401b637458SDan Gohman   StringRef getPassName() const override {
411b637458SDan Gohman     return "WebAssembly Fix Function Bitcasts";
421b637458SDan Gohman   }
431b637458SDan Gohman 
441b637458SDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
451b637458SDan Gohman     AU.setPreservesCFG();
461b637458SDan Gohman     ModulePass::getAnalysisUsage(AU);
471b637458SDan Gohman   }
481b637458SDan Gohman 
491b637458SDan Gohman   bool runOnModule(Module &M) override;
501b637458SDan Gohman 
511b637458SDan Gohman public:
521b637458SDan Gohman   static char ID;
531b637458SDan Gohman   FixFunctionBitcasts() : ModulePass(ID) {}
541b637458SDan Gohman };
551b637458SDan Gohman } // End anonymous namespace
561b637458SDan Gohman 
571b637458SDan Gohman char FixFunctionBitcasts::ID = 0;
5840926451SJacob Gravelle INITIALIZE_PASS(FixFunctionBitcasts, DEBUG_TYPE,
5940926451SJacob Gravelle                 "Fix mismatching bitcasts for WebAssembly", false, false)
6040926451SJacob Gravelle 
611b637458SDan Gohman ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
621b637458SDan Gohman   return new FixFunctionBitcasts();
631b637458SDan Gohman }
641b637458SDan Gohman 
651b637458SDan Gohman // Recursively descend the def-use lists from V to find non-bitcast users of
661b637458SDan Gohman // bitcasts of V.
6718c56a07SHeejin Ahn static void findUses(Value *V, Function &F,
687acb42a4SDerek Schuff                      SmallVectorImpl<std::pair<Use *, Function *>> &Uses,
697acb42a4SDerek Schuff                      SmallPtrSetImpl<Constant *> &ConstantBCs) {
701b637458SDan Gohman   for (Use &U : V->uses()) {
7118c56a07SHeejin Ahn     if (auto *BC = dyn_cast<BitCastOperator>(U.getUser()))
7218c56a07SHeejin Ahn       findUses(BC, F, Uses, ConstantBCs);
73*dde8a25aSSam Clegg     else if (auto *A = dyn_cast<GlobalAlias>(U.getUser()))
74*dde8a25aSSam Clegg       findUses(A, F, Uses, ConstantBCs);
757acb42a4SDerek Schuff     else if (U.get()->getType() != F.getType()) {
7637af00e7SJacob Gravelle       CallSite CS(U.getUser());
7737af00e7SJacob Gravelle       if (!CS)
7837af00e7SJacob Gravelle         // Skip uses that aren't immediately called
7937af00e7SJacob Gravelle         continue;
8037af00e7SJacob Gravelle       Value *Callee = CS.getCalledValue();
8137af00e7SJacob Gravelle       if (Callee != V)
8237af00e7SJacob Gravelle         // Skip calls where the function isn't the callee
8337af00e7SJacob Gravelle         continue;
847acb42a4SDerek Schuff       if (isa<Constant>(U.get())) {
857acb42a4SDerek Schuff         // Only add constant bitcasts to the list once; they get RAUW'd
8618c56a07SHeejin Ahn         auto C = ConstantBCs.insert(cast<Constant>(U.get()));
8718c56a07SHeejin Ahn         if (!C.second)
8837af00e7SJacob Gravelle           continue;
897acb42a4SDerek Schuff       }
901b637458SDan Gohman       Uses.push_back(std::make_pair(&U, &F));
911b637458SDan Gohman     }
921b637458SDan Gohman   }
937acb42a4SDerek Schuff }
941b637458SDan Gohman 
951b637458SDan Gohman // Create a wrapper function with type Ty that calls F (which may have a
961b637458SDan Gohman // different type). Attempt to support common bitcasted function idioms:
971b637458SDan Gohman //  - Call with more arguments than needed: arguments are dropped
981b637458SDan Gohman //  - Call with fewer arguments than needed: arguments are filled in with undef
991b637458SDan Gohman //  - Return value is not needed: drop it
1001b637458SDan Gohman //  - Return value needed but not present: supply an undef
1010e2ceb81SDan Gohman //
10241d7047dSSam Clegg // If the all the argument types of trivially castable to one another (i.e.
10341d7047dSSam Clegg // I32 vs pointer type) then we don't create a wrapper at all (return nullptr
10441d7047dSSam Clegg // instead).
10541d7047dSSam Clegg //
10688599bf6SSam Clegg // If there is a type mismatch that we know would result in an invalid wasm
10788599bf6SSam Clegg // module then generate wrapper that contains unreachable (i.e. abort at
10888599bf6SSam Clegg // runtime).  Such programs are deep into undefined behaviour territory,
10941d7047dSSam Clegg // but we choose to fail at runtime rather than generate and invalid module
11041d7047dSSam Clegg // or fail at compiler time.  The reason we delay the error is that we want
11141d7047dSSam Clegg // to support the CMake which expects to be able to compile and link programs
11241d7047dSSam Clegg // that refer to functions with entirely incorrect signatures (this is how
11341d7047dSSam Clegg // CMake detects the existence of a function in a toolchain).
11488599bf6SSam Clegg //
11588599bf6SSam Clegg // For bitcasts that involve struct types we don't know at this stage if they
11688599bf6SSam Clegg // would be equivalent at the wasm level and so we can't know if we need to
11788599bf6SSam Clegg // generate a wrapper.
11818c56a07SHeejin Ahn static Function *createWrapper(Function *F, FunctionType *Ty) {
1191b637458SDan Gohman   Module *M = F->getParent();
1201b637458SDan Gohman 
12141d7047dSSam Clegg   Function *Wrapper = Function::Create(Ty, Function::PrivateLinkage,
12241d7047dSSam Clegg                                        F->getName() + "_bitcast", M);
1231b637458SDan Gohman   BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
12441d7047dSSam Clegg   const DataLayout &DL = BB->getModule()->getDataLayout();
1251b637458SDan Gohman 
1261b637458SDan Gohman   // Determine what arguments to pass.
1271b637458SDan Gohman   SmallVector<Value *, 4> Args;
1281b637458SDan Gohman   Function::arg_iterator AI = Wrapper->arg_begin();
1292803bfafSDan Gohman   Function::arg_iterator AE = Wrapper->arg_end();
1301b637458SDan Gohman   FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
1311b637458SDan Gohman   FunctionType::param_iterator PE = F->getFunctionType()->param_end();
13241d7047dSSam Clegg   bool TypeMismatch = false;
13341d7047dSSam Clegg   bool WrapperNeeded = false;
13441d7047dSSam Clegg 
13588599bf6SSam Clegg   Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
13688599bf6SSam Clegg   Type *RtnType = Ty->getReturnType();
13788599bf6SSam Clegg 
13841d7047dSSam Clegg   if ((F->getFunctionType()->getNumParams() != Ty->getNumParams()) ||
13988599bf6SSam Clegg       (F->getFunctionType()->isVarArg() != Ty->isVarArg()) ||
14088599bf6SSam Clegg       (ExpectedRtnType != RtnType))
14141d7047dSSam Clegg     WrapperNeeded = true;
14241d7047dSSam Clegg 
1432803bfafSDan Gohman   for (; AI != AE && PI != PE; ++AI, ++PI) {
14441d7047dSSam Clegg     Type *ArgType = AI->getType();
14541d7047dSSam Clegg     Type *ParamType = *PI;
14641d7047dSSam Clegg 
14741d7047dSSam Clegg     if (ArgType == ParamType) {
1481b637458SDan Gohman       Args.push_back(&*AI);
14941d7047dSSam Clegg     } else {
15041d7047dSSam Clegg       if (CastInst::isBitOrNoopPointerCastable(ArgType, ParamType, DL)) {
15141d7047dSSam Clegg         Instruction *PtrCast =
15241d7047dSSam Clegg             CastInst::CreateBitOrPointerCast(AI, ParamType, "cast");
15341d7047dSSam Clegg         BB->getInstList().push_back(PtrCast);
15441d7047dSSam Clegg         Args.push_back(PtrCast);
15588599bf6SSam Clegg       } else if (ArgType->isStructTy() || ParamType->isStructTy()) {
15618c56a07SHeejin Ahn         LLVM_DEBUG(dbgs() << "createWrapper: struct param type in bitcast: "
15788599bf6SSam Clegg                           << F->getName() << "\n");
15888599bf6SSam Clegg         WrapperNeeded = false;
15941d7047dSSam Clegg       } else {
16018c56a07SHeejin Ahn         LLVM_DEBUG(dbgs() << "createWrapper: arg type mismatch calling: "
16141d7047dSSam Clegg                           << F->getName() << "\n");
16241d7047dSSam Clegg         LLVM_DEBUG(dbgs() << "Arg[" << Args.size() << "] Expected: "
16341d7047dSSam Clegg                           << *ParamType << " Got: " << *ArgType << "\n");
16441d7047dSSam Clegg         TypeMismatch = true;
16541d7047dSSam Clegg         break;
1661b637458SDan Gohman       }
16741d7047dSSam Clegg     }
16841d7047dSSam Clegg   }
16941d7047dSSam Clegg 
17088599bf6SSam Clegg   if (WrapperNeeded && !TypeMismatch) {
1711b637458SDan Gohman     for (; PI != PE; ++PI)
1721b637458SDan Gohman       Args.push_back(UndefValue::get(*PI));
1732803bfafSDan Gohman     if (F->isVarArg())
1742803bfafSDan Gohman       for (; AI != AE; ++AI)
1752803bfafSDan Gohman         Args.push_back(&*AI);
1761b637458SDan Gohman 
1771b637458SDan Gohman     CallInst *Call = CallInst::Create(F, Args, "", BB);
1781b637458SDan Gohman 
17941d7047dSSam Clegg     Type *ExpectedRtnType = F->getFunctionType()->getReturnType();
18041d7047dSSam Clegg     Type *RtnType = Ty->getReturnType();
1811b637458SDan Gohman     // Determine what value to return.
18241d7047dSSam Clegg     if (RtnType->isVoidTy()) {
1831b637458SDan Gohman       ReturnInst::Create(M->getContext(), BB);
18441d7047dSSam Clegg     } else if (ExpectedRtnType->isVoidTy()) {
18588599bf6SSam Clegg       LLVM_DEBUG(dbgs() << "Creating dummy return: " << *RtnType << "\n");
18641d7047dSSam Clegg       ReturnInst::Create(M->getContext(), UndefValue::get(RtnType), BB);
18741d7047dSSam Clegg     } else if (RtnType == ExpectedRtnType) {
1881b637458SDan Gohman       ReturnInst::Create(M->getContext(), Call, BB);
18941d7047dSSam Clegg     } else if (CastInst::isBitOrNoopPointerCastable(ExpectedRtnType, RtnType,
19041d7047dSSam Clegg                                                     DL)) {
19141d7047dSSam Clegg       Instruction *Cast =
19241d7047dSSam Clegg           CastInst::CreateBitOrPointerCast(Call, RtnType, "cast");
19341d7047dSSam Clegg       BB->getInstList().push_back(Cast);
19441d7047dSSam Clegg       ReturnInst::Create(M->getContext(), Cast, BB);
19588599bf6SSam Clegg     } else if (RtnType->isStructTy() || ExpectedRtnType->isStructTy()) {
19618c56a07SHeejin Ahn       LLVM_DEBUG(dbgs() << "createWrapper: struct return type in bitcast: "
19788599bf6SSam Clegg                         << F->getName() << "\n");
19888599bf6SSam Clegg       WrapperNeeded = false;
19941d7047dSSam Clegg     } else {
20018c56a07SHeejin Ahn       LLVM_DEBUG(dbgs() << "createWrapper: return type mismatch calling: "
20141d7047dSSam Clegg                         << F->getName() << "\n");
20241d7047dSSam Clegg       LLVM_DEBUG(dbgs() << "Expected: " << *ExpectedRtnType
20341d7047dSSam Clegg                         << " Got: " << *RtnType << "\n");
20441d7047dSSam Clegg       TypeMismatch = true;
20541d7047dSSam Clegg     }
20641d7047dSSam Clegg   }
20741d7047dSSam Clegg 
20841d7047dSSam Clegg   if (TypeMismatch) {
20988599bf6SSam Clegg     // Create a new wrapper that simply contains `unreachable`.
21088599bf6SSam Clegg     Wrapper->eraseFromParent();
211f208f631SHeejin Ahn     Wrapper = Function::Create(Ty, Function::PrivateLinkage,
212f208f631SHeejin Ahn                                F->getName() + "_bitcast_invalid", M);
21388599bf6SSam Clegg     BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
21441d7047dSSam Clegg     new UnreachableInst(M->getContext(), BB);
21541d7047dSSam Clegg     Wrapper->setName(F->getName() + "_bitcast_invalid");
21641d7047dSSam Clegg   } else if (!WrapperNeeded) {
21718c56a07SHeejin Ahn     LLVM_DEBUG(dbgs() << "createWrapper: no wrapper needed: " << F->getName()
21841d7047dSSam Clegg                       << "\n");
2190e2ceb81SDan Gohman     Wrapper->eraseFromParent();
2200e2ceb81SDan Gohman     return nullptr;
2210e2ceb81SDan Gohman   }
22218c56a07SHeejin Ahn   LLVM_DEBUG(dbgs() << "createWrapper: " << F->getName() << "\n");
2231b637458SDan Gohman   return Wrapper;
2241b637458SDan Gohman }
2251b637458SDan Gohman 
2264684f824SDan Gohman // Test whether a main function with type FuncTy should be rewritten to have
2274684f824SDan Gohman // type MainTy.
228711950c1SBenjamin Kramer static bool shouldFixMainFunction(FunctionType *FuncTy, FunctionType *MainTy) {
2294684f824SDan Gohman   // Only fix the main function if it's the standard zero-arg form. That way,
2304684f824SDan Gohman   // the standard cases will work as expected, and users will see signature
2314684f824SDan Gohman   // mismatches from the linker for non-standard cases.
2324684f824SDan Gohman   return FuncTy->getReturnType() == MainTy->getReturnType() &&
2334684f824SDan Gohman          FuncTy->getNumParams() == 0 &&
2344684f824SDan Gohman          !FuncTy->isVarArg();
2354684f824SDan Gohman }
2364684f824SDan Gohman 
2371b637458SDan Gohman bool FixFunctionBitcasts::runOnModule(Module &M) {
238569f0909SHeejin Ahn   LLVM_DEBUG(dbgs() << "********** Fix Function Bitcasts **********\n");
239569f0909SHeejin Ahn 
2406736f590SDan Gohman   Function *Main = nullptr;
2416736f590SDan Gohman   CallInst *CallMain = nullptr;
242d5eda355SDan Gohman   SmallVector<std::pair<Use *, Function *>, 0> Uses;
2437acb42a4SDerek Schuff   SmallPtrSet<Constant *, 2> ConstantBCs;
244d5eda355SDan Gohman 
2451b637458SDan Gohman   // Collect all the places that need wrappers.
2466736f590SDan Gohman   for (Function &F : M) {
24718c56a07SHeejin Ahn     findUses(&F, F, Uses, ConstantBCs);
2486736f590SDan Gohman 
2496736f590SDan Gohman     // If we have a "main" function, and its type isn't
2506736f590SDan Gohman     // "int main(int argc, char *argv[])", create an artificial call with it
2516736f590SDan Gohman     // bitcasted to that type so that we generate a wrapper for it, so that
2526736f590SDan Gohman     // the C runtime can call it.
2534684f824SDan Gohman     if (F.getName() == "main") {
2546736f590SDan Gohman       Main = &F;
2556736f590SDan Gohman       LLVMContext &C = M.getContext();
25679c054f6SSam Clegg       Type *MainArgTys[] = {Type::getInt32Ty(C),
25779c054f6SSam Clegg                             PointerType::get(Type::getInt8PtrTy(C), 0)};
2586736f590SDan Gohman       FunctionType *MainTy = FunctionType::get(Type::getInt32Ty(C), MainArgTys,
2596736f590SDan Gohman                                                /*isVarArg=*/false);
26018c56a07SHeejin Ahn       if (shouldFixMainFunction(F.getFunctionType(), MainTy)) {
26179c054f6SSam Clegg         LLVM_DEBUG(dbgs() << "Found `main` function with incorrect type: "
26279c054f6SSam Clegg                           << *F.getFunctionType() << "\n");
263f208f631SHeejin Ahn         Value *Args[] = {UndefValue::get(MainArgTys[0]),
264f208f631SHeejin Ahn                          UndefValue::get(MainArgTys[1])};
265f208f631SHeejin Ahn         Value *Casted =
266f208f631SHeejin Ahn             ConstantExpr::getBitCast(Main, PointerType::get(MainTy, 0));
2677976eb58SJames Y Knight         CallMain = CallInst::Create(MainTy, Casted, Args, "call_main");
2686736f590SDan Gohman         Use *UseMain = &CallMain->getOperandUse(2);
2696736f590SDan Gohman         Uses.push_back(std::make_pair(UseMain, &F));
2706736f590SDan Gohman       }
2716736f590SDan Gohman     }
2726736f590SDan Gohman   }
2731b637458SDan Gohman 
2741b637458SDan Gohman   DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
2751b637458SDan Gohman 
2761b637458SDan Gohman   for (auto &UseFunc : Uses) {
2771b637458SDan Gohman     Use *U = UseFunc.first;
2781b637458SDan Gohman     Function *F = UseFunc.second;
27918c56a07SHeejin Ahn     auto *PTy = cast<PointerType>(U->get()->getType());
28018c56a07SHeejin Ahn     auto *Ty = dyn_cast<FunctionType>(PTy->getElementType());
2811b637458SDan Gohman 
2821b637458SDan Gohman     // If the function is casted to something like i8* as a "generic pointer"
2831b637458SDan Gohman     // to be later casted to something else, we can't generate a wrapper for it.
2841b637458SDan Gohman     // Just ignore such casts for now.
2851b637458SDan Gohman     if (!Ty)
2861b637458SDan Gohman       continue;
2871b637458SDan Gohman 
2881b637458SDan Gohman     auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
2891b637458SDan Gohman     if (Pair.second)
29018c56a07SHeejin Ahn       Pair.first->second = createWrapper(F, Ty);
2911b637458SDan Gohman 
2920e2ceb81SDan Gohman     Function *Wrapper = Pair.first->second;
2930e2ceb81SDan Gohman     if (!Wrapper)
2940e2ceb81SDan Gohman       continue;
2950e2ceb81SDan Gohman 
2961b637458SDan Gohman     if (isa<Constant>(U->get()))
2970e2ceb81SDan Gohman       U->get()->replaceAllUsesWith(Wrapper);
2981b637458SDan Gohman     else
2990e2ceb81SDan Gohman       U->set(Wrapper);
3001b637458SDan Gohman   }
3011b637458SDan Gohman 
3026736f590SDan Gohman   // If we created a wrapper for main, rename the wrapper so that it's the
3036736f590SDan Gohman   // one that gets called from startup.
3046736f590SDan Gohman   if (CallMain) {
3056736f590SDan Gohman     Main->setName("__original_main");
30618c56a07SHeejin Ahn     auto *MainWrapper =
3076736f590SDan Gohman         cast<Function>(CallMain->getCalledValue()->stripPointerCasts());
3084684f824SDan Gohman     delete CallMain;
3094684f824SDan Gohman     if (Main->isDeclaration()) {
3104684f824SDan Gohman       // The wrapper is not needed in this case as we don't need to export
3114684f824SDan Gohman       // it to anyone else.
3124684f824SDan Gohman       MainWrapper->eraseFromParent();
3134684f824SDan Gohman     } else {
3144684f824SDan Gohman       // Otherwise give the wrapper the same linkage as the original main
3154684f824SDan Gohman       // function, so that it can be called from the same places.
3166736f590SDan Gohman       MainWrapper->setName("main");
3176736f590SDan Gohman       MainWrapper->setLinkage(Main->getLinkage());
3186736f590SDan Gohman       MainWrapper->setVisibility(Main->getVisibility());
3194684f824SDan Gohman     }
3206736f590SDan Gohman   }
3216736f590SDan Gohman 
3221b637458SDan Gohman   return true;
3231b637458SDan Gohman }
324