xref: /freebsd/contrib/llvm-project/clang/include/clang/Driver/ToolChain.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- ToolChain.h - Collections of tools for one platform ------*- 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 #ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
10 #define LLVM_CLANG_DRIVER_TOOLCHAIN_H
11 
12 #include "clang/Basic/LLVM.h"
13 #include "clang/Basic/LangOptions.h"
14 #include "clang/Basic/Sanitizers.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/Multilib.h"
17 #include "clang/Driver/Types.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/FloatingPointMode.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/Frontend/Debug/Options.h"
24 #include "llvm/MC/MCTargetOptions.h"
25 #include "llvm/Option/Option.h"
26 #include "llvm/Support/VersionTuple.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/TargetParser/Triple.h"
29 #include <cassert>
30 #include <climits>
31 #include <memory>
32 #include <optional>
33 #include <string>
34 #include <utility>
35 
36 namespace llvm {
37 namespace opt {
38 
39 class Arg;
40 class ArgList;
41 class DerivedArgList;
42 
43 } // namespace opt
44 namespace vfs {
45 
46 class FileSystem;
47 
48 } // namespace vfs
49 } // namespace llvm
50 
51 namespace clang {
52 
53 class ObjCRuntime;
54 
55 namespace driver {
56 
57 class Driver;
58 class InputInfo;
59 class SanitizerArgs;
60 class Tool;
61 class XRayArgs;
62 
63 /// Helper structure used to pass information extracted from clang executable
64 /// name such as `i686-linux-android-g++`.
65 struct ParsedClangName {
66   /// Target part of the executable name, as `i686-linux-android`.
67   std::string TargetPrefix;
68 
69   /// Driver mode part of the executable name, as `g++`.
70   std::string ModeSuffix;
71 
72   /// Corresponding driver mode argument, as '--driver-mode=g++'
73   const char *DriverMode = nullptr;
74 
75   /// True if TargetPrefix is recognized as a registered target name.
76   bool TargetIsValid = false;
77 
78   ParsedClangName() = default;
ParsedClangNameParsedClangName79   ParsedClangName(std::string Suffix, const char *Mode)
80       : ModeSuffix(Suffix), DriverMode(Mode) {}
ParsedClangNameParsedClangName81   ParsedClangName(std::string Target, std::string Suffix, const char *Mode,
82                   bool IsRegistered)
83       : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
84         TargetIsValid(IsRegistered) {}
85 
isEmptyParsedClangName86   bool isEmpty() const {
87     return TargetPrefix.empty() && ModeSuffix.empty() && DriverMode == nullptr;
88   }
89 };
90 
91 /// ToolChain - Access to tools for a single platform.
92 class ToolChain {
93 public:
94   using path_list = SmallVector<std::string, 16>;
95 
96   enum CXXStdlibType {
97     CST_Libcxx,
98     CST_Libstdcxx
99   };
100 
101   enum RuntimeLibType {
102     RLT_CompilerRT,
103     RLT_Libgcc
104   };
105 
106   enum UnwindLibType {
107     UNW_None,
108     UNW_CompilerRT,
109     UNW_Libgcc
110   };
111 
112   enum class UnwindTableLevel {
113     None,
114     Synchronous,
115     Asynchronous,
116   };
117 
118   enum RTTIMode {
119     RM_Enabled,
120     RM_Disabled,
121   };
122 
123   enum ExceptionsMode {
124     EM_Enabled,
125     EM_Disabled,
126   };
127 
128   struct BitCodeLibraryInfo {
129     std::string Path;
130     bool ShouldInternalize;
131     BitCodeLibraryInfo(StringRef Path, bool ShouldInternalize = true)
PathBitCodeLibraryInfo132         : Path(Path), ShouldInternalize(ShouldInternalize) {}
133   };
134 
135   enum FileType { FT_Object, FT_Static, FT_Shared };
136 
137 private:
138   friend class RegisterEffectiveTriple;
139 
140   const Driver &D;
141   llvm::Triple Triple;
142   const llvm::opt::ArgList &Args;
143 
144   // We need to initialize CachedRTTIArg before CachedRTTIMode
145   const llvm::opt::Arg *const CachedRTTIArg;
146 
147   const RTTIMode CachedRTTIMode;
148 
149   const ExceptionsMode CachedExceptionsMode;
150 
151   /// The list of toolchain specific path prefixes to search for libraries.
152   path_list LibraryPaths;
153 
154   /// The list of toolchain specific path prefixes to search for files.
155   path_list FilePaths;
156 
157   /// The list of toolchain specific path prefixes to search for programs.
158   path_list ProgramPaths;
159 
160   mutable std::unique_ptr<Tool> Clang;
161   mutable std::unique_ptr<Tool> Flang;
162   mutable std::unique_ptr<Tool> Assemble;
163   mutable std::unique_ptr<Tool> Link;
164   mutable std::unique_ptr<Tool> StaticLibTool;
165   mutable std::unique_ptr<Tool> IfsMerge;
166   mutable std::unique_ptr<Tool> OffloadBundler;
167   mutable std::unique_ptr<Tool> OffloadPackager;
168   mutable std::unique_ptr<Tool> LinkerWrapper;
169 
170   Tool *getClang() const;
171   Tool *getFlang() const;
172   Tool *getAssemble() const;
173   Tool *getLink() const;
174   Tool *getStaticLibTool() const;
175   Tool *getIfsMerge() const;
176   Tool *getClangAs() const;
177   Tool *getOffloadBundler() const;
178   Tool *getOffloadPackager() const;
179   Tool *getLinkerWrapper() const;
180 
181   mutable bool SanitizerArgsChecked = false;
182   mutable std::unique_ptr<XRayArgs> XRayArguments;
183 
184   /// The effective clang triple for the current Job.
185   mutable llvm::Triple EffectiveTriple;
186 
187   /// Set the toolchain's effective clang triple.
setEffectiveTriple(llvm::Triple ET)188   void setEffectiveTriple(llvm::Triple ET) const {
189     EffectiveTriple = std::move(ET);
190   }
191 
192   std::optional<std::string>
193   getFallbackAndroidTargetPath(StringRef BaseDir) const;
194 
195   mutable std::optional<CXXStdlibType> cxxStdlibType;
196   mutable std::optional<RuntimeLibType> runtimeLibType;
197   mutable std::optional<UnwindLibType> unwindLibType;
198 
199 protected:
200   MultilibSet Multilibs;
201   llvm::SmallVector<Multilib> SelectedMultilibs;
202 
203   ToolChain(const Driver &D, const llvm::Triple &T,
204             const llvm::opt::ArgList &Args);
205 
206   /// Executes the given \p Executable and returns the stdout.
207   llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
208   executeToolChainProgram(StringRef Executable,
209                           unsigned SecondsToWait = 0) const;
210 
211   void setTripleEnvironment(llvm::Triple::EnvironmentType Env);
212 
213   virtual Tool *buildAssembler() const;
214   virtual Tool *buildLinker() const;
215   virtual Tool *buildStaticLibTool() const;
216   virtual Tool *getTool(Action::ActionClass AC) const;
217 
218   virtual std::string buildCompilerRTBasename(const llvm::opt::ArgList &Args,
219                                               StringRef Component,
220                                               FileType Type,
221                                               bool AddArch) const;
222 
223   /// Find the target-specific subdirectory for the current target triple under
224   /// \p BaseDir, doing fallback triple searches as necessary.
225   /// \return The subdirectory path if it exists.
226   std::optional<std::string> getTargetSubDirPath(StringRef BaseDir) const;
227 
228   /// \name Utilities for implementing subclasses.
229   ///@{
230   static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
231                                llvm::opt::ArgStringList &CC1Args,
232                                const Twine &Path);
233   static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
234                                       llvm::opt::ArgStringList &CC1Args,
235                                       const Twine &Path);
236   static void
237       addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
238                                       llvm::opt::ArgStringList &CC1Args,
239                                       const Twine &Path);
240   static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
241                                 llvm::opt::ArgStringList &CC1Args,
242                                 ArrayRef<StringRef> Paths);
243 
244   static std::string concat(StringRef Path, const Twine &A, const Twine &B = "",
245                             const Twine &C = "", const Twine &D = "");
246   ///@}
247 
248 public:
249   virtual ~ToolChain();
250 
251   // Accessors
252 
getDriver()253   const Driver &getDriver() const { return D; }
254   llvm::vfs::FileSystem &getVFS() const;
getTriple()255   const llvm::Triple &getTriple() const { return Triple; }
256 
257   /// Get the toolchain's aux triple, if it has one.
258   ///
259   /// Exactly what the aux triple represents depends on the toolchain, but for
260   /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
261   /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
getAuxTriple()262   virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
263 
264   /// Some toolchains need to modify the file name, for example to replace the
265   /// extension for object files with .cubin for OpenMP offloading to Nvidia
266   /// GPUs.
267   virtual std::string getInputFilename(const InputInfo &Input) const;
268 
getArch()269   llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
getArchName()270   StringRef getArchName() const { return Triple.getArchName(); }
getPlatform()271   StringRef getPlatform() const { return Triple.getVendorName(); }
getOS()272   StringRef getOS() const { return Triple.getOSName(); }
273 
274   /// Provide the default architecture name (as expected by -arch) for
275   /// this toolchain.
276   StringRef getDefaultUniversalArchName() const;
277 
getTripleString()278   std::string getTripleString() const {
279     return Triple.getTriple();
280   }
281 
282   /// Get the toolchain's effective clang triple.
getEffectiveTriple()283   const llvm::Triple &getEffectiveTriple() const {
284     assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
285     return EffectiveTriple;
286   }
287 
hasEffectiveTriple()288   bool hasEffectiveTriple() const {
289     return !EffectiveTriple.getTriple().empty();
290   }
291 
getLibraryPaths()292   path_list &getLibraryPaths() { return LibraryPaths; }
getLibraryPaths()293   const path_list &getLibraryPaths() const { return LibraryPaths; }
294 
getFilePaths()295   path_list &getFilePaths() { return FilePaths; }
getFilePaths()296   const path_list &getFilePaths() const { return FilePaths; }
297 
getProgramPaths()298   path_list &getProgramPaths() { return ProgramPaths; }
getProgramPaths()299   const path_list &getProgramPaths() const { return ProgramPaths; }
300 
getMultilibs()301   const MultilibSet &getMultilibs() const { return Multilibs; }
302 
getSelectedMultilibs()303   const llvm::SmallVector<Multilib> &getSelectedMultilibs() const {
304     return SelectedMultilibs;
305   }
306 
307   /// Get flags suitable for multilib selection, based on the provided clang
308   /// command line arguments. The command line arguments aren't suitable to be
309   /// used directly for multilib selection because they are not normalized and
310   /// normalization is a complex process. The result of this function is similar
311   /// to clang command line arguments except that the list of arguments is
312   /// incomplete. Only certain command line arguments are processed. If more
313   /// command line arguments are needed for multilib selection then this
314   /// function should be extended.
315   /// To allow users to find out what flags are returned, clang accepts a
316   /// -print-multi-flags-experimental argument.
317   Multilib::flags_list getMultilibFlags(const llvm::opt::ArgList &) const;
318 
319   SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const;
320 
321   const XRayArgs& getXRayArgs() const;
322 
323   // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
getRTTIArg()324   const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
325 
326   // Returns the RTTIMode for the toolchain with the current arguments.
getRTTIMode()327   RTTIMode getRTTIMode() const { return CachedRTTIMode; }
328 
329   // Returns the ExceptionsMode for the toolchain with the current arguments.
getExceptionsMode()330   ExceptionsMode getExceptionsMode() const { return CachedExceptionsMode; }
331 
332   /// Return any implicit target and/or mode flag for an invocation of
333   /// the compiler driver as `ProgName`.
334   ///
335   /// For example, when called with i686-linux-android-g++, the first element
336   /// of the return value will be set to `"i686-linux-android"` and the second
337   /// will be set to "--driver-mode=g++"`.
338   /// It is OK if the target name is not registered. In this case the return
339   /// value contains false in the field TargetIsValid.
340   ///
341   /// \pre `llvm::InitializeAllTargets()` has been called.
342   /// \param ProgName The name the Clang driver was invoked with (from,
343   /// e.g., argv[0]).
344   /// \return A structure of type ParsedClangName that contains the executable
345   /// name parts.
346   static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
347 
348   // Tool access.
349 
350   /// TranslateArgs - Create a new derived argument list for any argument
351   /// translations this ToolChain may wish to perform, or 0 if no tool chain
352   /// specific translations are needed. If \p DeviceOffloadKind is specified
353   /// the translation specific for that offload kind is performed.
354   ///
355   /// \param BoundArch - The bound architecture name, or 0.
356   /// \param DeviceOffloadKind - The device offload kind used for the
357   /// translation.
358   virtual llvm::opt::DerivedArgList *
TranslateArgs(const llvm::opt::DerivedArgList & Args,StringRef BoundArch,Action::OffloadKind DeviceOffloadKind)359   TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
360                 Action::OffloadKind DeviceOffloadKind) const {
361     return nullptr;
362   }
363 
364   /// TranslateOpenMPTargetArgs - Create a new derived argument list for
365   /// that contains the OpenMP target specific flags passed via
366   /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
367   virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
368       const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
369       SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
370 
371   /// Append the argument following \p A to \p DAL assuming \p A is an Xarch
372   /// argument. If \p AllocatedArgs is null pointer, synthesized arguments are
373   /// added to \p DAL, otherwise they are appended to \p AllocatedArgs.
374   virtual void TranslateXarchArgs(
375       const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
376       llvm::opt::DerivedArgList *DAL,
377       SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs = nullptr) const;
378 
379   /// Translate -Xarch_ arguments. If there are no such arguments, return
380   /// a null pointer, otherwise return a DerivedArgList containing the
381   /// translated arguments.
382   virtual llvm::opt::DerivedArgList *
383   TranslateXarchArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
384                      Action::OffloadKind DeviceOffloadKind,
385                      SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const;
386 
387   /// Choose a tool to use to handle the action \p JA.
388   ///
389   /// This can be overridden when a particular ToolChain needs to use
390   /// a compiler other than Clang.
391   virtual Tool *SelectTool(const JobAction &JA) const;
392 
393   // Helper methods
394 
395   std::string GetFilePath(const char *Name) const;
396   std::string GetProgramPath(const char *Name) const;
397 
398   /// Returns the linker path, respecting the -fuse-ld= argument to determine
399   /// the linker suffix or name.
400   /// If LinkerIsLLD is non-nullptr, it is set to true if the returned linker
401   /// is LLD. If it's set, it can be assumed that the linker is LLD built
402   /// at the same revision as clang, and clang can make assumptions about
403   /// LLD's supported flags, error output, etc.
404   std::string GetLinkerPath(bool *LinkerIsLLD = nullptr) const;
405 
406   /// Returns the linker path for emitting a static library.
407   std::string GetStaticLibToolPath() const;
408 
409   /// Dispatch to the specific toolchain for verbose printing.
410   ///
411   /// This is used when handling the verbose option to print detailed,
412   /// toolchain-specific information useful for understanding the behavior of
413   /// the driver on a specific platform.
printVerboseInfo(raw_ostream & OS)414   virtual void printVerboseInfo(raw_ostream &OS) const {}
415 
416   // Platform defaults information
417 
418   /// Returns true if the toolchain is targeting a non-native
419   /// architecture.
420   virtual bool isCrossCompiling() const;
421 
422   /// HasNativeLTOLinker - Check whether the linker and related tools have
423   /// native LLVM support.
424   virtual bool HasNativeLLVMSupport() const;
425 
426   /// LookupTypeForExtension - Return the default language type to use for the
427   /// given extension.
428   virtual types::ID LookupTypeForExtension(StringRef Ext) const;
429 
430   /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
IsBlocksDefault()431   virtual bool IsBlocksDefault() const { return false; }
432 
433   /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
434   /// by default.
IsIntegratedAssemblerDefault()435   virtual bool IsIntegratedAssemblerDefault() const { return true; }
436 
437   /// IsIntegratedBackendDefault - Does this tool chain enable
438   /// -fintegrated-objemitter by default.
IsIntegratedBackendDefault()439   virtual bool IsIntegratedBackendDefault() const { return true; }
440 
441   /// IsIntegratedBackendSupported - Does this tool chain support
442   /// -fintegrated-objemitter.
IsIntegratedBackendSupported()443   virtual bool IsIntegratedBackendSupported() const { return true; }
444 
445   /// IsNonIntegratedBackendSupported - Does this tool chain support
446   /// -fno-integrated-objemitter.
IsNonIntegratedBackendSupported()447   virtual bool IsNonIntegratedBackendSupported() const { return false; }
448 
449   /// Check if the toolchain should use the integrated assembler.
450   virtual bool useIntegratedAs() const;
451 
452   /// Check if the toolchain should use the integrated backend.
453   virtual bool useIntegratedBackend() const;
454 
455   /// Check if the toolchain should use AsmParser to parse inlineAsm when
456   /// integrated assembler is not default.
parseInlineAsmUsingAsmParser()457   virtual bool parseInlineAsmUsingAsmParser() const { return false; }
458 
459   /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
IsMathErrnoDefault()460   virtual bool IsMathErrnoDefault() const { return true; }
461 
462   /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
463   /// -fencode-extended-block-signature by default.
IsEncodeExtendedBlockSignatureDefault()464   virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
465 
466   /// IsObjCNonFragileABIDefault - Does this tool chain set
467   /// -fobjc-nonfragile-abi by default.
IsObjCNonFragileABIDefault()468   virtual bool IsObjCNonFragileABIDefault() const { return false; }
469 
470   /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
471   /// mixed dispatch method be used?
UseObjCMixedDispatch()472   virtual bool UseObjCMixedDispatch() const { return false; }
473 
474   /// Check whether to enable x86 relax relocations by default.
475   virtual bool useRelaxRelocations() const;
476 
477   /// Check whether use IEEE binary128 as long double format by default.
478   bool defaultToIEEELongDouble() const;
479 
480   /// GetDefaultStackProtectorLevel - Get the default stack protector level for
481   /// this tool chain.
482   virtual LangOptions::StackProtectorMode
GetDefaultStackProtectorLevel(bool KernelOrKext)483   GetDefaultStackProtectorLevel(bool KernelOrKext) const {
484     return LangOptions::SSPOff;
485   }
486 
487   /// Get the default trivial automatic variable initialization.
488   virtual LangOptions::TrivialAutoVarInitKind
GetDefaultTrivialAutoVarInit()489   GetDefaultTrivialAutoVarInit() const {
490     return LangOptions::TrivialAutoVarInitKind::Uninitialized;
491   }
492 
493   /// GetDefaultLinker - Get the default linker to use.
getDefaultLinker()494   virtual const char *getDefaultLinker() const { return "ld"; }
495 
496   /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
GetDefaultRuntimeLibType()497   virtual RuntimeLibType GetDefaultRuntimeLibType() const {
498     return ToolChain::RLT_Libgcc;
499   }
500 
GetDefaultCXXStdlibType()501   virtual CXXStdlibType GetDefaultCXXStdlibType() const {
502     return ToolChain::CST_Libstdcxx;
503   }
504 
GetDefaultUnwindLibType()505   virtual UnwindLibType GetDefaultUnwindLibType() const {
506     return ToolChain::UNW_None;
507   }
508 
509   virtual std::string getCompilerRTPath() const;
510 
511   virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
512                                     StringRef Component,
513                                     FileType Type = ToolChain::FT_Static) const;
514 
515   const char *
516   getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component,
517                          FileType Type = ToolChain::FT_Static) const;
518 
519   std::string getCompilerRTBasename(const llvm::opt::ArgList &Args,
520                                     StringRef Component,
521                                     FileType Type = ToolChain::FT_Static) const;
522 
523   // Returns the target specific runtime path if it exists.
524   std::optional<std::string> getRuntimePath() const;
525 
526   // Returns target specific standard library path if it exists.
527   std::optional<std::string> getStdlibPath() const;
528 
529   // Returns target specific standard library include path if it exists.
530   std::optional<std::string> getStdlibIncludePath() const;
531 
532   // Returns <ResourceDir>/lib/<OSName>/<arch> or <ResourceDir>/lib/<triple>.
533   // This is used by runtimes (such as OpenMP) to find arch-specific libraries.
534   virtual path_list getArchSpecificLibPaths() const;
535 
536   // Returns <OSname> part of above.
537   virtual StringRef getOSLibName() const;
538 
539   /// needsProfileRT - returns true if instrumentation profile is on.
540   static bool needsProfileRT(const llvm::opt::ArgList &Args);
541 
542   /// Returns true if gcov instrumentation (-fprofile-arcs or --coverage) is on.
543   static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args);
544 
545   /// How detailed should the unwind tables be by default.
546   virtual UnwindTableLevel
547   getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const;
548 
549   /// Test whether this toolchain supports outline atomics by default.
550   virtual bool
IsAArch64OutlineAtomicsDefault(const llvm::opt::ArgList & Args)551   IsAArch64OutlineAtomicsDefault(const llvm::opt::ArgList &Args) const {
552     return false;
553   }
554 
555   /// Test whether this toolchain defaults to PIC.
556   virtual bool isPICDefault() const = 0;
557 
558   /// Test whether this toolchain defaults to PIE.
559   virtual bool isPIEDefault(const llvm::opt::ArgList &Args) const = 0;
560 
561   /// Tests whether this toolchain forces its default for PIC, PIE or
562   /// non-PIC.  If this returns true, any PIC related flags should be ignored
563   /// and instead the results of \c isPICDefault() and \c isPIEDefault(const
564   /// llvm::opt::ArgList &Args) are used exclusively.
565   virtual bool isPICDefaultForced() const = 0;
566 
567   /// SupportsProfiling - Does this tool chain support -pg.
SupportsProfiling()568   virtual bool SupportsProfiling() const { return true; }
569 
570   /// Complain if this tool chain doesn't support Objective-C ARC.
CheckObjCARC()571   virtual void CheckObjCARC() const {}
572 
573   /// Get the default debug info format. Typically, this is DWARF.
getDefaultDebugFormat()574   virtual llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const {
575     return llvm::codegenoptions::DIF_DWARF;
576   }
577 
578   /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
579   /// compile unit information.
UseDwarfDebugFlags()580   virtual bool UseDwarfDebugFlags() const { return false; }
581 
582   /// Add an additional -fdebug-prefix-map entry.
GetGlobalDebugPathRemapping()583   virtual std::string GetGlobalDebugPathRemapping() const { return {}; }
584 
585   // Return the DWARF version to emit, in the absence of arguments
586   // to the contrary.
GetDefaultDwarfVersion()587   virtual unsigned GetDefaultDwarfVersion() const { return 5; }
588 
589   // Some toolchains may have different restrictions on the DWARF version and
590   // may need to adjust it. E.g. NVPTX may need to enforce DWARF2 even when host
591   // compilation uses DWARF5.
getMaxDwarfVersion()592   virtual unsigned getMaxDwarfVersion() const { return UINT_MAX; }
593 
594   // True if the driver should assume "-fstandalone-debug"
595   // in the absence of an option specifying otherwise,
596   // provided that debugging was requested in the first place.
597   // i.e. a value of 'true' does not imply that debugging is wanted.
GetDefaultStandaloneDebug()598   virtual bool GetDefaultStandaloneDebug() const { return false; }
599 
600   // Return the default debugger "tuning."
getDefaultDebuggerTuning()601   virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
602     return llvm::DebuggerKind::GDB;
603   }
604 
605   /// Does this toolchain supports given debug info option or not.
supportsDebugInfoOption(const llvm::opt::Arg *)606   virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const {
607     return true;
608   }
609 
610   /// Adjust debug information kind considering all passed options.
611   virtual void
adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind & DebugInfoKind,const llvm::opt::ArgList & Args)612   adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
613                       const llvm::opt::ArgList &Args) const {}
614 
615   /// GetExceptionModel - Return the tool chain exception model.
616   virtual llvm::ExceptionHandling
617   GetExceptionModel(const llvm::opt::ArgList &Args) const;
618 
619   /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
SupportsEmbeddedBitcode()620   virtual bool SupportsEmbeddedBitcode() const { return false; }
621 
622   /// getThreadModel() - Which thread model does this target use?
getThreadModel()623   virtual std::string getThreadModel() const { return "posix"; }
624 
625   /// isThreadModelSupported() - Does this target support a thread model?
626   virtual bool isThreadModelSupported(const StringRef Model) const;
627 
628   /// isBareMetal - Is this a bare metal target.
isBareMetal()629   virtual bool isBareMetal() const { return false; }
630 
getMultiarchTriple(const Driver & D,const llvm::Triple & TargetTriple,StringRef SysRoot)631   virtual std::string getMultiarchTriple(const Driver &D,
632                                          const llvm::Triple &TargetTriple,
633                                          StringRef SysRoot) const {
634     return TargetTriple.str();
635   }
636 
637   /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
638   /// command line arguments into account.
639   virtual std::string
640   ComputeLLVMTriple(const llvm::opt::ArgList &Args,
641                     types::ID InputType = types::TY_INVALID) const;
642 
643   /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
644   /// target, which may take into account the command line arguments. For
645   /// example, on Darwin the -mmacos-version-min= command line argument (which
646   /// sets the deployment target) determines the version in the triple passed to
647   /// Clang.
648   virtual std::string ComputeEffectiveClangTriple(
649       const llvm::opt::ArgList &Args,
650       types::ID InputType = types::TY_INVALID) const;
651 
652   /// getDefaultObjCRuntime - Return the default Objective-C runtime
653   /// for this platform.
654   ///
655   /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
656   virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
657 
658   /// hasBlocksRuntime - Given that the user is compiling with
659   /// -fblocks, does this tool chain guarantee the existence of a
660   /// blocks runtime?
661   ///
662   /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
hasBlocksRuntime()663   virtual bool hasBlocksRuntime() const { return true; }
664 
665   /// Return the sysroot, possibly searching for a default sysroot using
666   /// target-specific logic.
667   virtual std::string computeSysRoot() const;
668 
669   /// Add the clang cc1 arguments for system include paths.
670   ///
671   /// This routine is responsible for adding the necessary cc1 arguments to
672   /// include headers from standard system header directories.
673   virtual void
674   AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
675                             llvm::opt::ArgStringList &CC1Args) const;
676 
677   /// Add options that need to be passed to cc1 for this target.
678   virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
679                                      llvm::opt::ArgStringList &CC1Args,
680                                      Action::OffloadKind DeviceOffloadKind) const;
681 
682   /// Add options that need to be passed to cc1as for this target.
683   virtual void
684   addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args,
685                              llvm::opt::ArgStringList &CC1ASArgs) const;
686 
687   /// Add warning options that need to be passed to cc1 for this target.
688   virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
689 
690   // GetRuntimeLibType - Determine the runtime library type to use with the
691   // given compilation arguments.
692   virtual RuntimeLibType
693   GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
694 
695   // GetCXXStdlibType - Determine the C++ standard library type to use with the
696   // given compilation arguments.
697   virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
698 
699   // GetUnwindLibType - Determine the unwind library type to use with the
700   // given compilation arguments.
701   virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const;
702 
703   // Detect the highest available version of libc++ in include path.
704   virtual std::string detectLibcxxVersion(StringRef IncludePath) const;
705 
706   /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
707   /// the include paths to use for the given C++ standard library type.
708   virtual void
709   AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
710                                llvm::opt::ArgStringList &CC1Args) const;
711 
712   /// AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set
713   /// the specified include paths for the C++ standard library.
714   void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs,
715                                     llvm::opt::ArgStringList &CC1Args) const;
716 
717   /// Returns if the C++ standard library should be linked in.
718   /// Note that e.g. -lm should still be linked even if this returns false.
719   bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
720 
721   /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
722   /// for the given C++ standard library type.
723   virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
724                                    llvm::opt::ArgStringList &CmdArgs) const;
725 
726   /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
727   void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
728                           llvm::opt::ArgStringList &CmdArgs) const;
729 
730   /// AddCCKextLibArgs - Add the system specific linker arguments to use
731   /// for kernel extensions (Darwin-specific).
732   virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
733                                 llvm::opt::ArgStringList &CmdArgs) const;
734 
735   /// If a runtime library exists that sets global flags for unsafe floating
736   /// point math, return true.
737   ///
738   /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
739   virtual bool isFastMathRuntimeAvailable(
740     const llvm::opt::ArgList &Args, std::string &Path) const;
741 
742   /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
743   /// global flags for unsafe floating point math, add it and return true.
744   ///
745   /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
746   bool addFastMathRuntimeIfAvailable(
747     const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
748 
749   /// getSystemGPUArchs - Use a tool to detect the user's availible GPUs.
750   virtual Expected<SmallVector<std::string>>
751   getSystemGPUArchs(const llvm::opt::ArgList &Args) const;
752 
753   /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
754   /// a suitable profile runtime library to the linker.
755   virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
756                                 llvm::opt::ArgStringList &CmdArgs) const;
757 
758   /// Add arguments to use system-specific CUDA includes.
759   virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
760                                   llvm::opt::ArgStringList &CC1Args) const;
761 
762   /// Add arguments to use system-specific HIP includes.
763   virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs,
764                                  llvm::opt::ArgStringList &CC1Args) const;
765 
766   /// Add arguments to use MCU GCC toolchain includes.
767   virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
768                                    llvm::opt::ArgStringList &CC1Args) const;
769 
770   /// On Windows, returns the MSVC compatibility version.
771   virtual VersionTuple computeMSVCVersion(const Driver *D,
772                                           const llvm::opt::ArgList &Args) const;
773 
774   /// Get paths for device libraries.
775   virtual llvm::SmallVector<BitCodeLibraryInfo, 12>
776   getDeviceLibs(const llvm::opt::ArgList &Args) const;
777 
778   /// Add the system specific linker arguments to use
779   /// for the given HIP runtime library type.
AddHIPRuntimeLibArgs(const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs)780   virtual void AddHIPRuntimeLibArgs(const llvm::opt::ArgList &Args,
781                                     llvm::opt::ArgStringList &CmdArgs) const {}
782 
783   /// Return sanitizers which are available in this toolchain.
784   virtual SanitizerMask getSupportedSanitizers() const;
785 
786   /// Return sanitizers which are enabled by default.
getDefaultSanitizers()787   virtual SanitizerMask getDefaultSanitizers() const {
788     return SanitizerMask();
789   }
790 
791   /// Returns true when it's possible to split LTO unit to use whole
792   /// program devirtualization and CFI santiizers.
canSplitThinLTOUnit()793   virtual bool canSplitThinLTOUnit() const { return true; }
794 
795   /// Returns the output denormal handling type in the default floating point
796   /// environment for the given \p FPType if given. Otherwise, the default
797   /// assumed mode for any floating point type.
798   virtual llvm::DenormalMode getDefaultDenormalModeForType(
799       const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
800       const llvm::fltSemantics *FPType = nullptr) const {
801     return llvm::DenormalMode::getIEEE();
802   }
803 
804   // We want to expand the shortened versions of the triples passed in to
805   // the values used for the bitcode libraries.
getOpenMPTriple(StringRef TripleStr)806   static llvm::Triple getOpenMPTriple(StringRef TripleStr) {
807     llvm::Triple TT(TripleStr);
808     if (TT.getVendor() == llvm::Triple::UnknownVendor ||
809         TT.getOS() == llvm::Triple::UnknownOS) {
810       if (TT.getArch() == llvm::Triple::nvptx)
811         return llvm::Triple("nvptx-nvidia-cuda");
812       if (TT.getArch() == llvm::Triple::nvptx64)
813         return llvm::Triple("nvptx64-nvidia-cuda");
814       if (TT.getArch() == llvm::Triple::amdgcn)
815         return llvm::Triple("amdgcn-amd-amdhsa");
816     }
817     return TT;
818   }
819 };
820 
821 /// Set a ToolChain's effective triple. Reset it when the registration object
822 /// is destroyed.
823 class RegisterEffectiveTriple {
824   const ToolChain &TC;
825 
826 public:
RegisterEffectiveTriple(const ToolChain & TC,llvm::Triple T)827   RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
828     TC.setEffectiveTriple(std::move(T));
829   }
830 
~RegisterEffectiveTriple()831   ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
832 };
833 
834 } // namespace driver
835 
836 } // namespace clang
837 
838 #endif // LLVM_CLANG_DRIVER_TOOLCHAIN_H
839