]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - include/clang/Driver/ToolChain.h
Vendor import of clang trunk r351319 (just before the release_80 branch
[FreeBSD/FreeBSD.git] / include / clang / Driver / ToolChain.h
1 //===- ToolChain.h - Collections of tools for one platform ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
11 #define LLVM_CLANG_DRIVER_TOOLCHAIN_H
12
13 #include "clang/Basic/DebugInfoOptions.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Basic/LangOptions.h"
16 #include "clang/Basic/Sanitizers.h"
17 #include "clang/Driver/Action.h"
18 #include "clang/Driver/Multilib.h"
19 #include "clang/Driver/Types.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.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 <cassert>
29 #include <memory>
30 #include <string>
31 #include <utility>
32
33 namespace llvm {
34 namespace opt {
35
36 class Arg;
37 class ArgList;
38 class DerivedArgList;
39
40 } // namespace opt
41 namespace vfs {
42
43 class FileSystem;
44
45 } // namespace vfs
46 } // namespace llvm
47
48 namespace clang {
49
50 class ObjCRuntime;
51
52 namespace driver {
53
54 class Driver;
55 class InputInfo;
56 class SanitizerArgs;
57 class Tool;
58 class XRayArgs;
59
60 /// Helper structure used to pass information extracted from clang executable
61 /// name such as `i686-linux-android-g++`.
62 struct ParsedClangName {
63   /// Target part of the executable name, as `i686-linux-android`.
64   std::string TargetPrefix;
65
66   /// Driver mode part of the executable name, as `g++`.
67   std::string ModeSuffix;
68
69   /// Corresponding driver mode argument, as '--driver-mode=g++'
70   const char *DriverMode = nullptr;
71
72   /// True if TargetPrefix is recognized as a registered target name.
73   bool TargetIsValid = false;
74
75   ParsedClangName() = default;
76   ParsedClangName(std::string Suffix, const char *Mode)
77       : ModeSuffix(Suffix), DriverMode(Mode) {}
78   ParsedClangName(std::string Target, std::string Suffix, const char *Mode,
79                   bool IsRegistered)
80       : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
81         TargetIsValid(IsRegistered) {}
82
83   bool isEmpty() const {
84     return TargetPrefix.empty() && ModeSuffix.empty() && DriverMode == nullptr;
85   }
86 };
87
88 /// ToolChain - Access to tools for a single platform.
89 class ToolChain {
90 public:
91   using path_list = SmallVector<std::string, 16>;
92
93   enum CXXStdlibType {
94     CST_Libcxx,
95     CST_Libstdcxx
96   };
97
98   enum RuntimeLibType {
99     RLT_CompilerRT,
100     RLT_Libgcc
101   };
102
103   enum RTTIMode {
104     RM_Enabled,
105     RM_Disabled,
106   };
107
108 private:
109   friend class RegisterEffectiveTriple;
110
111   const Driver &D;
112   llvm::Triple Triple;
113   const llvm::opt::ArgList &Args;
114
115   // We need to initialize CachedRTTIArg before CachedRTTIMode
116   const llvm::opt::Arg *const CachedRTTIArg;
117
118   const RTTIMode CachedRTTIMode;
119
120   /// The list of toolchain specific path prefixes to search for libraries.
121   path_list LibraryPaths;
122
123   /// The list of toolchain specific path prefixes to search for files.
124   path_list FilePaths;
125
126   /// The list of toolchain specific path prefixes to search for programs.
127   path_list ProgramPaths;
128
129   mutable std::unique_ptr<Tool> Clang;
130   mutable std::unique_ptr<Tool> Assemble;
131   mutable std::unique_ptr<Tool> Link;
132   mutable std::unique_ptr<Tool> OffloadBundler;
133
134   Tool *getClang() const;
135   Tool *getAssemble() const;
136   Tool *getLink() const;
137   Tool *getClangAs() const;
138   Tool *getOffloadBundler() const;
139
140   mutable std::unique_ptr<SanitizerArgs> SanitizerArguments;
141   mutable std::unique_ptr<XRayArgs> XRayArguments;
142
143   /// The effective clang triple for the current Job.
144   mutable llvm::Triple EffectiveTriple;
145
146   /// Set the toolchain's effective clang triple.
147   void setEffectiveTriple(llvm::Triple ET) const {
148     EffectiveTriple = std::move(ET);
149   }
150
151 protected:
152   MultilibSet Multilibs;
153   Multilib SelectedMultilib;
154
155   ToolChain(const Driver &D, const llvm::Triple &T,
156             const llvm::opt::ArgList &Args);
157
158   void setTripleEnvironment(llvm::Triple::EnvironmentType Env);
159
160   virtual Tool *buildAssembler() const;
161   virtual Tool *buildLinker() const;
162   virtual Tool *getTool(Action::ActionClass AC) const;
163
164   /// \name Utilities for implementing subclasses.
165   ///@{
166   static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
167                                llvm::opt::ArgStringList &CC1Args,
168                                const Twine &Path);
169   static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
170                                       llvm::opt::ArgStringList &CC1Args,
171                                       const Twine &Path);
172   static void
173       addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
174                                       llvm::opt::ArgStringList &CC1Args,
175                                       const Twine &Path);
176   static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
177                                 llvm::opt::ArgStringList &CC1Args,
178                                 ArrayRef<StringRef> Paths);
179   ///@}
180
181 public:
182   virtual ~ToolChain();
183
184   // Accessors
185
186   const Driver &getDriver() const { return D; }
187   llvm::vfs::FileSystem &getVFS() const;
188   const llvm::Triple &getTriple() const { return Triple; }
189
190   /// Get the toolchain's aux triple, if it has one.
191   ///
192   /// Exactly what the aux triple represents depends on the toolchain, but for
193   /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
194   /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
195   virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
196
197   /// Some toolchains need to modify the file name, for example to replace the
198   /// extension for object files with .cubin for OpenMP offloading to Nvidia
199   /// GPUs.
200   virtual std::string getInputFilename(const InputInfo &Input) const;
201
202   llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
203   StringRef getArchName() const { return Triple.getArchName(); }
204   StringRef getPlatform() const { return Triple.getVendorName(); }
205   StringRef getOS() const { return Triple.getOSName(); }
206
207   /// Provide the default architecture name (as expected by -arch) for
208   /// this toolchain.
209   StringRef getDefaultUniversalArchName() const;
210
211   std::string getTripleString() const {
212     return Triple.getTriple();
213   }
214
215   /// Get the toolchain's effective clang triple.
216   const llvm::Triple &getEffectiveTriple() const {
217     assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
218     return EffectiveTriple;
219   }
220
221   path_list &getLibraryPaths() { return LibraryPaths; }
222   const path_list &getLibraryPaths() const { return LibraryPaths; }
223
224   path_list &getFilePaths() { return FilePaths; }
225   const path_list &getFilePaths() const { return FilePaths; }
226
227   path_list &getProgramPaths() { return ProgramPaths; }
228   const path_list &getProgramPaths() const { return ProgramPaths; }
229
230   const MultilibSet &getMultilibs() const { return Multilibs; }
231
232   const Multilib &getMultilib() const { return SelectedMultilib; }
233
234   const SanitizerArgs& getSanitizerArgs() const;
235
236   const XRayArgs& getXRayArgs() const;
237
238   // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
239   const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
240
241   // Returns the RTTIMode for the toolchain with the current arguments.
242   RTTIMode getRTTIMode() const { return CachedRTTIMode; }
243
244   /// Return any implicit target and/or mode flag for an invocation of
245   /// the compiler driver as `ProgName`.
246   ///
247   /// For example, when called with i686-linux-android-g++, the first element
248   /// of the return value will be set to `"i686-linux-android"` and the second
249   /// will be set to "--driver-mode=g++"`.
250   /// It is OK if the target name is not registered. In this case the return
251   /// value contains false in the field TargetIsValid.
252   ///
253   /// \pre `llvm::InitializeAllTargets()` has been called.
254   /// \param ProgName The name the Clang driver was invoked with (from,
255   /// e.g., argv[0]).
256   /// \return A structure of type ParsedClangName that contains the executable
257   /// name parts.
258   static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
259
260   // Tool access.
261
262   /// TranslateArgs - Create a new derived argument list for any argument
263   /// translations this ToolChain may wish to perform, or 0 if no tool chain
264   /// specific translations are needed. If \p DeviceOffloadKind is specified
265   /// the translation specific for that offload kind is performed.
266   ///
267   /// \param BoundArch - The bound architecture name, or 0.
268   /// \param DeviceOffloadKind - The device offload kind used for the
269   /// translation.
270   virtual llvm::opt::DerivedArgList *
271   TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
272                 Action::OffloadKind DeviceOffloadKind) const {
273     return nullptr;
274   }
275
276   /// TranslateOpenMPTargetArgs - Create a new derived argument list for
277   /// that contains the OpenMP target specific flags passed via
278   /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
279   virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
280       const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
281       SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
282
283   /// Choose a tool to use to handle the action \p JA.
284   ///
285   /// This can be overridden when a particular ToolChain needs to use
286   /// a compiler other than Clang.
287   virtual Tool *SelectTool(const JobAction &JA) const;
288
289   // Helper methods
290
291   std::string GetFilePath(const char *Name) const;
292   std::string GetProgramPath(const char *Name) const;
293
294   /// Returns the linker path, respecting the -fuse-ld= argument to determine
295   /// the linker suffix or name.
296   std::string GetLinkerPath() const;
297
298   /// Dispatch to the specific toolchain for verbose printing.
299   ///
300   /// This is used when handling the verbose option to print detailed,
301   /// toolchain-specific information useful for understanding the behavior of
302   /// the driver on a specific platform.
303   virtual void printVerboseInfo(raw_ostream &OS) const {}
304
305   // Platform defaults information
306
307   /// Returns true if the toolchain is targeting a non-native
308   /// architecture.
309   virtual bool isCrossCompiling() const;
310
311   /// HasNativeLTOLinker - Check whether the linker and related tools have
312   /// native LLVM support.
313   virtual bool HasNativeLLVMSupport() const;
314
315   /// LookupTypeForExtension - Return the default language type to use for the
316   /// given extension.
317   virtual types::ID LookupTypeForExtension(StringRef Ext) const;
318
319   /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
320   virtual bool IsBlocksDefault() const { return false; }
321
322   /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
323   /// by default.
324   virtual bool IsIntegratedAssemblerDefault() const { return false; }
325
326   /// Check if the toolchain should use the integrated assembler.
327   virtual bool useIntegratedAs() const;
328
329   /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
330   virtual bool IsMathErrnoDefault() const { return true; }
331
332   /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
333   /// -fencode-extended-block-signature by default.
334   virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
335
336   /// IsObjCNonFragileABIDefault - Does this tool chain set
337   /// -fobjc-nonfragile-abi by default.
338   virtual bool IsObjCNonFragileABIDefault() const { return false; }
339
340   /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
341   /// mixed dispatch method be used?
342   virtual bool UseObjCMixedDispatch() const { return false; }
343
344   /// Check whether to enable x86 relax relocations by default.
345   virtual bool useRelaxRelocations() const;
346
347   /// GetDefaultStackProtectorLevel - Get the default stack protector level for
348   /// this tool chain (0=off, 1=on, 2=strong, 3=all).
349   virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
350     return 0;
351   }
352
353   /// Get the default trivial automatic variable initialization.
354   virtual LangOptions::TrivialAutoVarInitKind
355   GetDefaultTrivialAutoVarInit() const {
356     return LangOptions::TrivialAutoVarInitKind::Uninitialized;
357   }
358
359   /// GetDefaultLinker - Get the default linker to use.
360   virtual const char *getDefaultLinker() const { return "ld"; }
361
362   /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
363   virtual RuntimeLibType GetDefaultRuntimeLibType() const {
364     return ToolChain::RLT_Libgcc;
365   }
366
367   virtual CXXStdlibType GetDefaultCXXStdlibType() const {
368     return ToolChain::CST_Libstdcxx;
369   }
370
371   virtual std::string getCompilerRTPath() const;
372
373   virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
374                                     StringRef Component,
375                                     bool Shared = false) const;
376
377   const char *getCompilerRTArgString(const llvm::opt::ArgList &Args,
378                                      StringRef Component,
379                                      bool Shared = false) const;
380
381   // Returns <ResourceDir>/lib/<OSName>/<arch>.  This is used by runtimes (such
382   // as OpenMP) to find arch-specific libraries.
383   std::string getArchSpecificLibPath() const;
384
385   // Returns <OSname> part of above.
386   StringRef getOSLibName() const;
387
388   /// needsProfileRT - returns true if instrumentation profile is on.
389   static bool needsProfileRT(const llvm::opt::ArgList &Args);
390
391   /// Returns true if gcov instrumentation (-fprofile-arcs or --coverage) is on.
392   static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args);
393
394   /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
395   /// by default.
396   virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const;
397
398   /// Test whether this toolchain defaults to PIC.
399   virtual bool isPICDefault() const = 0;
400
401   /// Test whether this toolchain defaults to PIE.
402   virtual bool isPIEDefault() const = 0;
403
404   /// Tests whether this toolchain forces its default for PIC, PIE or
405   /// non-PIC.  If this returns true, any PIC related flags should be ignored
406   /// and instead the results of \c isPICDefault() and \c isPIEDefault() are
407   /// used exclusively.
408   virtual bool isPICDefaultForced() const = 0;
409
410   /// SupportsProfiling - Does this tool chain support -pg.
411   virtual bool SupportsProfiling() const { return true; }
412
413   /// Complain if this tool chain doesn't support Objective-C ARC.
414   virtual void CheckObjCARC() const {}
415
416   /// Get the default debug info format. Typically, this is DWARF.
417   virtual codegenoptions::DebugInfoFormat getDefaultDebugFormat() const {
418     return codegenoptions::DIF_DWARF;
419   }
420
421   /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
422   /// compile unit information.
423   virtual bool UseDwarfDebugFlags() const { return false; }
424
425   // Return the DWARF version to emit, in the absence of arguments
426   // to the contrary.
427   virtual unsigned GetDefaultDwarfVersion() const { return 4; }
428
429   // True if the driver should assume "-fstandalone-debug"
430   // in the absence of an option specifying otherwise,
431   // provided that debugging was requested in the first place.
432   // i.e. a value of 'true' does not imply that debugging is wanted.
433   virtual bool GetDefaultStandaloneDebug() const { return false; }
434
435   // Return the default debugger "tuning."
436   virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
437     return llvm::DebuggerKind::GDB;
438   }
439
440   /// Does this toolchain supports given debug info option or not.
441   virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const {
442     return true;
443   }
444
445   /// Adjust debug information kind considering all passed options.
446   virtual void adjustDebugInfoKind(codegenoptions::DebugInfoKind &DebugInfoKind,
447                                    const llvm::opt::ArgList &Args) const {}
448
449   /// GetExceptionModel - Return the tool chain exception model.
450   virtual llvm::ExceptionHandling
451   GetExceptionModel(const llvm::opt::ArgList &Args) const;
452
453   /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
454   virtual bool SupportsEmbeddedBitcode() const { return false; }
455
456   /// getThreadModel() - Which thread model does this target use?
457   virtual std::string getThreadModel() const { return "posix"; }
458
459   /// isThreadModelSupported() - Does this target support a thread model?
460   virtual bool isThreadModelSupported(const StringRef Model) const;
461
462   /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
463   /// command line arguments into account.
464   virtual std::string
465   ComputeLLVMTriple(const llvm::opt::ArgList &Args,
466                     types::ID InputType = types::TY_INVALID) const;
467
468   /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
469   /// target, which may take into account the command line arguments. For
470   /// example, on Darwin the -mmacosx-version-min= command line argument (which
471   /// sets the deployment target) determines the version in the triple passed to
472   /// Clang.
473   virtual std::string ComputeEffectiveClangTriple(
474       const llvm::opt::ArgList &Args,
475       types::ID InputType = types::TY_INVALID) const;
476
477   /// getDefaultObjCRuntime - Return the default Objective-C runtime
478   /// for this platform.
479   ///
480   /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
481   virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
482
483   /// hasBlocksRuntime - Given that the user is compiling with
484   /// -fblocks, does this tool chain guarantee the existence of a
485   /// blocks runtime?
486   ///
487   /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
488   virtual bool hasBlocksRuntime() const { return true; }
489
490   /// Add the clang cc1 arguments for system include paths.
491   ///
492   /// This routine is responsible for adding the necessary cc1 arguments to
493   /// include headers from standard system header directories.
494   virtual void
495   AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
496                             llvm::opt::ArgStringList &CC1Args) const;
497
498   /// Add options that need to be passed to cc1 for this target.
499   virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
500                                      llvm::opt::ArgStringList &CC1Args,
501                                      Action::OffloadKind DeviceOffloadKind) const;
502
503   /// Add warning options that need to be passed to cc1 for this target.
504   virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
505
506   // GetRuntimeLibType - Determine the runtime library type to use with the
507   // given compilation arguments.
508   virtual RuntimeLibType
509   GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
510
511   // GetCXXStdlibType - Determine the C++ standard library type to use with the
512   // given compilation arguments.
513   virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
514
515   /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
516   /// the include paths to use for the given C++ standard library type.
517   virtual void
518   AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
519                                llvm::opt::ArgStringList &CC1Args) const;
520
521   /// Returns if the C++ standard library should be linked in.
522   /// Note that e.g. -lm should still be linked even if this returns false.
523   bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
524
525   /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
526   /// for the given C++ standard library type.
527   virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
528                                    llvm::opt::ArgStringList &CmdArgs) const;
529
530   /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
531   void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
532                           llvm::opt::ArgStringList &CmdArgs) const;
533
534   /// AddCCKextLibArgs - Add the system specific linker arguments to use
535   /// for kernel extensions (Darwin-specific).
536   virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
537                                 llvm::opt::ArgStringList &CmdArgs) const;
538
539   /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
540   /// global flags for unsafe floating point math, add it and return true.
541   ///
542   /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
543   virtual bool AddFastMathRuntimeIfAvailable(
544       const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
545
546   /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
547   /// a suitable profile runtime library to the linker.
548   virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
549                                 llvm::opt::ArgStringList &CmdArgs) const;
550
551   /// Add arguments to use system-specific CUDA includes.
552   virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
553                                   llvm::opt::ArgStringList &CC1Args) const;
554
555   /// Add arguments to use MCU GCC toolchain includes.
556   virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
557                                    llvm::opt::ArgStringList &CC1Args) const;
558
559   /// On Windows, returns the MSVC compatibility version.
560   virtual VersionTuple computeMSVCVersion(const Driver *D,
561                                           const llvm::opt::ArgList &Args) const;
562
563   /// Return sanitizers which are available in this toolchain.
564   virtual SanitizerMask getSupportedSanitizers() const;
565
566   /// Return sanitizers which are enabled by default.
567   virtual SanitizerMask getDefaultSanitizers() const { return 0; }
568 };
569
570 /// Set a ToolChain's effective triple. Reset it when the registration object
571 /// is destroyed.
572 class RegisterEffectiveTriple {
573   const ToolChain &TC;
574
575 public:
576   RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
577     TC.setEffectiveTriple(std::move(T));
578   }
579
580   ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
581 };
582
583 } // namespace driver
584
585 } // namespace clang
586
587 #endif // LLVM_CLANG_DRIVER_TOOLCHAIN_H