1 //===-- llvm/Target/TargetMachine.h - Target Information --------*- C++ -*-===// 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 defines the TargetMachine and LLVMTargetMachine classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_TARGET_TARGETMACHINE_H 14 #define LLVM_TARGET_TARGETMACHINE_H 15 16 #include "llvm/ADT/StringRef.h" 17 #include "llvm/IR/DataLayout.h" 18 #include "llvm/IR/PassManager.h" 19 #include "llvm/Support/Allocator.h" 20 #include "llvm/Support/CodeGen.h" 21 #include "llvm/Support/Error.h" 22 #include "llvm/Support/PGOOptions.h" 23 #include "llvm/Target/CGPassBuilderOption.h" 24 #include "llvm/Target/TargetOptions.h" 25 #include "llvm/TargetParser/Triple.h" 26 #include <optional> 27 #include <string> 28 #include <utility> 29 30 namespace llvm { 31 32 class AAManager; 33 using ModulePassManager = PassManager<Module>; 34 35 class Function; 36 class GlobalValue; 37 class MachineModuleInfoWrapperPass; 38 class Mangler; 39 class MCAsmInfo; 40 class MCContext; 41 class MCInstrInfo; 42 class MCRegisterInfo; 43 class MCStreamer; 44 class MCSubtargetInfo; 45 class MCSymbol; 46 class raw_pwrite_stream; 47 class PassBuilder; 48 class PassInstrumentationCallbacks; 49 struct PerFunctionMIParsingState; 50 class SMDiagnostic; 51 class SMRange; 52 class Target; 53 class TargetIntrinsicInfo; 54 class TargetIRAnalysis; 55 class TargetTransformInfo; 56 class TargetLoweringObjectFile; 57 class TargetPassConfig; 58 class TargetSubtargetInfo; 59 60 // The old pass manager infrastructure is hidden in a legacy namespace now. 61 namespace legacy { 62 class PassManagerBase; 63 } 64 using legacy::PassManagerBase; 65 66 struct MachineFunctionInfo; 67 namespace yaml { 68 struct MachineFunctionInfo; 69 } 70 71 //===----------------------------------------------------------------------===// 72 /// 73 /// Primary interface to the complete machine description for the target 74 /// machine. All target-specific information should be accessible through this 75 /// interface. 76 /// 77 class TargetMachine { 78 protected: // Can only create subclasses. 79 TargetMachine(const Target &T, StringRef DataLayoutString, 80 const Triple &TargetTriple, StringRef CPU, StringRef FS, 81 const TargetOptions &Options); 82 83 /// The Target that this machine was created for. 84 const Target &TheTarget; 85 86 /// DataLayout for the target: keep ABI type size and alignment. 87 /// 88 /// The DataLayout is created based on the string representation provided 89 /// during construction. It is kept here only to avoid reparsing the string 90 /// but should not really be used during compilation, because it has an 91 /// internal cache that is context specific. 92 const DataLayout DL; 93 94 /// Triple string, CPU name, and target feature strings the TargetMachine 95 /// instance is created with. 96 Triple TargetTriple; 97 std::string TargetCPU; 98 std::string TargetFS; 99 100 Reloc::Model RM = Reloc::Static; 101 CodeModel::Model CMModel = CodeModel::Small; 102 uint64_t LargeDataThreshold = 0; 103 CodeGenOptLevel OptLevel = CodeGenOptLevel::Default; 104 105 /// Contains target specific asm information. 106 std::unique_ptr<const MCAsmInfo> AsmInfo; 107 std::unique_ptr<const MCRegisterInfo> MRI; 108 std::unique_ptr<const MCInstrInfo> MII; 109 std::unique_ptr<const MCSubtargetInfo> STI; 110 111 unsigned RequireStructuredCFG : 1; 112 unsigned O0WantsFastISel : 1; 113 114 // PGO related tunables. 115 std::optional<PGOOptions> PGOOption; 116 117 public: 118 mutable TargetOptions Options; 119 120 TargetMachine(const TargetMachine &) = delete; 121 void operator=(const TargetMachine &) = delete; 122 virtual ~TargetMachine(); 123 124 const Target &getTarget() const { return TheTarget; } 125 126 const Triple &getTargetTriple() const { return TargetTriple; } 127 StringRef getTargetCPU() const { return TargetCPU; } 128 StringRef getTargetFeatureString() const { return TargetFS; } 129 void setTargetFeatureString(StringRef FS) { TargetFS = std::string(FS); } 130 131 /// Virtual method implemented by subclasses that returns a reference to that 132 /// target's TargetSubtargetInfo-derived member variable. 133 virtual const TargetSubtargetInfo *getSubtargetImpl(const Function &) const { 134 return nullptr; 135 } 136 virtual TargetLoweringObjectFile *getObjFileLowering() const { 137 return nullptr; 138 } 139 140 /// Create the target's instance of MachineFunctionInfo 141 virtual MachineFunctionInfo * 142 createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F, 143 const TargetSubtargetInfo *STI) const { 144 return nullptr; 145 } 146 147 /// Allocate and return a default initialized instance of the YAML 148 /// representation for the MachineFunctionInfo. 149 virtual yaml::MachineFunctionInfo *createDefaultFuncInfoYAML() const { 150 return nullptr; 151 } 152 153 /// Allocate and initialize an instance of the YAML representation of the 154 /// MachineFunctionInfo. 155 virtual yaml::MachineFunctionInfo * 156 convertFuncInfoToYAML(const MachineFunction &MF) const { 157 return nullptr; 158 } 159 160 /// Parse out the target's MachineFunctionInfo from the YAML reprsentation. 161 virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, 162 PerFunctionMIParsingState &PFS, 163 SMDiagnostic &Error, 164 SMRange &SourceRange) const { 165 return false; 166 } 167 168 /// This method returns a pointer to the specified type of 169 /// TargetSubtargetInfo. In debug builds, it verifies that the object being 170 /// returned is of the correct type. 171 template <typename STC> const STC &getSubtarget(const Function &F) const { 172 return *static_cast<const STC*>(getSubtargetImpl(F)); 173 } 174 175 /// Create a DataLayout. 176 const DataLayout createDataLayout() const { return DL; } 177 178 /// Test if a DataLayout if compatible with the CodeGen for this target. 179 /// 180 /// The LLVM Module owns a DataLayout that is used for the target independent 181 /// optimizations and code generation. This hook provides a target specific 182 /// check on the validity of this DataLayout. 183 bool isCompatibleDataLayout(const DataLayout &Candidate) const { 184 return DL == Candidate; 185 } 186 187 /// Get the pointer size for this target. 188 /// 189 /// This is the only time the DataLayout in the TargetMachine is used. 190 unsigned getPointerSize(unsigned AS) const { 191 return DL.getPointerSize(AS); 192 } 193 194 unsigned getPointerSizeInBits(unsigned AS) const { 195 return DL.getPointerSizeInBits(AS); 196 } 197 198 unsigned getProgramPointerSize() const { 199 return DL.getPointerSize(DL.getProgramAddressSpace()); 200 } 201 202 unsigned getAllocaPointerSize() const { 203 return DL.getPointerSize(DL.getAllocaAddrSpace()); 204 } 205 206 /// Reset the target options based on the function's attributes. 207 // FIXME: Remove TargetOptions that affect per-function code generation 208 // from TargetMachine. 209 void resetTargetOptions(const Function &F) const; 210 211 /// Return target specific asm information. 212 const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); } 213 214 const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); } 215 const MCInstrInfo *getMCInstrInfo() const { return MII.get(); } 216 const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); } 217 218 /// If intrinsic information is available, return it. If not, return null. 219 virtual const TargetIntrinsicInfo *getIntrinsicInfo() const { 220 return nullptr; 221 } 222 223 bool requiresStructuredCFG() const { return RequireStructuredCFG; } 224 void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; } 225 226 /// Returns the code generation relocation model. The choices are static, PIC, 227 /// and dynamic-no-pic, and target default. 228 Reloc::Model getRelocationModel() const; 229 230 /// Returns the code model. The choices are small, kernel, medium, large, and 231 /// target default. 232 CodeModel::Model getCodeModel() const { return CMModel; } 233 234 /// Returns the maximum code size possible under the code model. 235 uint64_t getMaxCodeSize() const; 236 237 /// Set the code model. 238 void setCodeModel(CodeModel::Model CM) { CMModel = CM; } 239 240 void setLargeDataThreshold(uint64_t LDT) { LargeDataThreshold = LDT; } 241 bool isLargeGlobalValue(const GlobalValue *GV) const; 242 243 bool isPositionIndependent() const; 244 245 bool shouldAssumeDSOLocal(const GlobalValue *GV) const; 246 247 /// Returns true if this target uses emulated TLS. 248 bool useEmulatedTLS() const; 249 250 /// Returns true if this target uses TLS Descriptors. 251 bool useTLSDESC() const; 252 253 /// Returns the TLS model which should be used for the given global variable. 254 TLSModel::Model getTLSModel(const GlobalValue *GV) const; 255 256 /// Returns the optimization level: None, Less, Default, or Aggressive. 257 CodeGenOptLevel getOptLevel() const; 258 259 /// Overrides the optimization level. 260 void setOptLevel(CodeGenOptLevel Level); 261 262 void setFastISel(bool Enable) { Options.EnableFastISel = Enable; } 263 bool getO0WantsFastISel() { return O0WantsFastISel; } 264 void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; } 265 void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; } 266 void setGlobalISelAbort(GlobalISelAbortMode Mode) { 267 Options.GlobalISelAbort = Mode; 268 } 269 void setMachineOutliner(bool Enable) { 270 Options.EnableMachineOutliner = Enable; 271 } 272 void setSupportsDefaultOutlining(bool Enable) { 273 Options.SupportsDefaultOutlining = Enable; 274 } 275 void setSupportsDebugEntryValues(bool Enable) { 276 Options.SupportsDebugEntryValues = Enable; 277 } 278 279 void setCFIFixup(bool Enable) { Options.EnableCFIFixup = Enable; } 280 281 bool getAIXExtendedAltivecABI() const { 282 return Options.EnableAIXExtendedAltivecABI; 283 } 284 285 bool getUniqueSectionNames() const { return Options.UniqueSectionNames; } 286 287 /// Return true if unique basic block section names must be generated. 288 bool getUniqueBasicBlockSectionNames() const { 289 return Options.UniqueBasicBlockSectionNames; 290 } 291 292 bool getSeparateNamedSections() const { 293 return Options.SeparateNamedSections; 294 } 295 296 /// Return true if data objects should be emitted into their own section, 297 /// corresponds to -fdata-sections. 298 bool getDataSections() const { 299 return Options.DataSections; 300 } 301 302 /// Return true if functions should be emitted into their own section, 303 /// corresponding to -ffunction-sections. 304 bool getFunctionSections() const { 305 return Options.FunctionSections; 306 } 307 308 /// Return true if visibility attribute should not be emitted in XCOFF, 309 /// corresponding to -mignore-xcoff-visibility. 310 bool getIgnoreXCOFFVisibility() const { 311 return Options.IgnoreXCOFFVisibility; 312 } 313 314 /// Return true if XCOFF traceback table should be emitted, 315 /// corresponding to -xcoff-traceback-table. 316 bool getXCOFFTracebackTable() const { return Options.XCOFFTracebackTable; } 317 318 /// If basic blocks should be emitted into their own section, 319 /// corresponding to -fbasic-block-sections. 320 llvm::BasicBlockSection getBBSectionsType() const { 321 return Options.BBSections; 322 } 323 324 /// Get the list of functions and basic block ids that need unique sections. 325 const MemoryBuffer *getBBSectionsFuncListBuf() const { 326 return Options.BBSectionsFuncListBuf.get(); 327 } 328 329 /// Returns true if a cast between SrcAS and DestAS is a noop. 330 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const { 331 return false; 332 } 333 334 void setPGOOption(std::optional<PGOOptions> PGOOpt) { PGOOption = PGOOpt; } 335 const std::optional<PGOOptions> &getPGOOption() const { return PGOOption; } 336 337 /// If the specified generic pointer could be assumed as a pointer to a 338 /// specific address space, return that address space. 339 /// 340 /// Under offloading programming, the offloading target may be passed with 341 /// values only prepared on the host side and could assume certain 342 /// properties. 343 virtual unsigned getAssumedAddrSpace(const Value *V) const { return -1; } 344 345 /// If the specified predicate checks whether a generic pointer falls within 346 /// a specified address space, return that generic pointer and the address 347 /// space being queried. 348 /// 349 /// Such predicates could be specified in @llvm.assume intrinsics for the 350 /// optimizer to assume that the given generic pointer always falls within 351 /// the address space based on that predicate. 352 virtual std::pair<const Value *, unsigned> 353 getPredicatedAddrSpace(const Value *V) const { 354 return std::make_pair(nullptr, -1); 355 } 356 357 /// Get a \c TargetIRAnalysis appropriate for the target. 358 /// 359 /// This is used to construct the new pass manager's target IR analysis pass, 360 /// set up appropriately for this target machine. Even the old pass manager 361 /// uses this to answer queries about the IR. 362 TargetIRAnalysis getTargetIRAnalysis() const; 363 364 /// Return a TargetTransformInfo for a given function. 365 /// 366 /// The returned TargetTransformInfo is specialized to the subtarget 367 /// corresponding to \p F. 368 virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const; 369 370 /// Allow the target to modify the pass pipeline. 371 // TODO: Populate all pass names by using <Target>PassRegistry.def. 372 virtual void registerPassBuilderCallbacks(PassBuilder &) {} 373 374 /// Allow the target to register alias analyses with the AAManager for use 375 /// with the new pass manager. Only affects the "default" AAManager. 376 virtual void registerDefaultAliasAnalyses(AAManager &) {} 377 378 /// Add passes to the specified pass manager to get the specified file 379 /// emitted. Typically this will involve several steps of code generation. 380 /// This method should return true if emission of this file type is not 381 /// supported, or false on success. 382 /// \p MMIWP is an optional parameter that, if set to non-nullptr, 383 /// will be used to set the MachineModuloInfo for this PM. 384 virtual bool 385 addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, 386 raw_pwrite_stream *, CodeGenFileType, 387 bool /*DisableVerify*/ = true, 388 MachineModuleInfoWrapperPass *MMIWP = nullptr) { 389 return true; 390 } 391 392 /// Add passes to the specified pass manager to get machine code emitted with 393 /// the MCJIT. This method returns true if machine code is not supported. It 394 /// fills the MCContext Ctx pointer which can be used to build custom 395 /// MCStreamer. 396 /// 397 virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&, 398 raw_pwrite_stream &, 399 bool /*DisableVerify*/ = true) { 400 return true; 401 } 402 403 /// True if subtarget inserts the final scheduling pass on its own. 404 /// 405 /// Branch relaxation, which must happen after block placement, can 406 /// on some targets (e.g. SystemZ) expose additional post-RA 407 /// scheduling opportunities. 408 virtual bool targetSchedulesPostRAScheduling() const { return false; }; 409 410 void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV, 411 Mangler &Mang, bool MayAlwaysUsePrivate = false) const; 412 MCSymbol *getSymbol(const GlobalValue *GV) const; 413 414 /// The integer bit size to use for SjLj based exception handling. 415 static constexpr unsigned DefaultSjLjDataSize = 32; 416 virtual unsigned getSjLjDataSize() const { return DefaultSjLjDataSize; } 417 418 static std::pair<int, int> parseBinutilsVersion(StringRef Version); 419 420 /// getAddressSpaceForPseudoSourceKind - Given the kind of memory 421 /// (e.g. stack) the target returns the corresponding address space. 422 virtual unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const { 423 return 0; 424 } 425 426 /// Entry point for module splitting. Targets can implement custom module 427 /// splitting logic, mainly used by LTO for --lto-partitions. 428 /// 429 /// \returns `true` if the module was split, `false` otherwise. When `false` 430 /// is returned, it is assumed that \p ModuleCallback has never been called 431 /// and \p M has not been modified. 432 virtual bool splitModule( 433 Module &M, unsigned NumParts, 434 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) { 435 return false; 436 } 437 }; 438 439 /// This class describes a target machine that is implemented with the LLVM 440 /// target-independent code generator. 441 /// 442 class LLVMTargetMachine : public TargetMachine { 443 protected: // Can only create subclasses. 444 LLVMTargetMachine(const Target &T, StringRef DataLayoutString, 445 const Triple &TT, StringRef CPU, StringRef FS, 446 const TargetOptions &Options, Reloc::Model RM, 447 CodeModel::Model CM, CodeGenOptLevel OL); 448 449 void initAsmInfo(); 450 451 public: 452 /// Get a TargetTransformInfo implementation for the target. 453 /// 454 /// The TTI returned uses the common code generator to answer queries about 455 /// the IR. 456 TargetTransformInfo getTargetTransformInfo(const Function &F) const override; 457 458 /// Create a pass configuration object to be used by addPassToEmitX methods 459 /// for generating a pipeline of CodeGen passes. 460 virtual TargetPassConfig *createPassConfig(PassManagerBase &PM); 461 462 /// Add passes to the specified pass manager to get the specified file 463 /// emitted. Typically this will involve several steps of code generation. 464 /// \p MMIWP is an optional parameter that, if set to non-nullptr, 465 /// will be used to set the MachineModuloInfo for this PM. 466 bool 467 addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out, 468 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, 469 bool DisableVerify = true, 470 MachineModuleInfoWrapperPass *MMIWP = nullptr) override; 471 472 virtual Error buildCodeGenPipeline(ModulePassManager &, raw_pwrite_stream &, 473 raw_pwrite_stream *, CodeGenFileType, 474 const CGPassBuilderOption &, 475 PassInstrumentationCallbacks *) { 476 return make_error<StringError>("buildCodeGenPipeline is not overridden", 477 inconvertibleErrorCode()); 478 } 479 480 /// Add passes to the specified pass manager to get machine code emitted with 481 /// the MCJIT. This method returns true if machine code is not supported. It 482 /// fills the MCContext Ctx pointer which can be used to build custom 483 /// MCStreamer. 484 bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 485 raw_pwrite_stream &Out, 486 bool DisableVerify = true) override; 487 488 /// Returns true if the target is expected to pass all machine verifier 489 /// checks. This is a stopgap measure to fix targets one by one. We will 490 /// remove this at some point and always enable the verifier when 491 /// EXPENSIVE_CHECKS is enabled. 492 virtual bool isMachineVerifierClean() const { return true; } 493 494 /// Adds an AsmPrinter pass to the pipeline that prints assembly or 495 /// machine code from the MI representation. 496 bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out, 497 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, 498 MCContext &Context); 499 500 Expected<std::unique_ptr<MCStreamer>> 501 createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, 502 CodeGenFileType FileType, MCContext &Ctx); 503 504 /// True if the target uses physical regs (as nearly all targets do). False 505 /// for stack machines such as WebAssembly and other virtual-register 506 /// machines. If true, all vregs must be allocated before PEI. If false, then 507 /// callee-save register spilling and scavenging are not needed or used. If 508 /// false, implicitly defined registers will still be assumed to be physical 509 /// registers, except that variadic defs will be allocated vregs. 510 virtual bool usesPhysRegsForValues() const { return true; } 511 512 /// True if the target wants to use interprocedural register allocation by 513 /// default. The -enable-ipra flag can be used to override this. 514 virtual bool useIPRA() const { 515 return false; 516 } 517 518 /// The default variant to use in unqualified `asm` instructions. 519 /// If this returns 0, `asm "$(foo$|bar$)"` will evaluate to `asm "foo"`. 520 virtual int unqualifiedInlineAsmVariant() const { return 0; } 521 522 // MachineRegisterInfo callback function 523 virtual void registerMachineRegisterInfoCallback(MachineFunction &MF) const {} 524 }; 525 526 /// Helper method for getting the code model, returning Default if 527 /// CM does not have a value. The tiny and kernel models will produce 528 /// an error, so targets that support them or require more complex codemodel 529 /// selection logic should implement and call their own getEffectiveCodeModel. 530 inline CodeModel::Model 531 getEffectiveCodeModel(std::optional<CodeModel::Model> CM, 532 CodeModel::Model Default) { 533 if (CM) { 534 // By default, targets do not support the tiny and kernel models. 535 if (*CM == CodeModel::Tiny) 536 report_fatal_error("Target does not support the tiny CodeModel", false); 537 if (*CM == CodeModel::Kernel) 538 report_fatal_error("Target does not support the kernel CodeModel", false); 539 return *CM; 540 } 541 return Default; 542 } 543 544 } // end namespace llvm 545 546 #endif // LLVM_TARGET_TARGETMACHINE_H 547