LLVM 24.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"
16#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/Module.h"
27#include <optional>
28
29using namespace llvm;
30
31namespace llvm {
32
33/// Options for LLVMCreateTargetMachine().
35 std::string CPU;
36 std::string Features;
37 std::string ABI;
39 std::optional<Reloc::Model> RM;
40 std::optional<CodeModel::Model> CM;
41 bool JIT;
42};
43
44} // namespace llvm
45
53 return reinterpret_cast<Target*>(P);
54}
56 return reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine *>(P));
57}
58static LLVMTargetRef wrap(const Target * P) {
59 return reinterpret_cast<LLVMTargetRef>(const_cast<Target*>(P));
60}
61
63 if (TargetRegistry::targets().begin() == TargetRegistry::targets().end()) {
64 return nullptr;
65 }
66
67 const Target *target = &*TargetRegistry::targets().begin();
68 return wrap(target);
69}
73
75 StringRef NameRef = Name;
77 [&](const Target &T) { return T.getName() == NameRef; });
78 return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
79}
80
82 char **ErrorMessage) {
83 std::string Error;
84
85 Triple TT(TripleStr);
87
88 if (!*T) {
89 if (ErrorMessage)
90 *ErrorMessage = strdup(Error.c_str());
91
92 return 1;
93 }
94
95 return 0;
96}
97
99 return unwrap(T)->getName();
100}
101
103 return unwrap(T)->getShortDescription();
104}
105
107 return unwrap(T)->hasJIT();
108}
109
111 return unwrap(T)->hasTargetMachine();
112}
113
115 return unwrap(T)->hasMCAsmBackend();
116}
117
121
125
127 const char *CPU) {
128 unwrap(Options)->CPU = CPU;
129}
130
132 const char *Features) {
133 unwrap(Options)->Features = Features;
134}
135
137 const char *ABI) {
138 unwrap(Options)->ABI = ABI;
139}
140
144
145 switch (Level) {
148 break;
151 break;
154 break;
157 break;
158 }
159
160 unwrap(Options)->OL = OL;
161}
162
165 std::optional<Reloc::Model> RM;
166
167 switch (Reloc) {
168 case LLVMRelocStatic:
169 RM = Reloc::Static;
170 break;
171 case LLVMRelocPIC:
172 RM = Reloc::PIC_;
173 break;
176 break;
177 case LLVMRelocROPI:
178 RM = Reloc::ROPI;
179 break;
180 case LLVMRelocRWPI:
181 RM = Reloc::RWPI;
182 break;
184 RM = Reloc::ROPI_RWPI;
185 break;
186 case LLVMRelocDefault:
187 break;
188 }
189
190 unwrap(Options)->RM = RM;
191}
192
198
202 auto *Opt = unwrap(Options);
203 TargetOptions TO;
204 TO.MCOptions.ABIName = Opt->ABI;
205 return wrap(unwrap(T)->createTargetMachine(Triple(TripleStr), Opt->CPU,
206 Opt->Features, TO, Opt->RM,
207 Opt->CM, Opt->OL, Opt->JIT));
208}
209
227
229
231 const Target* target = &(unwrap(T)->getTarget());
232 return wrap(target);
233}
234
236 std::string StringRep = unwrap(T)->getTargetTriple().str();
237 return strdup(StringRep.c_str());
238}
239
241 std::string StringRep = std::string(unwrap(T)->getTargetCPU());
242 return strdup(StringRep.c_str());
243}
244
246 std::string StringRep = std::string(unwrap(T)->getTargetFeatureString());
247 return strdup(StringRep.c_str());
248}
249
251 LLVMBool VerboseAsm) {
252 unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
253}
254
258
262
280
285
289
293 char **ErrorMessage) {
294 TargetMachine* TM = unwrap(T);
295 Module* Mod = unwrap(M);
296
298
299 std::string error;
300
301 Mod->setDataLayout(TM->createDataLayout());
302
304 switch (codegen) {
305 case LLVMAssemblyFile:
307 break;
308 default:
310 break;
311 }
312 if (TM->addPassesToEmitFile(pass, OS, nullptr, ft)) {
313 error = "TargetMachine can't emit a file of this type";
314 *ErrorMessage = strdup(error.c_str());
315 return true;
316 }
317
318 pass.run(*Mod);
319
320 OS.flush();
321 return false;
322}
323
325 const char *Filename,
327 char **ErrorMessage) {
328 std::error_code EC;
330 if (EC) {
331 *ErrorMessage = strdup(EC.message().c_str());
332 return true;
333 }
334 bool Result = LLVMTargetMachineEmit(T, M, dest, codegen, ErrorMessage);
335 dest.flush();
336 return Result;
337}
338
340 LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
341 LLVMMemoryBufferRef *OutMemBuf) {
342 SmallString<0> CodeString;
343 raw_svector_ostream OStream(CodeString);
344 bool Result = LLVMTargetMachineEmit(T, M, OStream, codegen, ErrorMessage);
345
346 StringRef Data = OStream.str();
347 *OutMemBuf =
349 return Result;
350}
351
353 return strdup(sys::getDefaultTargetTriple().c_str());
354}
355
356char *LLVMNormalizeTargetTriple(const char* triple) {
357 return strdup(Triple::normalize(StringRef(triple)).c_str());
358}
359
361 return strdup(sys::getHostCPUName().data());
362}
363
365 SubtargetFeatures Features;
366 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
367 Features.AddFeature(Feature, IsEnabled);
368
369 return strdup(Features.getString().c_str());
370}
371
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
@ Enable
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
#define I(x, y, z)
Definition MD5.cpp:57
#define T
modulo schedule Modulo Schedule test pass
static std::unique_ptr< TargetMachine > createTargetMachine(Function *F, CodeGenOptLevel OptLevel)
Create the TargetMachine object to query the backend for optimization preferences.
static constexpr StringLiteral Filename
#define P(N)
Function const char TargetMachine * Machine
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static Split data
#define error(X)
static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M, raw_pwrite_stream &OS, LLVMCodeGenFileType codegen, char **ErrorMessage)
This pass exposes codegen information to IR-level passes.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Manages the enabling and disabling of subtarget specific features.
LLVM_ABI std::string getString() const
Returns features as a string.
LLVM_ABI void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Primary interface to the complete machine description for the target machine.
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfoWrapperPass *MMIWP=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
const DataLayout createDataLayout() const
Create a DataLayout.
MCTargetOptions MCOptions
Machine level options.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
static LLVM_ABI std::string normalize(StringRef Str, CanonicalForm Form=CanonicalForm::ANY)
Turn an arbitrary machine specification into the canonical triple form (or something sensible that th...
Definition Triple.cpp:1185
IteratorT end() const
IteratorT begin() const
PassManager manages ModulePassManagers.
A raw_ostream that writes to a file descriptor.
An abstract base class for streams implementations that also support a pwrite operation.
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
LLVM_C_ABI LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(const char *InputData, size_t InputDataLength, const char *BufferName)
Definition Core.cpp:4701
int LLVMBool
Definition Types.h:28
struct LLVMOpaquePassManager * LLVMPassManagerRef
Definition Types.h:127
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition Types.h:48
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition Types.h:61
LLVMCodeGenFileType
void LLVMTargetMachineOptionsSetCodeGenOptLevel(LLVMTargetMachineOptionsRef Options, LLVMCodeGenOptLevel Level)
void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM)
Adds the target-specific analysis passes to the pass manager.
char * LLVMGetTargetMachineCPU(LLVMTargetMachineRef T)
Returns the cpu used creating this target machine.
LLVMTargetRef LLVMGetFirstTarget()
Returns the first llvm::Target in the registered targets list.
void LLVMSetTargetMachineGlobalISelAbort(LLVMTargetMachineRef T, LLVMGlobalISelAbortMode Mode)
Set abort behaviour when global instruction selection fails to lower/select an instruction.
struct LLVMTarget * LLVMTargetRef
void LLVMTargetMachineOptionsSetABI(LLVMTargetMachineOptionsRef Options, const char *ABI)
struct LLVMOpaqueTargetMachine * LLVMTargetMachineRef
LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T)
Returns the Target used in a TargetMachine.
LLVMTargetMachineRef LLVMCreateTargetMachineWithOptions(LLVMTargetRef T, const char *TripleStr, LLVMTargetMachineOptionsRef Options)
Create a new llvm::TargetMachine.
LLVMCodeModel
LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M, const char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage)
Emits an asm or object file for the given module to the filename.
void LLVMSetTargetMachineMachineOutliner(LLVMTargetMachineRef T, LLVMBool Enable)
Enable the MachineOutliner pass.
struct LLVMOpaqueTargetMachineOptions * LLVMTargetMachineOptionsRef
LLVMTargetRef LLVMGetTargetFromName(const char *Name)
Finds the target corresponding to the given name and stores it in T.
void LLVMTargetMachineOptionsSetFeatures(LLVMTargetMachineOptionsRef Options, const char *Features)
Set the list of features for the target machine.
LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T)
Returns if the target as an ASM backend (required for emitting output)
char * LLVMGetDefaultTargetTriple(void)
Get a triple for the host machine as a string.
LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, const char *Triple, const char *CPU, const char *Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel)
Creates a new llvm::TargetMachine.
void LLVMTargetMachineOptionsSetRelocMode(LLVMTargetMachineOptionsRef Options, LLVMRelocMode Reloc)
LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T)
Returns the next llvm::Target given a previous one (or null if there's none)
char * LLVMGetHostCPUFeatures(void)
Get the host CPU's features as a string.
void LLVMDisposeTargetMachineOptions(LLVMTargetMachineOptionsRef Options)
Dispose of an LLVMTargetMachineOptionsRef instance.
LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T)
Returns if the target has a TargetMachine associated.
void LLVMSetTargetMachineFastISel(LLVMTargetMachineRef T, LLVMBool Enable)
Enable fast-path instruction selection.
char * LLVMNormalizeTargetTriple(const char *triple)
Normalize a target triple.
LLVMBool LLVMGetTargetFromTriple(const char *TripleStr, LLVMTargetRef *T, char **ErrorMessage)
Finds the target corresponding to the given triple and stores it in T.
char * LLVMGetTargetMachineTriple(LLVMTargetMachineRef T)
Returns the triple used creating this target machine.
char * LLVMGetHostCPUName(void)
Get the host CPU as a string.
void LLVMTargetMachineOptionsSetCPU(LLVMTargetMachineOptionsRef Options, const char *CPU)
void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T, LLVMBool VerboseAsm)
Set the target machine's ASM verbosity.
void LLVMSetTargetMachineGlobalISel(LLVMTargetMachineRef T, LLVMBool Enable)
Enable global instruction selection.
void LLVMTargetMachineOptionsSetCodeModel(LLVMTargetMachineOptionsRef Options, LLVMCodeModel CodeModel)
const char * LLVMGetTargetName(LLVMTargetRef T)
Returns the name of a target.
LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T)
Create a DataLayout based on the targetMachine.
LLVMRelocMode
LLVMCodeGenOptLevel
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition Target.h:39
LLVMGlobalISelAbortMode
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.
const char * LLVMGetTargetDescription(LLVMTargetRef T)
Returns the description of a target.
char * LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T)
Returns the feature string used creating this target machine.
LLVMBool LLVMTargetHasJIT(LLVMTargetRef T)
Returns if the target has a JIT.
void LLVMDisposeTargetMachine(LLVMTargetMachineRef T)
Dispose the LLVMTargetMachineRef instance generated by LLVMCreateTargetMachine.
LLVMTargetMachineOptionsRef LLVMCreateTargetMachineOptions(void)
Create a new set of options for an llvm::TargetMachine.
@ LLVMAssemblyFile
@ LLVMRelocPIC
@ LLVMRelocDynamicNoPic
@ LLVMRelocStatic
@ LLVMRelocRWPI
@ LLVMRelocROPI
@ LLVMRelocROPI_RWPI
@ LLVMRelocDefault
@ LLVMCodeGenLevelAggressive
@ LLVMCodeGenLevelDefault
@ LLVMCodeGenLevelNone
@ LLVMCodeGenLevelLess
@ LLVMGlobalISelAbortDisableWithDiag
@ LLVMGlobalISelAbortDisable
@ LLVMGlobalISelAbortEnable
@ DynamicNoPIC
Definition CodeGen.h:26
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition Host.cpp:2619
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:2046
LLVM_ABI std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
This is an optimization pass for GlobalISel generic memory operations.
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:178
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:149
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:152
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:397
LLVM_ABI ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
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:1772
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:392
GlobalISelAbortMode
Enable abort calls when global instruction selection fails to lower/select an instruction.
Options for LLVMCreateTargetMachine().
std::optional< Reloc::Model > RM
std::optional< CodeModel::Model > CM
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
static LLVM_ABI iterator_range< iterator > targets()