180814287SRaphael Isemann //===-- RenderScriptx86ABIFixups.cpp --------------------------------------===//
219459580SLuke Drummond //
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
619459580SLuke Drummond //
719459580SLuke Drummond //===----------------------------------------------------------------------===//
819459580SLuke Drummond 
919459580SLuke Drummond #include <set>
1019459580SLuke Drummond 
1119459580SLuke Drummond #include "llvm/ADT/StringRef.h"
1219459580SLuke Drummond #include "llvm/IR/BasicBlock.h"
1319459580SLuke Drummond #include "llvm/IR/Constants.h"
1419459580SLuke Drummond #include "llvm/IR/Function.h"
1519459580SLuke Drummond #include "llvm/IR/Instruction.h"
1619459580SLuke Drummond #include "llvm/IR/Instructions.h"
1719459580SLuke Drummond #include "llvm/IR/Module.h"
1819459580SLuke Drummond #include "llvm/IRReader/IRReader.h"
1919459580SLuke Drummond #include "llvm/Pass.h"
2019459580SLuke Drummond 
2119459580SLuke Drummond #include "lldb/Target/Process.h"
22c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
236f9e6901SZachary Turner #include "lldb/Utility/Log.h"
2419459580SLuke Drummond 
2519459580SLuke Drummond using namespace lldb_private;
2619459580SLuke Drummond 
27*00fb0504SNikita Popov static bool isRSAPICall(llvm::CallInst *call_inst) {
2819459580SLuke Drummond   // TODO get the list of renderscript modules from lldb and check if
2919459580SLuke Drummond   // this llvm::Module calls into any of them.
3019459580SLuke Drummond   const auto func_name = call_inst->getCalledFunction()->getName();
3119459580SLuke Drummond   if (func_name.startswith("llvm") || func_name.startswith("lldb"))
3219459580SLuke Drummond     return false;
3319459580SLuke Drummond 
3419459580SLuke Drummond   if (call_inst->getCalledFunction()->isIntrinsic())
3519459580SLuke Drummond     return false;
3619459580SLuke Drummond 
3719459580SLuke Drummond   return true;
3819459580SLuke Drummond }
3919459580SLuke Drummond 
40*00fb0504SNikita Popov static bool isRSLargeReturnCall(llvm::CallInst *call_inst) {
41b9c1b51eSKate Stone   // i686 and x86_64 returns for large vectors in the RenderScript API are not
4205097246SAdrian Prantl   // handled as normal register pairs, but as a hidden sret type. This is not
4305097246SAdrian Prantl   // reflected in the debug info or mangled symbol name, and the android ABI
4405097246SAdrian Prantl   // for x86 and x86_64, (as well as the emulators) specifies there is no AVX,
4505097246SAdrian Prantl   // so bcc generates an sret function because we cannot natively return
46b9c1b51eSKate Stone   // 256 bit vectors.
47b9c1b51eSKate Stone   // This function simply checks whether a function has a > 128bit return type.
4805097246SAdrian Prantl   // It is perhaps an unreliable heuristic, and relies on bcc not generating
4905097246SAdrian Prantl   // AVX code, so if the android ABI one day provides for AVX, this function
5005097246SAdrian Prantl   // may go out of fashion.
5119459580SLuke Drummond   if (!call_inst || !call_inst->getCalledFunction())
5219459580SLuke Drummond     return false;
5319459580SLuke Drummond 
54b9c1b51eSKate Stone   return call_inst->getCalledFunction()
55b9c1b51eSKate Stone              ->getReturnType()
56b9c1b51eSKate Stone              ->getPrimitiveSizeInBits() > 128;
5719459580SLuke Drummond }
5819459580SLuke Drummond 
5993c1b3caSPavel Labath static bool isRSAllocationPtrTy(const llvm::Type *type) {
6019459580SLuke Drummond   if (!type->isPointerTy())
6119459580SLuke Drummond     return false;
6219459580SLuke Drummond   auto ptr_type = type->getPointerElementType();
6319459580SLuke Drummond 
64b9c1b51eSKate Stone   return ptr_type->isStructTy() &&
65b9c1b51eSKate Stone          ptr_type->getStructName().startswith("struct.rs_allocation");
6619459580SLuke Drummond }
6719459580SLuke Drummond 
68*00fb0504SNikita Popov static bool isRSAllocationTyCallSite(llvm::CallInst *call_inst) {
6919459580SLuke Drummond   if (!call_inst->hasByValArgument())
7019459580SLuke Drummond     return false;
718dc7b982SMark de Wever   for (const auto *param : call_inst->operand_values())
7219459580SLuke Drummond     if (isRSAllocationPtrTy(param->getType()))
7319459580SLuke Drummond       return true;
7419459580SLuke Drummond   return false;
7519459580SLuke Drummond }
7619459580SLuke Drummond 
7793c1b3caSPavel Labath static llvm::FunctionType *cloneToStructRetFnTy(llvm::CallInst *call_inst) {
78b9c1b51eSKate Stone   // on x86 StructReturn functions return a pointer to the return value, rather
7905097246SAdrian Prantl   // than the return value itself
8005097246SAdrian Prantl   // [ref](http://www.agner.org/optimize/calling_conventions.pdf section 6). We
8105097246SAdrian Prantl   // create a return type by getting the pointer type of the old return type,
8205097246SAdrian Prantl   // and inserting a new initial argument of pointer type of the original
8305097246SAdrian Prantl   // return type.
84a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Language | LLDBLog::Expressions);
8519459580SLuke Drummond 
8619459580SLuke Drummond   assert(call_inst && "no CallInst");
8719459580SLuke Drummond   llvm::Function *orig = call_inst->getCalledFunction();
8819459580SLuke Drummond   assert(orig && "CallInst has no called function");
8919459580SLuke Drummond   llvm::FunctionType *orig_type = orig->getFunctionType();
9019459580SLuke Drummond   auto name = orig->getName();
9163e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%s - cloning to StructRet function for '%s'", __FUNCTION__,
92b9c1b51eSKate Stone             name.str().c_str());
9319459580SLuke Drummond 
9419459580SLuke Drummond   unsigned num_params = orig_type->getNumParams();
959d83de42SLuke Drummond   std::vector<llvm::Type *> new_params{num_params + 1, nullptr};
96b9c1b51eSKate Stone   std::vector<llvm::Type *> params{orig_type->param_begin(),
97b9c1b51eSKate Stone                                    orig_type->param_end()};
9819459580SLuke Drummond 
99b9c1b51eSKate Stone   // This may not work if the function is somehow declared void as llvm is
10005097246SAdrian Prantl   // strongly typed and represents void* with i8*
101b9c1b51eSKate Stone   assert(!orig_type->getReturnType()->isVoidTy() &&
102b9c1b51eSKate Stone          "Cannot add StructRet attribute to void function");
103b9c1b51eSKate Stone   llvm::PointerType *return_type_ptr_type =
104b9c1b51eSKate Stone       llvm::PointerType::getUnqual(orig->getReturnType());
105b9c1b51eSKate Stone   assert(return_type_ptr_type &&
106b9c1b51eSKate Stone          "failed to get function return type PointerType");
10719459580SLuke Drummond   if (!return_type_ptr_type)
10819459580SLuke Drummond     return nullptr;
10919459580SLuke Drummond 
11063e5fb76SJonas Devlieghere   LLDB_LOGF(log,
11163e5fb76SJonas Devlieghere             "%s - return type pointer type for StructRet clone @ '0x%p':\n",
112b9c1b51eSKate Stone             __FUNCTION__, (void *)return_type_ptr_type);
1134ebdee0aSBruce Mitchener   // put the sret pointer argument in place at the beginning of the
11405097246SAdrian Prantl   // argument list.
11519459580SLuke Drummond   params.emplace(params.begin(), return_type_ptr_type);
11619459580SLuke Drummond   assert(params.size() == num_params + 1);
117b9c1b51eSKate Stone   return llvm::FunctionType::get(return_type_ptr_type, params,
118b9c1b51eSKate Stone                                  orig->isVarArg());
11919459580SLuke Drummond }
12019459580SLuke Drummond 
12193c1b3caSPavel Labath static bool
12293c1b3caSPavel Labath findRSCallSites(llvm::Module &module, std::set<llvm::CallInst *> &rs_callsites,
123*00fb0504SNikita Popov                 bool (*predicate)(llvm::CallInst *)) {
12419459580SLuke Drummond   bool found = false;
12519459580SLuke Drummond 
12619459580SLuke Drummond   for (auto &func : module.getFunctionList())
12719459580SLuke Drummond     for (auto &block : func.getBasicBlockList())
128b9c1b51eSKate Stone       for (auto &inst : block) {
129b9c1b51eSKate Stone         llvm::CallInst *call_inst =
130b9c1b51eSKate Stone             llvm::dyn_cast_or_null<llvm::CallInst>(&inst);
13119459580SLuke Drummond         if (!call_inst || !call_inst->getCalledFunction())
13219459580SLuke Drummond           // This is not the call-site you are looking for...
13319459580SLuke Drummond           continue;
134*00fb0504SNikita Popov         if (isRSAPICall(call_inst) && predicate(call_inst)) {
13519459580SLuke Drummond           rs_callsites.insert(call_inst);
13619459580SLuke Drummond           found = true;
13719459580SLuke Drummond         }
13819459580SLuke Drummond       }
13919459580SLuke Drummond   return found;
14019459580SLuke Drummond }
14119459580SLuke Drummond 
14293c1b3caSPavel Labath static bool fixupX86StructRetCalls(llvm::Module &module) {
14319459580SLuke Drummond   bool changed = false;
14405097246SAdrian Prantl   // changing a basic block while iterating over it seems to have some
14505097246SAdrian Prantl   // undefined behaviour going on so we find all RS callsites first, then fix
14605097246SAdrian Prantl   // them up after consuming the iterator.
14719459580SLuke Drummond   std::set<llvm::CallInst *> rs_callsites;
14819459580SLuke Drummond   if (!findRSCallSites(module, rs_callsites, isRSLargeReturnCall))
14919459580SLuke Drummond     return false;
15019459580SLuke Drummond 
151b9c1b51eSKate Stone   for (auto call_inst : rs_callsites) {
15219459580SLuke Drummond     llvm::FunctionType *new_func_type = cloneToStructRetFnTy(call_inst);
153b9c1b51eSKate Stone     assert(new_func_type &&
154b9c1b51eSKate Stone            "failed to clone functionType for Renderscript ABI fixup");
15519459580SLuke Drummond 
15619459580SLuke Drummond     llvm::Function *func = call_inst->getCalledFunction();
15719459580SLuke Drummond     assert(func && "cannot resolve function in RenderScriptRuntime");
15819459580SLuke Drummond     // Copy the original call arguments
1595948dafcSMircea Trofin     std::vector<llvm::Value *> new_call_args(call_inst->arg_begin(),
1605948dafcSMircea Trofin                                              call_inst->arg_end());
16119459580SLuke Drummond 
16219459580SLuke Drummond     // Allocate enough space to store the return value of the original function
163b9c1b51eSKate Stone     // we pass a pointer to this allocation as the StructRet param, and then
16405097246SAdrian Prantl     // copy its value into the lldb return value
16575696ffaSMatt Arsenault     const llvm::DataLayout &DL = module.getDataLayout();
166b9c1b51eSKate Stone     llvm::AllocaInst *return_value_alloc = new llvm::AllocaInst(
16775696ffaSMatt Arsenault       func->getReturnType(), DL.getAllocaAddrSpace(), "var_vector_return_alloc",
16875696ffaSMatt Arsenault       call_inst);
16919459580SLuke Drummond     // use the new allocation as the new first argument
170b9c1b51eSKate Stone     new_call_args.emplace(new_call_args.begin(),
171b9c1b51eSKate Stone                           llvm::cast<llvm::Value>(return_value_alloc));
172b9c1b51eSKate Stone     llvm::PointerType *new_func_ptr_type =
173b9c1b51eSKate Stone         llvm::PointerType::get(new_func_type, 0);
17419459580SLuke Drummond     // Create the type cast from the old function type to the new one
175b9c1b51eSKate Stone     llvm::Constant *new_func_cast = llvm::ConstantExpr::getCast(
176b9c1b51eSKate Stone         llvm::Instruction::BitCast, func, new_func_ptr_type);
17719459580SLuke Drummond     // create an allocation for a new function pointer
178b9c1b51eSKate Stone     llvm::AllocaInst *new_func_ptr =
17975696ffaSMatt Arsenault         new llvm::AllocaInst(new_func_ptr_type, DL.getAllocaAddrSpace(),
18075696ffaSMatt Arsenault                              "new_func_ptr", call_inst);
18119459580SLuke Drummond     // store the new_func_cast to the newly allocated space
182a322f36cSDavid Blaikie     (new llvm::StoreInst(new_func_cast, new_func_ptr, call_inst))
183a322f36cSDavid Blaikie         ->setName("new_func_ptr_load_cast");
18419459580SLuke Drummond     // load the new function address ready for a jump
185ad1feef7SNikita Popov     llvm::LoadInst *new_func_addr_load = new llvm::LoadInst(
186ad1feef7SNikita Popov         new_func_ptr_type, new_func_ptr, "load_func_pointer", call_inst);
18719459580SLuke Drummond     // and create a callinstruction from it
188ae2f9512SJames Y Knight     llvm::CallInst *new_call_inst =
189ae2f9512SJames Y Knight         llvm::CallInst::Create(new_func_type, new_func_addr_load, new_call_args,
190ae2f9512SJames Y Knight                                "new_func_call", call_inst);
19119459580SLuke Drummond     new_call_inst->setCallingConv(call_inst->getCallingConv());
19219459580SLuke Drummond     new_call_inst->setTailCall(call_inst->isTailCall());
193ad1feef7SNikita Popov     llvm::LoadInst *lldb_save_result_address =
194ad1feef7SNikita Popov         new llvm::LoadInst(func->getReturnType(), return_value_alloc,
195ad1feef7SNikita Popov                            "save_return_val", call_inst);
19619459580SLuke Drummond 
19719459580SLuke Drummond     // Now remove the old broken call
19819459580SLuke Drummond     call_inst->replaceAllUsesWith(lldb_save_result_address);
19919459580SLuke Drummond     call_inst->eraseFromParent();
20019459580SLuke Drummond     changed = true;
20119459580SLuke Drummond   }
20219459580SLuke Drummond   return changed;
20319459580SLuke Drummond }
20419459580SLuke Drummond 
20593c1b3caSPavel Labath static bool fixupRSAllocationStructByValCalls(llvm::Module &module) {
206b9c1b51eSKate Stone   // On x86_64, calls to functions in the RS runtime that take an
20705097246SAdrian Prantl   // `rs_allocation` type argument are actually handled as by-ref params by
20805097246SAdrian Prantl   // bcc, but appear to be passed by value by lldb (the callsite all use
20905097246SAdrian Prantl   // `struct byval`). On x86_64 Linux, struct arguments are transferred in
21005097246SAdrian Prantl   // registers if the struct size is no bigger than 128bits
21105097246SAdrian Prantl   // [ref](http://www.agner.org/optimize/calling_conventions.pdf) section 7.1
21205097246SAdrian Prantl   // "Passing and returning objects" otherwise passed on the stack. an object
21305097246SAdrian Prantl   // of type `rs_allocation` is actually 256bits, so should be passed on the
21405097246SAdrian Prantl   // stack. However, code generated by bcc actually treats formal params of
21505097246SAdrian Prantl   // type `rs_allocation` as `rs_allocation *` so we need to convert the
216b9c1b51eSKate Stone   // calling convention to pass by reference, and remove any hint of byval from
217b9c1b51eSKate Stone   // formal parameters.
21819459580SLuke Drummond   bool changed = false;
21919459580SLuke Drummond   std::set<llvm::CallInst *> rs_callsites;
22019459580SLuke Drummond   if (!findRSCallSites(module, rs_callsites, isRSAllocationTyCallSite))
22119459580SLuke Drummond     return false;
22219459580SLuke Drummond 
22319459580SLuke Drummond   std::set<llvm::Function *> rs_functions;
22419459580SLuke Drummond 
22519459580SLuke Drummond   // for all call instructions
226b9c1b51eSKate Stone   for (auto call_inst : rs_callsites) {
227b9c1b51eSKate Stone     // add the called function to a set so that we can strip its byval
228b9c1b51eSKate Stone     // attributes in another pass
22919459580SLuke Drummond     rs_functions.insert(call_inst->getCalledFunction());
23019459580SLuke Drummond 
23119459580SLuke Drummond     // get the function attributes
232a3e3715cSReid Kleckner     llvm::AttributeList call_attribs = call_inst->getAttributes();
23319459580SLuke Drummond 
23419459580SLuke Drummond     // iterate over the argument attributes
235a7b4ce9cSArthur Eubanks     for (unsigned I : call_attribs.indexes()) {
23619459580SLuke Drummond       // if this argument is passed by val
237ebbf7f90SArthur Eubanks       if (call_attribs.hasAttributeAtIndex(I, llvm::Attribute::ByVal)) {
23819459580SLuke Drummond         // strip away the byval attribute
239ebbf7f90SArthur Eubanks         call_inst->removeAttributeAtIndex(I, llvm::Attribute::ByVal);
24019459580SLuke Drummond         changed = true;
24119459580SLuke Drummond       }
24219459580SLuke Drummond     }
24319459580SLuke Drummond   }
24419459580SLuke Drummond 
24519459580SLuke Drummond   // for all called function decls
246b9c1b51eSKate Stone   for (auto func : rs_functions) {
24719459580SLuke Drummond     // inspect all of the arguments in the call
24820670ba5SReid Kleckner     for (auto &arg : func->args()) {
249b9c1b51eSKate Stone       if (arg.hasByValAttr()) {
250f76a8ac5SReid Kleckner         arg.removeAttr(llvm::Attribute::ByVal);
25119459580SLuke Drummond         changed = true;
25219459580SLuke Drummond       }
25319459580SLuke Drummond     }
25419459580SLuke Drummond   }
25519459580SLuke Drummond   return changed;
25619459580SLuke Drummond }
25719459580SLuke Drummond 
258b9c1b51eSKate Stone namespace lldb_private {
259b9c1b51eSKate Stone namespace lldb_renderscript {
26019459580SLuke Drummond 
261b9c1b51eSKate Stone bool fixupX86FunctionCalls(llvm::Module &module) {
26219459580SLuke Drummond   return fixupX86StructRetCalls(module);
26319459580SLuke Drummond }
26419459580SLuke Drummond 
265b9c1b51eSKate Stone bool fixupX86_64FunctionCalls(llvm::Module &module) {
26619459580SLuke Drummond   bool changed = false;
26719459580SLuke Drummond   changed |= fixupX86StructRetCalls(module);
26819459580SLuke Drummond   changed |= fixupRSAllocationStructByValCalls(module);
26919459580SLuke Drummond   return changed;
27019459580SLuke Drummond }
27119459580SLuke Drummond 
27219459580SLuke Drummond } // end namespace lldb_renderscript
27319459580SLuke Drummond } // end namespace lldb_private
274