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