[Orc] Make the makeStub function propagate argument attributes onto the call to
[oota-llvm.git] / lib / ExecutionEngine / Orc / IndirectionUtils.cpp
1 //===---- IndirectionUtils.cpp - Utilities for call indirection in Orc ----===//
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 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/Triple.h"
12 #include "llvm/ExecutionEngine/Orc/CloneSubModule.h"
13 #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
14 #include "llvm/IR/CallSite.h"
15 #include "llvm/IR/IRBuilder.h"
16 #include <set>
17 #include <sstream>
18
19 namespace llvm {
20 namespace orc {
21
22 Constant* createIRTypedAddress(FunctionType &FT, TargetAddress Addr) {
23   Constant *AddrIntVal =
24     ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr);
25   Constant *AddrPtrVal =
26     ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
27                           PointerType::get(&FT, 0));
28   return AddrPtrVal;
29 }
30
31 GlobalVariable* createImplPointer(PointerType &PT, Module &M,
32                                   const Twine &Name, Constant *Initializer) {
33   if (!Initializer)
34     Initializer = Constant::getNullValue(&PT);
35   return new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
36                             Initializer, Name, nullptr,
37                             GlobalValue::NotThreadLocal, 0, true);
38 }
39
40 void makeStub(Function &F, GlobalVariable &ImplPointer) {
41   assert(F.isDeclaration() && "Can't turn a definition into a stub.");
42   assert(F.getParent() && "Function isn't in a module.");
43   Module &M = *F.getParent();
44   BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
45   IRBuilder<> Builder(EntryBlock);
46   LoadInst *ImplAddr = Builder.CreateLoad(&ImplPointer);
47   std::vector<Value*> CallArgs;
48   for (auto &A : F.args())
49     CallArgs.push_back(&A);
50   CallInst *Call = Builder.CreateCall(ImplAddr, CallArgs);
51   Call->setTailCall();
52   Call->setAttributes(F.getAttributes());
53   Builder.CreateRet(Call);
54 }
55
56 // Utility class for renaming global values and functions during partitioning.
57 class GlobalRenamer {
58 public:
59
60   static bool needsRenaming(const Value &New) {
61     if (!New.hasName() || New.getName().startswith("\01L"))
62       return true;
63     return false;
64   }
65
66   const std::string& getRename(const Value &Orig) {
67     // See if we have a name for this global.
68     {
69       auto I = Names.find(&Orig);
70       if (I != Names.end())
71         return I->second;
72     }
73
74     // Nope. Create a new one.
75     // FIXME: Use a more robust uniquing scheme. (This may blow up if the user
76     //        writes a "__orc_anon[[:digit:]]* method).
77     unsigned ID = Names.size();
78     std::ostringstream NameStream;
79     NameStream << "__orc_anon" << ID++;
80     auto I = Names.insert(std::make_pair(&Orig, NameStream.str()));
81     return I.first->second;
82   }
83 private:
84   DenseMap<const Value*, std::string> Names;
85 };
86
87 void partition(Module &M, const ModulePartitionMap &PMap) {
88
89   GlobalRenamer Renamer;
90
91   for (auto &KVPair : PMap) {
92
93     auto ExtractGlobalVars =
94       [&](GlobalVariable &New, const GlobalVariable &Orig,
95           ValueToValueMapTy &VMap) {
96         if (KVPair.second.count(&Orig)) {
97           copyGVInitializer(New, Orig, VMap);
98         }
99         if (New.hasLocalLinkage()) {
100           if (Renamer.needsRenaming(New))
101             New.setName(Renamer.getRename(Orig));
102           New.setLinkage(GlobalValue::ExternalLinkage);
103           New.setVisibility(GlobalValue::HiddenVisibility);
104         }
105         assert(!Renamer.needsRenaming(New) && "Invalid global name.");
106       };
107
108     auto ExtractFunctions =
109       [&](Function &New, const Function &Orig, ValueToValueMapTy &VMap) {
110         if (KVPair.second.count(&Orig))
111           copyFunctionBody(New, Orig, VMap);
112         if (New.hasLocalLinkage()) {
113           if (Renamer.needsRenaming(New))
114             New.setName(Renamer.getRename(Orig));
115           New.setLinkage(GlobalValue::ExternalLinkage);
116           New.setVisibility(GlobalValue::HiddenVisibility);
117         }
118         assert(!Renamer.needsRenaming(New) && "Invalid function name.");
119       };
120
121     CloneSubModule(*KVPair.first, M, ExtractGlobalVars, ExtractFunctions,
122                    false);
123   }
124 }
125
126 FullyPartitionedModule fullyPartition(Module &M) {
127   FullyPartitionedModule MP;
128
129   ModulePartitionMap PMap;
130
131   for (auto &F : M) {
132
133     if (F.isDeclaration())
134       continue;
135
136     std::string NewModuleName = (M.getName() + "." + F.getName()).str();
137     MP.Functions.push_back(
138       llvm::make_unique<Module>(NewModuleName, M.getContext()));
139     MP.Functions.back()->setDataLayout(M.getDataLayout());
140     PMap[MP.Functions.back().get()].insert(&F);
141   }
142
143   MP.GlobalVars =
144     llvm::make_unique<Module>((M.getName() + ".globals_and_stubs").str(),
145                               M.getContext());
146   MP.GlobalVars->setDataLayout(M.getDataLayout());
147
148   MP.Commons =
149     llvm::make_unique<Module>((M.getName() + ".commons").str(), M.getContext());
150   MP.Commons->setDataLayout(M.getDataLayout());
151
152   // Make sure there's at least an empty set for the stubs map or we'll fail
153   // to clone anything for it (including the decls).
154   PMap[MP.GlobalVars.get()] = ModulePartitionMap::mapped_type();
155   for (auto &GV : M.globals())
156     if (GV.getLinkage() == GlobalValue::CommonLinkage)
157       PMap[MP.Commons.get()].insert(&GV);
158     else
159       PMap[MP.GlobalVars.get()].insert(&GV);
160
161   partition(M, PMap);
162
163   return MP;
164 }
165
166 } // End namespace orc.
167 } // End namespace llvm.