blob: 76a2ff3f9803b6d8f745d4cd656569545496d6af [file] [log] [blame]
Dan Gohman1b637452017-01-07 00:34:54 +00001//===-- WebAssemblyFixFunctionBitcasts.cpp - Fix function bitcasts --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Fix bitcasted functions.
12///
13/// WebAssembly requires caller and callee signatures to match, however in LLVM,
14/// some amount of slop is vaguely permitted. Detect mismatch by looking for
15/// bitcasts of functions and rewrite them to use wrapper functions instead.
16///
17/// This doesn't catch all cases, such as when a function's address is taken in
18/// one place and casted in another, but it works for many common cases.
19///
20/// Note that LLVM already optimizes away function bitcasts in common cases by
21/// dropping arguments as needed, so this pass only ends up getting used in less
22/// common cases.
23///
24//===----------------------------------------------------------------------===//
25
26#include "WebAssembly.h"
27#include "llvm/IR/Constants.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
Dan Gohman1b637452017-01-07 00:34:54 +000051public:
52 static char ID;
53 FixFunctionBitcasts() : ModulePass(ID) {}
54};
55} // End anonymous namespace
56
57char FixFunctionBitcasts::ID = 0;
58ModulePass *llvm::createWebAssemblyFixFunctionBitcasts() {
59 return new FixFunctionBitcasts();
60}
61
62// Recursively descend the def-use lists from V to find non-bitcast users of
63// bitcasts of V.
64static void FindUses(Value *V, Function &F,
Derek Schuff7acb42a2017-01-10 21:59:53 +000065 SmallVectorImpl<std::pair<Use *, Function *>> &Uses,
66 SmallPtrSetImpl<Constant *> &ConstantBCs) {
Dan Gohman1b637452017-01-07 00:34:54 +000067 for (Use &U : V->uses()) {
68 if (BitCastOperator *BC = dyn_cast<BitCastOperator>(U.getUser()))
Derek Schuff7acb42a2017-01-10 21:59:53 +000069 FindUses(BC, F, Uses, ConstantBCs);
70 else if (U.get()->getType() != F.getType()) {
71 if (isa<Constant>(U.get())) {
72 // Only add constant bitcasts to the list once; they get RAUW'd
73 auto c = ConstantBCs.insert(cast<Constant>(U.get()));
74 if (!c.second) continue;
75 }
Dan Gohman1b637452017-01-07 00:34:54 +000076 Uses.push_back(std::make_pair(&U, &F));
Derek Schuff7acb42a2017-01-10 21:59:53 +000077 }
Dan Gohman1b637452017-01-07 00:34:54 +000078 }
79}
80
81// Create a wrapper function with type Ty that calls F (which may have a
82// different type). Attempt to support common bitcasted function idioms:
83// - Call with more arguments than needed: arguments are dropped
84// - Call with fewer arguments than needed: arguments are filled in with undef
85// - Return value is not needed: drop it
86// - Return value needed but not present: supply an undef
Dan Gohmand37dc2f2017-02-27 22:41:39 +000087//
Dan Gohman0e2ceb82017-01-07 01:50:01 +000088// For now, return nullptr without creating a wrapper if the wrapper cannot
89// be generated due to incompatible types.
Dan Gohman1b637452017-01-07 00:34:54 +000090static Function *CreateWrapper(Function *F, FunctionType *Ty) {
91 Module *M = F->getParent();
92
93 Function *Wrapper =
94 Function::Create(Ty, Function::PrivateLinkage, "bitcast", M);
95 BasicBlock *BB = BasicBlock::Create(M->getContext(), "body", Wrapper);
96
97 // Determine what arguments to pass.
98 SmallVector<Value *, 4> Args;
99 Function::arg_iterator AI = Wrapper->arg_begin();
100 FunctionType::param_iterator PI = F->getFunctionType()->param_begin();
101 FunctionType::param_iterator PE = F->getFunctionType()->param_end();
102 for (; AI != Wrapper->arg_end() && PI != PE; ++AI, ++PI) {
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000103 if (AI->getType() != *PI) {
104 Wrapper->eraseFromParent();
105 return nullptr;
106 }
Dan Gohman1b637452017-01-07 00:34:54 +0000107 Args.push_back(&*AI);
108 }
109 for (; PI != PE; ++PI)
110 Args.push_back(UndefValue::get(*PI));
111
112 CallInst *Call = CallInst::Create(F, Args, "", BB);
113
114 // Determine what value to return.
115 if (Ty->getReturnType()->isVoidTy())
116 ReturnInst::Create(M->getContext(), BB);
117 else if (F->getFunctionType()->getReturnType()->isVoidTy())
118 ReturnInst::Create(M->getContext(), UndefValue::get(Ty->getReturnType()),
119 BB);
120 else if (F->getFunctionType()->getReturnType() == Ty->getReturnType())
121 ReturnInst::Create(M->getContext(), Call, BB);
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000122 else {
123 Wrapper->eraseFromParent();
124 return nullptr;
125 }
Dan Gohman1b637452017-01-07 00:34:54 +0000126
127 return Wrapper;
128}
129
130bool FixFunctionBitcasts::runOnModule(Module &M) {
Dan Gohmand5eda352017-01-07 01:31:18 +0000131 SmallVector<std::pair<Use *, Function *>, 0> Uses;
Derek Schuff7acb42a2017-01-10 21:59:53 +0000132 SmallPtrSet<Constant *, 2> ConstantBCs;
Dan Gohmand5eda352017-01-07 01:31:18 +0000133
Dan Gohman1b637452017-01-07 00:34:54 +0000134 // Collect all the places that need wrappers.
Derek Schuff7acb42a2017-01-10 21:59:53 +0000135 for (Function &F : M) FindUses(&F, F, Uses, ConstantBCs);
Dan Gohman1b637452017-01-07 00:34:54 +0000136
137 DenseMap<std::pair<Function *, FunctionType *>, Function *> Wrappers;
138
139 for (auto &UseFunc : Uses) {
140 Use *U = UseFunc.first;
141 Function *F = UseFunc.second;
142 PointerType *PTy = cast<PointerType>(U->get()->getType());
143 FunctionType *Ty = dyn_cast<FunctionType>(PTy->getElementType());
144
145 // If the function is casted to something like i8* as a "generic pointer"
146 // to be later casted to something else, we can't generate a wrapper for it.
147 // Just ignore such casts for now.
148 if (!Ty)
149 continue;
150
Dan Gohmana99b7172017-01-20 20:50:29 +0000151 // Wasm varargs are not ABI-compatible with non-varargs. Just ignore
152 // such casts for now.
153 if (Ty->isVarArg() || F->isVarArg())
154 continue;
155
Dan Gohman1b637452017-01-07 00:34:54 +0000156 auto Pair = Wrappers.insert(std::make_pair(std::make_pair(F, Ty), nullptr));
157 if (Pair.second)
158 Pair.first->second = CreateWrapper(F, Ty);
159
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000160 Function *Wrapper = Pair.first->second;
161 if (!Wrapper)
162 continue;
163
Dan Gohman1b637452017-01-07 00:34:54 +0000164 if (isa<Constant>(U->get()))
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000165 U->get()->replaceAllUsesWith(Wrapper);
Dan Gohman1b637452017-01-07 00:34:54 +0000166 else
Dan Gohman0e2ceb82017-01-07 01:50:01 +0000167 U->set(Wrapper);
Dan Gohman1b637452017-01-07 00:34:54 +0000168 }
169
170 return true;
171}