1 //===-- TargetMachine.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the LLVM-C part of TargetMachine.h
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm-c/Core.h"
14 #include "llvm-c/TargetMachine.h"
15 #include "llvm/Analysis/TargetTransformInfo.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/LegacyPassManager.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/MC/TargetRegistry.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/CodeGenCWrappers.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/TargetParser/Host.h"
25 #include "llvm/TargetParser/SubtargetFeature.h"
26 #include <cstring>
27 #include <optional>
28 
29 using namespace llvm;
30 
31 static TargetMachine *unwrap(LLVMTargetMachineRef P) {
32   return reinterpret_cast<TargetMachine *>(P);
33 }
34 static Target *unwrap(LLVMTargetRef P) {
35   return reinterpret_cast<Target*>(P);
36 }
37 static LLVMTargetMachineRef wrap(const TargetMachine *P) {
38   return reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine *>(P));
39 }
40 static LLVMTargetRef wrap(const Target * P) {
41   return reinterpret_cast<LLVMTargetRef>(const_cast<Target*>(P));
42 }
43 
44 LLVMTargetRef LLVMGetFirstTarget() {
45   if (TargetRegistry::targets().begin() == TargetRegistry::targets().end()) {
46     return nullptr;
47   }
48 
49   const Target *target = &*TargetRegistry::targets().begin();
50   return wrap(target);
51 }
52 LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T) {
53   return wrap(unwrap(T)->getNext());
54 }
55 
56 LLVMTargetRef LLVMGetTargetFromName(const char *Name) {
57   StringRef NameRef = Name;
58   auto I = find_if(TargetRegistry::targets(),
59                    [&](const Target &T) { return T.getName() == NameRef; });
60   return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
61 }
62 
63 LLVMBool LLVMGetTargetFromTriple(const char* TripleStr, LLVMTargetRef *T,
64                                  char **ErrorMessage) {
65   std::string Error;
66 
67   *T = wrap(TargetRegistry::lookupTarget(TripleStr, Error));
68 
69   if (!*T) {
70     if (ErrorMessage)
71       *ErrorMessage = strdup(Error.c_str());
72 
73     return 1;
74   }
75 
76   return 0;
77 }
78 
79 const char * LLVMGetTargetName(LLVMTargetRef T) {
80   return unwrap(T)->getName();
81 }
82 
83 const char * LLVMGetTargetDescription(LLVMTargetRef T) {
84   return unwrap(T)->getShortDescription();
85 }
86 
87 LLVMBool LLVMTargetHasJIT(LLVMTargetRef T) {
88   return unwrap(T)->hasJIT();
89 }
90 
91 LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T) {
92   return unwrap(T)->hasTargetMachine();
93 }
94 
95 LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T) {
96   return unwrap(T)->hasMCAsmBackend();
97 }
98 
99 LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T,
100         const char *Triple, const char *CPU, const char *Features,
101         LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc,
102         LLVMCodeModel CodeModel) {
103   std::optional<Reloc::Model> RM;
104   switch (Reloc){
105     case LLVMRelocStatic:
106       RM = Reloc::Static;
107       break;
108     case LLVMRelocPIC:
109       RM = Reloc::PIC_;
110       break;
111     case LLVMRelocDynamicNoPic:
112       RM = Reloc::DynamicNoPIC;
113       break;
114     case LLVMRelocROPI:
115       RM = Reloc::ROPI;
116       break;
117     case LLVMRelocRWPI:
118       RM = Reloc::RWPI;
119       break;
120     case LLVMRelocROPI_RWPI:
121       RM = Reloc::ROPI_RWPI;
122       break;
123     default:
124       break;
125   }
126 
127   bool JIT;
128   std::optional<CodeModel::Model> CM = unwrap(CodeModel, JIT);
129 
130   CodeGenOpt::Level OL;
131   switch (Level) {
132     case LLVMCodeGenLevelNone:
133       OL = CodeGenOpt::None;
134       break;
135     case LLVMCodeGenLevelLess:
136       OL = CodeGenOpt::Less;
137       break;
138     case LLVMCodeGenLevelAggressive:
139       OL = CodeGenOpt::Aggressive;
140       break;
141     default:
142       OL = CodeGenOpt::Default;
143       break;
144   }
145 
146   TargetOptions opt;
147   return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt, RM, CM,
148                                              OL, JIT));
149 }
150 
151 void LLVMDisposeTargetMachine(LLVMTargetMachineRef T) { delete unwrap(T); }
152 
153 LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T) {
154   const Target* target = &(unwrap(T)->getTarget());
155   return wrap(target);
156 }
157 
158 char* LLVMGetTargetMachineTriple(LLVMTargetMachineRef T) {
159   std::string StringRep = unwrap(T)->getTargetTriple().str();
160   return strdup(StringRep.c_str());
161 }
162 
163 char* LLVMGetTargetMachineCPU(LLVMTargetMachineRef T) {
164   std::string StringRep = std::string(unwrap(T)->getTargetCPU());
165   return strdup(StringRep.c_str());
166 }
167 
168 char* LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T) {
169   std::string StringRep = std::string(unwrap(T)->getTargetFeatureString());
170   return strdup(StringRep.c_str());
171 }
172 
173 void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T,
174                                       LLVMBool VerboseAsm) {
175   unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
176 }
177 
178 LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T) {
179   return wrap(new DataLayout(unwrap(T)->createDataLayout()));
180 }
181 
182 static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M,
183                                       raw_pwrite_stream &OS,
184                                       LLVMCodeGenFileType codegen,
185                                       char **ErrorMessage) {
186   TargetMachine* TM = unwrap(T);
187   Module* Mod = unwrap(M);
188 
189   legacy::PassManager pass;
190 
191   std::string error;
192 
193   Mod->setDataLayout(TM->createDataLayout());
194 
195   CodeGenFileType ft;
196   switch (codegen) {
197     case LLVMAssemblyFile:
198       ft = CGFT_AssemblyFile;
199       break;
200     default:
201       ft = CGFT_ObjectFile;
202       break;
203   }
204   if (TM->addPassesToEmitFile(pass, OS, nullptr, ft)) {
205     error = "TargetMachine can't emit a file of this type";
206     *ErrorMessage = strdup(error.c_str());
207     return true;
208   }
209 
210   pass.run(*Mod);
211 
212   OS.flush();
213   return false;
214 }
215 
216 LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
217                                      const char *Filename,
218                                      LLVMCodeGenFileType codegen,
219                                      char **ErrorMessage) {
220   std::error_code EC;
221   raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);
222   if (EC) {
223     *ErrorMessage = strdup(EC.message().c_str());
224     return true;
225   }
226   bool Result = LLVMTargetMachineEmit(T, M, dest, codegen, ErrorMessage);
227   dest.flush();
228   return Result;
229 }
230 
231 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T,
232   LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
233   LLVMMemoryBufferRef *OutMemBuf) {
234   SmallString<0> CodeString;
235   raw_svector_ostream OStream(CodeString);
236   bool Result = LLVMTargetMachineEmit(T, M, OStream, codegen, ErrorMessage);
237 
238   StringRef Data = OStream.str();
239   *OutMemBuf =
240       LLVMCreateMemoryBufferWithMemoryRangeCopy(Data.data(), Data.size(), "");
241   return Result;
242 }
243 
244 char *LLVMGetDefaultTargetTriple(void) {
245   return strdup(sys::getDefaultTargetTriple().c_str());
246 }
247 
248 char *LLVMNormalizeTargetTriple(const char* triple) {
249   return strdup(Triple::normalize(StringRef(triple)).c_str());
250 }
251 
252 char *LLVMGetHostCPUName(void) {
253   return strdup(sys::getHostCPUName().data());
254 }
255 
256 char *LLVMGetHostCPUFeatures(void) {
257   SubtargetFeatures Features;
258   StringMap<bool> HostFeatures;
259 
260   if (sys::getHostCPUFeatures(HostFeatures))
261     for (const auto &[Feature, IsEnabled] : HostFeatures)
262       Features.AddFeature(Feature, IsEnabled);
263 
264   return strdup(Features.getString().c_str());
265 }
266 
267 void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM) {
268   unwrap(PM)->add(
269       createTargetTransformInfoWrapperPass(unwrap(T)->getTargetIRAnalysis()));
270 }
271