1 //===-- RenderScriptx86ABIFixups.cpp ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/IR/BasicBlock.h"
14 #include "llvm/IR/CallSite.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Instruction.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IRReader/IRReader.h"
21 #include "llvm/Pass.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Utility/Log.h"
26 using namespace lldb_private;
29 bool isRSAPICall(llvm::Module &module, llvm::CallInst *call_inst) {
30 // TODO get the list of renderscript modules from lldb and check if
31 // this llvm::Module calls into any of them.
33 const auto func_name = call_inst->getCalledFunction()->getName();
34 if (func_name.startswith("llvm") || func_name.startswith("lldb"))
37 if (call_inst->getCalledFunction()->isIntrinsic())
43 bool isRSLargeReturnCall(llvm::Module &module, llvm::CallInst *call_inst) {
44 // i686 and x86_64 returns for large vectors in the RenderScript API are not
45 // handled as normal register pairs, but as a hidden sret type. This is not
46 // reflected in the debug info or mangled symbol name, and the android ABI
47 // for x86 and x86_64, (as well as the emulators) specifies there is no AVX,
48 // so bcc generates an sret function because we cannot natively return
50 // This function simply checks whether a function has a > 128bit return type.
51 // It is perhaps an unreliable heuristic, and relies on bcc not generating
52 // AVX code, so if the android ABI one day provides for AVX, this function
53 // may go out of fashion.
55 if (!call_inst || !call_inst->getCalledFunction())
58 return call_inst->getCalledFunction()
60 ->getPrimitiveSizeInBits() > 128;
63 bool isRSAllocationPtrTy(const llvm::Type *type) {
64 if (!type->isPointerTy())
66 auto ptr_type = type->getPointerElementType();
68 return ptr_type->isStructTy() &&
69 ptr_type->getStructName().startswith("struct.rs_allocation");
72 bool isRSAllocationTyCallSite(llvm::Module &module, llvm::CallInst *call_inst) {
74 if (!call_inst->hasByValArgument())
76 for (const auto ¶m : call_inst->operand_values())
77 if (isRSAllocationPtrTy(param->getType()))
82 llvm::FunctionType *cloneToStructRetFnTy(llvm::CallInst *call_inst) {
83 // on x86 StructReturn functions return a pointer to the return value, rather
84 // than the return value itself
85 // [ref](http://www.agner.org/optimize/calling_conventions.pdf section 6). We
86 // create a return type by getting the pointer type of the old return type,
87 // and inserting a new initial argument of pointer type of the original
90 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_EXPRESSIONS));
92 assert(call_inst && "no CallInst");
93 llvm::Function *orig = call_inst->getCalledFunction();
94 assert(orig && "CallInst has no called function");
95 llvm::FunctionType *orig_type = orig->getFunctionType();
96 auto name = orig->getName();
98 log->Printf("%s - cloning to StructRet function for '%s'", __FUNCTION__,
101 unsigned num_params = orig_type->getNumParams();
102 std::vector<llvm::Type *> new_params{num_params + 1, nullptr};
103 std::vector<llvm::Type *> params{orig_type->param_begin(),
104 orig_type->param_end()};
106 // This may not work if the function is somehow declared void as llvm is
107 // strongly typed and represents void* with i8*
108 assert(!orig_type->getReturnType()->isVoidTy() &&
109 "Cannot add StructRet attribute to void function");
110 llvm::PointerType *return_type_ptr_type =
111 llvm::PointerType::getUnqual(orig->getReturnType());
112 assert(return_type_ptr_type &&
113 "failed to get function return type PointerType");
114 if (!return_type_ptr_type)
118 log->Printf("%s - return type pointer type for StructRet clone @ '0x%p':\n",
119 __FUNCTION__, (void *)return_type_ptr_type);
120 // put the sret pointer argument in place at the beginning of the
122 params.emplace(params.begin(), return_type_ptr_type);
123 assert(params.size() == num_params + 1);
124 return llvm::FunctionType::get(return_type_ptr_type, params,
128 bool findRSCallSites(llvm::Module &module,
129 std::set<llvm::CallInst *> &rs_callsites,
130 bool (*predicate)(llvm::Module &, llvm::CallInst *)) {
133 for (auto &func : module.getFunctionList())
134 for (auto &block : func.getBasicBlockList())
135 for (auto &inst : block) {
136 llvm::CallInst *call_inst =
137 llvm::dyn_cast_or_null<llvm::CallInst>(&inst);
138 if (!call_inst || !call_inst->getCalledFunction())
139 // This is not the call-site you are looking for...
141 if (isRSAPICall(module, call_inst) && predicate(module, call_inst)) {
142 rs_callsites.insert(call_inst);
149 bool fixupX86StructRetCalls(llvm::Module &module) {
150 bool changed = false;
151 // changing a basic block while iterating over it seems to have some
152 // undefined behaviour going on so we find all RS callsites first, then fix
153 // them up after consuming the iterator.
154 std::set<llvm::CallInst *> rs_callsites;
155 if (!findRSCallSites(module, rs_callsites, isRSLargeReturnCall))
158 for (auto call_inst : rs_callsites) {
159 llvm::FunctionType *new_func_type = cloneToStructRetFnTy(call_inst);
160 assert(new_func_type &&
161 "failed to clone functionType for Renderscript ABI fixup");
163 llvm::CallSite call_site(call_inst);
164 llvm::Function *func = call_inst->getCalledFunction();
165 assert(func && "cannot resolve function in RenderScriptRuntime");
166 // Copy the original call arguments
167 std::vector<llvm::Value *> new_call_args(call_site.arg_begin(),
168 call_site.arg_end());
170 // Allocate enough space to store the return value of the original function
171 // we pass a pointer to this allocation as the StructRet param, and then
172 // copy its value into the lldb return value
173 const llvm::DataLayout &DL = module.getDataLayout();
174 llvm::AllocaInst *return_value_alloc = new llvm::AllocaInst(
175 func->getReturnType(), DL.getAllocaAddrSpace(), "var_vector_return_alloc",
177 // use the new allocation as the new first argument
178 new_call_args.emplace(new_call_args.begin(),
179 llvm::cast<llvm::Value>(return_value_alloc));
180 llvm::PointerType *new_func_ptr_type =
181 llvm::PointerType::get(new_func_type, 0);
182 // Create the type cast from the old function type to the new one
183 llvm::Constant *new_func_cast = llvm::ConstantExpr::getCast(
184 llvm::Instruction::BitCast, func, new_func_ptr_type);
185 // create an allocation for a new function pointer
186 llvm::AllocaInst *new_func_ptr =
187 new llvm::AllocaInst(new_func_ptr_type, DL.getAllocaAddrSpace(),
188 "new_func_ptr", call_inst);
189 // store the new_func_cast to the newly allocated space
190 (new llvm::StoreInst(new_func_cast, new_func_ptr, call_inst))
191 ->setName("new_func_ptr_load_cast");
192 // load the new function address ready for a jump
193 llvm::LoadInst *new_func_addr_load =
194 new llvm::LoadInst(new_func_ptr, "load_func_pointer", call_inst);
195 // and create a callinstruction from it
196 llvm::CallInst *new_call_inst = llvm::CallInst::Create(
197 new_func_addr_load, new_call_args, "new_func_call", call_inst);
198 new_call_inst->setCallingConv(call_inst->getCallingConv());
199 new_call_inst->setTailCall(call_inst->isTailCall());
200 llvm::LoadInst *lldb_save_result_address =
201 new llvm::LoadInst(return_value_alloc, "save_return_val", call_inst);
203 // Now remove the old broken call
204 call_inst->replaceAllUsesWith(lldb_save_result_address);
205 call_inst->eraseFromParent();
211 bool fixupRSAllocationStructByValCalls(llvm::Module &module) {
212 // On x86_64, calls to functions in the RS runtime that take an
213 // `rs_allocation` type argument are actually handled as by-ref params by
214 // bcc, but appear to be passed by value by lldb (the callsite all use
215 // `struct byval`). On x86_64 Linux, struct arguments are transferred in
216 // registers if the struct size is no bigger than 128bits
217 // [ref](http://www.agner.org/optimize/calling_conventions.pdf) section 7.1
218 // "Passing and returning objects" otherwise passed on the stack. an object
219 // of type `rs_allocation` is actually 256bits, so should be passed on the
220 // stack. However, code generated by bcc actually treats formal params of
221 // type `rs_allocation` as `rs_allocation *` so we need to convert the
222 // calling convention to pass by reference, and remove any hint of byval from
223 // formal parameters.
224 bool changed = false;
225 std::set<llvm::CallInst *> rs_callsites;
226 if (!findRSCallSites(module, rs_callsites, isRSAllocationTyCallSite))
229 std::set<llvm::Function *> rs_functions;
231 // for all call instructions
232 for (auto call_inst : rs_callsites) {
233 // add the called function to a set so that we can strip its byval
234 // attributes in another pass
235 rs_functions.insert(call_inst->getCalledFunction());
237 // get the function attributes
238 llvm::AttributeList call_attribs = call_inst->getAttributes();
240 // iterate over the argument attributes
241 for (unsigned I = call_attribs.index_begin(); I != call_attribs.index_end();
243 // if this argument is passed by val
244 if (call_attribs.hasAttribute(I, llvm::Attribute::ByVal)) {
245 // strip away the byval attribute
246 call_inst->removeAttribute(I, llvm::Attribute::ByVal);
252 // for all called function decls
253 for (auto func : rs_functions) {
254 // inspect all of the arguments in the call
255 for (auto &arg : func->args()) {
256 if (arg.hasByValAttr()) {
257 arg.removeAttr(llvm::Attribute::ByVal);
264 } // end anonymous namespace
266 namespace lldb_private {
267 namespace lldb_renderscript {
269 bool fixupX86FunctionCalls(llvm::Module &module) {
270 return fixupX86StructRetCalls(module);
273 bool fixupX86_64FunctionCalls(llvm::Module &module) {
274 bool changed = false;
275 changed |= fixupX86StructRetCalls(module);
276 changed |= fixupRSAllocationStructByValCalls(module);
280 } // end namespace lldb_renderscript
281 } // end namespace lldb_private