LLVM 22.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 <cstring>
28#include <optional>
29
30using namespace llvm;
31
32namespace llvm {
33
34/// Options for LLVMCreateTargetMachine().
36 std::string CPU;
37 std::string Features;
38 std::string ABI;
40 std::optional<Reloc::Model> RM;
41 std::optional<CodeModel::Model> CM;
42 bool JIT;
43};
44
45} // namespace llvm
46
54 return reinterpret_cast<Target*>(P);
55}
57 return reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine *>(P));
58}
59static LLVMTargetRef wrap(const Target * P) {
60 return reinterpret_cast<LLVMTargetRef>(const_cast<Target*>(P));
61}
62
64 if (TargetRegistry::targets().begin() == TargetRegistry::targets().end()) {
65 return nullptr;
66 }
67
68 const Target *target = &*TargetRegistry::targets().begin();
69 return wrap(target);
70}
74
76 StringRef NameRef = Name;
78 [&](const Target &T) { return T.getName() == NameRef; });
79 return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr;
80}
81
83 char **ErrorMessage) {
84 std::string Error;
85
86 Triple TT(TripleStr);
88
89 if (!*T) {
90 if (ErrorMessage)
91 *ErrorMessage = strdup(Error.c_str());
92
93 return 1;
94 }
95
96 return 0;
97}
98
100 return unwrap(T)->getName();
101}
102
104 return unwrap(T)->getShortDescription();
105}
106
108 return unwrap(T)->hasJIT();
109}
110
112 return unwrap(T)->hasTargetMachine();
113}
114
116 return unwrap(T)->hasMCAsmBackend();
117}
118
122
126
128 const char *CPU) {
129 unwrap(Options)->CPU = CPU;
130}
131
133 const char *Features) {
134 unwrap(Options)->Features = Features;
135}
136
138 const char *ABI) {
139 unwrap(Options)->ABI = ABI;
140}
141
145
146 switch (Level) {
149 break;
152 break;
155 break;
158 break;
159 }
160
161 unwrap(Options)->OL = OL;
162}
163
166 std::optional<Reloc::Model> RM;
167
168 switch (Reloc) {
169 case LLVMRelocStatic:
170 RM = Reloc::Static;
171 break;
172 case LLVMRelocPIC:
173 RM = Reloc::PIC_;
174 break;
177 break;
178 case LLVMRelocROPI:
179 RM = Reloc::ROPI;
180 break;
181 case LLVMRelocRWPI:
182 RM = Reloc::RWPI;
183 break;
185 RM = Reloc::ROPI_RWPI;
186 break;
187 case LLVMRelocDefault:
188 break;
189 }
190
191 unwrap(Options)->RM = RM;
192}
193
199
203 auto *Opt = unwrap(Options);
204 TargetOptions TO;
205 TO.MCOptions.ABIName = Opt->ABI;
206 return wrap(unwrap(T)->createTargetMachine(Triple(TripleStr), Opt->CPU,
207 Opt->Features, TO, Opt->RM,
208 Opt->CM, Opt->OL, Opt->JIT));
209}
210
228
230
232 const Target* target = &(unwrap(T)->getTarget());
233 return wrap(target);
234}
235
237 std::string StringRep = unwrap(T)->getTargetTriple().str();
238 return strdup(StringRep.c_str());
239}
240
242 std::string StringRep = std::string(unwrap(T)->getTargetCPU());
243 return strdup(StringRep.c_str());
244}
245
247 std::string StringRep = std::string(unwrap(T)->getTargetFeatureString());
248 return strdup(StringRep.c_str());
249}
250
252 LLVMBool VerboseAsm) {
253 unwrap(T)->Options.MCOptions.AsmVerbose = VerboseAsm;
254}
255
259
263
281
286
290
294 char **ErrorMessage) {
295 TargetMachine* TM = unwrap(T);
296 Module* Mod = unwrap(M);
297
299
300 std::string error;
301
302 Mod->setDataLayout(TM->createDataLayout());
303
305 switch (codegen) {
306 case LLVMAssemblyFile:
308 break;
309 default:
311 break;
312 }
313 if (TM->addPassesToEmitFile(pass, OS, nullptr, ft)) {
314 error = "TargetMachine can't emit a file of this type";
315 *ErrorMessage = strdup(error.c_str());
316 return true;
317 }
318
319 pass.run(*Mod);
320
321 OS.flush();
322 return false;
323}
324
326 const char *Filename,
328 char **ErrorMessage) {
329 std::error_code EC;
330 raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);
331 if (EC) {
332 *ErrorMessage = strdup(EC.message().c_str());
333 return true;
334 }
335 bool Result = LLVMTargetMachineEmit(T, M, dest, codegen, ErrorMessage);
336 dest.flush();
337 return Result;
338}
339
341 LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
342 LLVMMemoryBufferRef *OutMemBuf) {
343 SmallString<0> CodeString;
344 raw_svector_ostream OStream(CodeString);
345 bool Result = LLVMTargetMachineEmit(T, M, OStream, codegen, ErrorMessage);
346
347 StringRef Data = OStream.str();
348 *OutMemBuf =
350 return Result;
351}
352
354 return strdup(sys::getDefaultTargetTriple().c_str());
355}
356
357char *LLVMNormalizeTargetTriple(const char* triple) {
358 return strdup(Triple::normalize(StringRef(triple)).c_str());
359}
360
362 return strdup(sys::getHostCPUName().data());
363}
364
366 SubtargetFeatures Features;
367 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
368 Features.AddFeature(Feature, IsEnabled);
369
370 return strdup(Features.getString().c_str());
371}
372
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
@ Enable
global merge Global merge function pass
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:58
#define T
static std::unique_ptr< TargetMachine > createTargetMachine(Function *F, CodeGenOptLevel OptLevel)
Create the TargetMachine object to query the backend for optimization preferences.
#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:63
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
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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.
MCTargetOptions MCOptions
Machine level options.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
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:1165
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:4556
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:38
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:25
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition Host.cpp:2400
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:1956
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:111
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
@ Default
-O2, -Os
Definition CodeGen.h:85
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:351
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:1738
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:346
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 const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
static LLVM_ABI iterator_range< iterator > targets()