LLVM  12.0.0git
TargetMachineC.cpp
Go to the documentation of this file.
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"
17 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/Module.h"
23 #include "llvm/Support/Host.h"
28 #include <cassert>
29 #include <cstdlib>
30 #include <cstring>
31 
32 using namespace llvm;
33 
35  return reinterpret_cast<TargetMachine *>(P);
36 }
38  return reinterpret_cast<Target*>(P);
39 }
41  return reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine *>(P));
42 }
43 static LLVMTargetRef wrap(const Target * P) {
44  return reinterpret_cast<LLVMTargetRef>(const_cast<Target*>(P));
45 }
46 
49  return nullptr;
50  }
51 
52  const Target *target = &*TargetRegistry::targets().begin();
53  return wrap(target);
54 }
56  return wrap(unwrap(T)->getNext());
57 }
58 
60  StringRef NameRef = Name;
62  [&](const Target &T) { return T.getName() == NameRef; });
63  return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
64 }
65 
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 
83  return unwrap(T)->getName();
84 }
85 
87  return unwrap(T)->getShortDescription();
88 }
89 
91  return unwrap(T)->hasJIT();
92 }
93 
95  return unwrap(T)->hasTargetMachine();
96 }
97 
99  return unwrap(T)->hasMCAsmBackend();
100 }
101 
103  const char *Triple, const char *CPU, const char *Features,
105  LLVMCodeModel CodeModel) {
107  switch (Reloc){
108  case LLVMRelocStatic:
109  RM = Reloc::Static;
110  break;
111  case LLVMRelocPIC:
112  RM = Reloc::PIC_;
113  break;
116  break;
117  case LLVMRelocROPI:
118  RM = Reloc::ROPI;
119  break;
120  case LLVMRelocRWPI:
121  RM = Reloc::RWPI;
122  break;
123  case LLVMRelocROPI_RWPI:
125  break;
126  default:
127  break;
128  }
129 
130  bool JIT;
131  Optional<CodeModel::Model> CM = unwrap(CodeModel, JIT);
132 
134  switch (Level) {
136  OL = CodeGenOpt::None;
137  break;
139  OL = CodeGenOpt::Less;
140  break;
143  break;
144  default:
145  OL = CodeGenOpt::Default;
146  break;
147  }
148 
150  return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt, RM, CM,
151  OL, JIT));
152 }
153 
155 
157  const Target* target = &(unwrap(T)->getTarget());
158  return wrap(target);
159 }
160 
162  std::string StringRep = unwrap(T)->getTargetTriple().str();
163  return strdup(StringRep.c_str());
164 }
165 
167  std::string StringRep = std::string(unwrap(T)->getTargetCPU());
168  return strdup(StringRep.c_str());
169 }
170 
172  std::string StringRep = std::string(unwrap(T)->getTargetFeatureString());
173  return strdup(StringRep.c_str());
174 }
175 
177  LLVMBool VerboseAsm) {
178  unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
179 }
180 
182  return wrap(new DataLayout(unwrap(T)->createDataLayout()));
183 }
184 
186  raw_pwrite_stream &OS,
188  char **ErrorMessage) {
189  TargetMachine* TM = unwrap(T);
190  Module* Mod = unwrap(M);
191 
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 
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 
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 =
242  return Result;
243 }
244 
246  return strdup(sys::getDefaultTargetTriple().c_str());
247 }
248 
249 char *LLVMNormalizeTargetTriple(const char* triple) {
250  return strdup(Triple::normalize(StringRef(triple)).c_str());
251 }
252 
253 char *LLVMGetHostCPUName(void) {
254  return strdup(sys::getHostCPUName().data());
255 }
256 
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 
269  unwrap(PM)->add(
270  createTargetTransformInfoWrapperPass(unwrap(T)->getTargetIRAnalysis()));
271 }
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:111
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:233
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:224
This class represents lattice values for constants.
Definition: AllocatorList.h:23
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:61
LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(const char *InputData, size_t InputDataLength, const char *BufferName)
Definition: Core.cpp:4096
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition: Types.h:48
char * LLVMGetDefaultTargetTriple(void)
Get a triple for the host machine as a string.
LLVMCodeGenOptLevel
Definition: TargetMachine.h:31
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
std::string getString() const
Returns features as a string.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:636
#define error(X)
F(f)
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T)
Create a DataLayout based on the targetMachine.
char * LLVMGetHostCPUName(void)
Get the host CPU as a string.
LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T)
Returns the Target used in a TargetMachine.
LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T)
Returns if the target as an ASM backend (required for emitting output)
LLVMCodeGenFileType
Definition: TargetMachine.h:58
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition: DataLayout.h:39
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:229
void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T, LLVMBool VerboseAsm)
Set the target machine's ASM verbosity.
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
const char * LLVMGetTargetName(LLVMTargetRef T)
Returns the name of a target.
static std::unique_ptr< TargetMachine > createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M)
Definition: LTOBackend.cpp:180
char * LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T)
Returns the feature string used creating this target machine.
static iterator_range< iterator > targets()
LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M, LLVMCodeGenFileType codegen, char **ErrorMessage, LLVMMemoryBufferRef *OutMemBuf)
Compile the LLVM IR stored in M and store the result in OutMemBuf.
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
Definition: JSON.h:886
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, CodeGenFileType FileType)
Definition: ParallelCG.cpp:27
PassManager manages ModulePassManagers.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:63
#define P(N)
llvm::StringLiteral ErrorMessage
Definition: JSON.h:565
LLVMBool LLVMGetTargetFromTriple(const char *TripleStr, LLVMTargetRef *T, char **ErrorMessage)
Finds the target corresponding to the given triple and stores it in T.
void LLVMDisposeTargetMachine(LLVMTargetMachineRef T)
Dispose the LLVMTargetMachineRef instance generated by LLVMCreateTargetMachine.
struct LLVMTarget * LLVMTargetRef
Definition: TargetMachine.h:29
LLVMCodeModel
Definition: TargetMachine.h:48
LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M, char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage)
Emits an asm or object file for the given module to the filename.
static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M, raw_pwrite_stream &OS, LLVMCodeGenFileType codegen, char **ErrorMessage)
const char * LLVMGetTargetDescription(LLVMTargetRef T)
Returns the description of a target.
typedefLLVM_C_EXTERN_C_BEGIN struct LLVMOpaqueTargetMachine * LLVMTargetMachineRef
Definition: TargetMachine.h:28
LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T)
Returns if the target has a TargetMachine associated.
int LLVMBool
Definition: Types.h:28
LLVMTargetRef LLVMGetFirstTarget()
Returns the first llvm::Target in the registered targets list.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
char * LLVMGetTargetMachineTriple(LLVMTargetMachineRef T)
Returns the triple used creating this target machine.
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T)
Returns the next llvm::Target given a previous one (or null if there's none)
Module.h This file contains the declarations for the Module class.
modulo schedule Modulo Schedule test pass
arm prera ldst opt
std::string normalize() const
Return the normalized form of this triple's string.
Definition: Triple.h:297
The access may modify the value stored in memory.
struct LLVMOpaquePassManager * LLVMPassManagerRef
Definition: Types.h:127
char * LLVMGetTargetMachineCPU(LLVMTargetMachineRef T)
Returns the cpu used creating this target machine.
Target - Wrapper for Target specific information.
Manages the enabling and disabling of subtarget specific features.
LLVMRelocMode
Definition: TargetMachine.h:38
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:224
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:425
StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition: Host.cpp:1240
LLVMBool LLVMTargetHasJIT(LLVMTargetRef T)
Returns if the target has a JIT.
#define I(x, y, z)
Definition: MD5.cpp:59
char * LLVMNormalizeTargetTriple(const char *triple)
Normalize a target triple.
LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, const char *Triple, const char *CPU, const char *Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel)
Creates a new llvm::TargetMachine.
char * LLVMGetHostCPUFeatures(void)
Get the host CPU's features as a string.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:399
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
This pass exposes codegen information to IR-level passes.
void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM)
Adds the target-specific analysis passes to the pass manager.
LLVMTargetRef LLVMGetTargetFromName(const char *Name)
Finds the target corresponding to the given name and stores it in T.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1525
Level
Definition: Debugify.cpp:34
bool getHostCPUFeatures(StringMap< bool, MallocAllocator > &Features)
getHostCPUFeatures - Get the LLVM names for the host CPU features.