xref: /freebsd/contrib/llvm-project/clang/include/clang/Driver/Driver.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- 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_DRIVER_H
10 #define LLVM_CLANG_DRIVER_DRIVER_H
11 
12 #include "clang/Basic/Diagnostic.h"
13 #include "clang/Basic/HeaderInclude.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/InputInfo.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/Phases.h"
20 #include "clang/Driver/ToolChain.h"
21 #include "clang/Driver/Types.h"
22 #include "clang/Driver/Util.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/STLFunctionalExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Option/Arg.h"
28 #include "llvm/Option/ArgList.h"
29 #include "llvm/Support/StringSaver.h"
30 
31 #include <map>
32 #include <set>
33 #include <string>
34 #include <vector>
35 
36 namespace llvm {
37 class Triple;
38 namespace vfs {
39 class FileSystem;
40 }
41 namespace cl {
42 class ExpansionContext;
43 }
44 } // namespace llvm
45 
46 namespace clang {
47 
48 namespace driver {
49 
50 typedef SmallVector<InputInfo, 4> InputInfoList;
51 
52 class Command;
53 class Compilation;
54 class JobAction;
55 class ToolChain;
56 
57 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
58 enum LTOKind {
59   LTOK_None,
60   LTOK_Full,
61   LTOK_Thin,
62   LTOK_Unknown
63 };
64 
65 /// Whether headers used to construct C++20 module units should be looked
66 /// up by the path supplied on the command line, or in the user or system
67 /// search paths.
68 enum ModuleHeaderMode {
69   HeaderMode_None,
70   HeaderMode_Default,
71   HeaderMode_User,
72   HeaderMode_System
73 };
74 
75 /// Driver - Encapsulate logic for constructing compilation processes
76 /// from a set of gcc-driver-like command line arguments.
77 class Driver {
78   DiagnosticsEngine &Diags;
79 
80   IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
81 
82   enum DriverMode {
83     GCCMode,
84     GXXMode,
85     CPPMode,
86     CLMode,
87     FlangMode,
88     DXCMode
89   } Mode;
90 
91   enum SaveTempsMode {
92     SaveTempsNone,
93     SaveTempsCwd,
94     SaveTempsObj
95   } SaveTemps;
96 
97   enum BitcodeEmbedMode {
98     EmbedNone,
99     EmbedMarker,
100     EmbedBitcode
101   } BitcodeEmbed;
102 
103   enum OffloadMode {
104     OffloadHostDevice,
105     OffloadHost,
106     OffloadDevice,
107   } Offload;
108 
109   /// Header unit mode set by -fmodule-header={user,system}.
110   ModuleHeaderMode CXX20HeaderType;
111 
112   /// Set if we should process inputs and jobs with C++20 module
113   /// interpretation.
114   bool ModulesModeCXX20;
115 
116   /// LTO mode selected via -f(no-)?lto(=.*)? options.
117   LTOKind LTOMode;
118 
119   /// LTO mode selected via -f(no-offload-)?lto(=.*)? options.
120   LTOKind OffloadLTOMode;
121 
122 public:
123   enum OpenMPRuntimeKind {
124     /// An unknown OpenMP runtime. We can't generate effective OpenMP code
125     /// without knowing what runtime to target.
126     OMPRT_Unknown,
127 
128     /// The LLVM OpenMP runtime. When completed and integrated, this will become
129     /// the default for Clang.
130     OMPRT_OMP,
131 
132     /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
133     /// this runtime but can swallow the pragmas, and find and link against the
134     /// runtime library itself.
135     OMPRT_GOMP,
136 
137     /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
138     /// OpenMP runtime. We support this mode for users with existing
139     /// dependencies on this runtime library name.
140     OMPRT_IOMP5
141   };
142 
143   // Diag - Forwarding function for diagnostics.
Diag(unsigned DiagID)144   DiagnosticBuilder Diag(unsigned DiagID) const {
145     return Diags.Report(DiagID);
146   }
147 
148   // FIXME: Privatize once interface is stable.
149 public:
150   /// The name the driver was invoked as.
151   std::string Name;
152 
153   /// The path the driver executable was in, as invoked from the
154   /// command line.
155   std::string Dir;
156 
157   /// The original path to the clang executable.
158   std::string ClangExecutable;
159 
160   /// Target and driver mode components extracted from clang executable name.
161   ParsedClangName ClangNameParts;
162 
163   /// The path to the compiler resource directory.
164   std::string ResourceDir;
165 
166   /// System directory for config files.
167   std::string SystemConfigDir;
168 
169   /// User directory for config files.
170   std::string UserConfigDir;
171 
172   /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
173   /// functionality.
174   /// FIXME: This type of customization should be removed in favor of the
175   /// universal driver when it is ready.
176   typedef SmallVector<std::string, 4> prefix_list;
177   prefix_list PrefixDirs;
178 
179   /// sysroot, if present
180   std::string SysRoot;
181 
182   /// Dynamic loader prefix, if present
183   std::string DyldPrefix;
184 
185   /// Driver title to use with help.
186   std::string DriverTitle;
187 
188   /// Information about the host which can be overridden by the user.
189   std::string HostBits, HostMachine, HostSystem, HostRelease;
190 
191   /// The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled.
192   std::string CCPrintStatReportFilename;
193 
194   /// The file to log CC_PRINT_INTERNAL_STAT_FILE output to, if enabled.
195   std::string CCPrintInternalStatReportFilename;
196 
197   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
198   std::string CCPrintOptionsFilename;
199 
200   /// The file to log CC_PRINT_HEADERS output to, if enabled.
201   std::string CCPrintHeadersFilename;
202 
203   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
204   std::string CCLogDiagnosticsFilename;
205 
206   /// An input type and its arguments.
207   using InputTy = std::pair<types::ID, const llvm::opt::Arg *>;
208 
209   /// A list of inputs and their types for the given arguments.
210   using InputList = SmallVector<InputTy, 16>;
211 
212   /// Whether the driver should follow g++ like behavior.
CCCIsCXX()213   bool CCCIsCXX() const { return Mode == GXXMode; }
214 
215   /// Whether the driver is just the preprocessor.
CCCIsCPP()216   bool CCCIsCPP() const { return Mode == CPPMode; }
217 
218   /// Whether the driver should follow gcc like behavior.
CCCIsCC()219   bool CCCIsCC() const { return Mode == GCCMode; }
220 
221   /// Whether the driver should follow cl.exe like behavior.
IsCLMode()222   bool IsCLMode() const { return Mode == CLMode; }
223 
224   /// Whether the driver should invoke flang for fortran inputs.
225   /// Other modes fall back to calling gcc which in turn calls gfortran.
IsFlangMode()226   bool IsFlangMode() const { return Mode == FlangMode; }
227 
228   /// Whether the driver should follow dxc.exe like behavior.
IsDXCMode()229   bool IsDXCMode() const { return Mode == DXCMode; }
230 
231   /// Only print tool bindings, don't build any jobs.
232   LLVM_PREFERRED_TYPE(bool)
233   unsigned CCCPrintBindings : 1;
234 
235   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
236   /// CCPrintOptionsFilename or to stderr.
237   LLVM_PREFERRED_TYPE(bool)
238   unsigned CCPrintOptions : 1;
239 
240   /// The format of the header information that is emitted. If CC_PRINT_HEADERS
241   /// is set, the format is textual. Otherwise, the format is determined by the
242   /// enviroment variable CC_PRINT_HEADERS_FORMAT.
243   HeaderIncludeFormatKind CCPrintHeadersFormat = HIFMT_None;
244 
245   /// This flag determines whether clang should filter the header information
246   /// that is emitted. If enviroment variable CC_PRINT_HEADERS_FILTERING is set
247   /// to "only-direct-system", only system headers that are directly included
248   /// from non-system headers are emitted.
249   HeaderIncludeFilteringKind CCPrintHeadersFiltering = HIFIL_None;
250 
251   /// Name of the library that provides implementations of
252   /// IEEE-754 128-bit float math functions used by Fortran F128
253   /// runtime library. It should be linked as needed by the linker job.
254   std::string FlangF128MathLibrary;
255 
256   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
257   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
258   /// format.
259   LLVM_PREFERRED_TYPE(bool)
260   unsigned CCLogDiagnostics : 1;
261 
262   /// Whether the driver is generating diagnostics for debugging purposes.
263   LLVM_PREFERRED_TYPE(bool)
264   unsigned CCGenDiagnostics : 1;
265 
266   /// Set CC_PRINT_PROC_STAT mode, which causes the driver to dump
267   /// performance report to CC_PRINT_PROC_STAT_FILE or to stdout.
268   LLVM_PREFERRED_TYPE(bool)
269   unsigned CCPrintProcessStats : 1;
270 
271   /// Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal
272   /// performance report to CC_PRINT_INTERNAL_STAT_FILE or to stdout.
273   LLVM_PREFERRED_TYPE(bool)
274   unsigned CCPrintInternalStats : 1;
275 
276   /// Pointer to the ExecuteCC1Tool function, if available.
277   /// When the clangDriver lib is used through clang.exe, this provides a
278   /// shortcut for executing the -cc1 command-line directly, in the same
279   /// process.
280   using CC1ToolFunc =
281       llvm::function_ref<int(SmallVectorImpl<const char *> &ArgV)>;
282   CC1ToolFunc CC1Main = nullptr;
283 
284 private:
285   /// Raw target triple.
286   std::string TargetTriple;
287 
288   /// Name to use when invoking gcc/g++.
289   std::string CCCGenericGCCName;
290 
291   /// Paths to configuration files used.
292   std::vector<std::string> ConfigFiles;
293 
294   /// Allocator for string saver.
295   llvm::BumpPtrAllocator Alloc;
296 
297   /// Object that stores strings read from configuration file.
298   llvm::StringSaver Saver;
299 
300   /// Arguments originated from configuration file.
301   std::unique_ptr<llvm::opt::InputArgList> CfgOptions;
302 
303   /// Arguments originated from command line.
304   std::unique_ptr<llvm::opt::InputArgList> CLOptions;
305 
306   /// If this is non-null, the driver will prepend this argument before
307   /// reinvoking clang. This is useful for the llvm-driver where clang's
308   /// realpath will be to the llvm binary and not clang, so it must pass
309   /// "clang" as it's first argument.
310   const char *PrependArg;
311 
312   /// Whether to check that input files exist when constructing compilation
313   /// jobs.
314   LLVM_PREFERRED_TYPE(bool)
315   unsigned CheckInputsExist : 1;
316   /// Whether to probe for PCH files on disk, in order to upgrade
317   /// -include foo.h to -include-pch foo.h.pch.
318   LLVM_PREFERRED_TYPE(bool)
319   unsigned ProbePrecompiled : 1;
320 
321 public:
322   // getFinalPhase - Determine which compilation mode we are in and record
323   // which option we used to determine the final phase.
324   // TODO: Much of what getFinalPhase returns are not actually true compiler
325   //       modes. Fold this functionality into Types::getCompilationPhases and
326   //       handleArguments.
327   phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
328                            llvm::opt::Arg **FinalPhaseArg = nullptr) const;
329 
330 private:
331   /// Certain options suppress the 'no input files' warning.
332   LLVM_PREFERRED_TYPE(bool)
333   unsigned SuppressMissingInputWarning : 1;
334 
335   /// Cache of all the ToolChains in use by the driver.
336   ///
337   /// This maps from the string representation of a triple to a ToolChain
338   /// created targeting that triple. The driver owns all the ToolChain objects
339   /// stored in it, and will clean them up when torn down.
340   mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
341 
342   /// Cache of known offloading architectures for the ToolChain already derived.
343   /// This should only be modified when we first initialize the offloading
344   /// toolchains.
345   llvm::DenseMap<const ToolChain *, llvm::DenseSet<llvm::StringRef>> KnownArchs;
346 
347 private:
348   /// TranslateInputArgs - Create a new derived argument list from the input
349   /// arguments, after applying the standard argument translations.
350   llvm::opt::DerivedArgList *
351   TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
352 
353   // handleArguments - All code related to claiming and printing diagnostics
354   // related to arguments to the driver are done here.
355   void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args,
356                        const InputList &Inputs, ActionList &Actions) const;
357 
358   // Before executing jobs, sets up response files for commands that need them.
359   void setUpResponseFiles(Compilation &C, Command &Cmd);
360 
361   void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
362                                  SmallVectorImpl<std::string> &Names) const;
363 
364   /// Find the appropriate .crash diagonostic file for the child crash
365   /// under this driver and copy it out to a temporary destination with the
366   /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
367   /// directory for the user to look at.
368   ///
369   /// \param ReproCrashFilename The file path to copy the .crash to.
370   /// \param CrashDiagDir       The suggested directory for the user to look at
371   ///                           in case the search or copy fails.
372   ///
373   /// \returns If the .crash is found and successfully copied return true,
374   /// otherwise false and return the suggested directory in \p CrashDiagDir.
375   bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
376                               SmallString<128> &CrashDiagDir);
377 
378 public:
379 
380   /// Takes the path to a binary that's either in bin/ or lib/ and returns
381   /// the path to clang's resource directory.
382   static std::string GetResourcesPath(StringRef BinaryPath,
383                                       StringRef CustomResourceDir = "");
384 
385   Driver(StringRef ClangExecutable, StringRef TargetTriple,
386          DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler",
387          IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
388 
389   /// @name Accessors
390   /// @{
391 
392   /// Name to use when invoking gcc/g++.
getCCCGenericGCCName()393   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
394 
getConfigFiles()395   llvm::ArrayRef<std::string> getConfigFiles() const {
396     return ConfigFiles;
397   }
398 
getOpts()399   const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
400 
getDiags()401   DiagnosticsEngine &getDiags() const { return Diags; }
402 
getVFS()403   llvm::vfs::FileSystem &getVFS() const { return *VFS; }
404 
getCheckInputsExist()405   bool getCheckInputsExist() const { return CheckInputsExist; }
406 
setCheckInputsExist(bool Value)407   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
408 
getProbePrecompiled()409   bool getProbePrecompiled() const { return ProbePrecompiled; }
setProbePrecompiled(bool Value)410   void setProbePrecompiled(bool Value) { ProbePrecompiled = Value; }
411 
getPrependArg()412   const char *getPrependArg() const { return PrependArg; }
setPrependArg(const char * Value)413   void setPrependArg(const char *Value) { PrependArg = Value; }
414 
setTargetAndMode(const ParsedClangName & TM)415   void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
416 
getTitle()417   const std::string &getTitle() { return DriverTitle; }
setTitle(std::string Value)418   void setTitle(std::string Value) { DriverTitle = std::move(Value); }
419 
getTargetTriple()420   std::string getTargetTriple() const { return TargetTriple; }
421 
422   /// Get the path to the main clang executable.
getClangProgramPath()423   const char *getClangProgramPath() const {
424     return ClangExecutable.c_str();
425   }
426 
isSaveTempsEnabled()427   bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
isSaveTempsObj()428   bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
429 
embedBitcodeEnabled()430   bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
embedBitcodeInObject()431   bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
embedBitcodeMarkerOnly()432   bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
433 
offloadHostOnly()434   bool offloadHostOnly() const { return Offload == OffloadHost; }
offloadDeviceOnly()435   bool offloadDeviceOnly() const { return Offload == OffloadDevice; }
436 
setFlangF128MathLibrary(std::string name)437   void setFlangF128MathLibrary(std::string name) {
438     FlangF128MathLibrary = std::move(name);
439   }
getFlangF128MathLibrary()440   StringRef getFlangF128MathLibrary() const { return FlangF128MathLibrary; }
441 
442   /// Compute the desired OpenMP runtime from the flags provided.
443   OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
444 
445   /// @}
446   /// @name Primary Functionality
447   /// @{
448 
449   /// CreateOffloadingDeviceToolChains - create all the toolchains required to
450   /// support offloading devices given the programming models specified in the
451   /// current compilation. Also, update the host tool chain kind accordingly.
452   void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
453 
454   /// BuildCompilation - Construct a compilation object for a command
455   /// line argument vector.
456   ///
457   /// \return A compilation, or 0 if none was built for the given
458   /// argument vector. A null return value does not necessarily
459   /// indicate an error condition, the diagnostics should be queried
460   /// to determine if an error occurred.
461   Compilation *BuildCompilation(ArrayRef<const char *> Args);
462 
463   /// ParseArgStrings - Parse the given list of strings into an
464   /// ArgList.
465   llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
466                                           bool UseDriverMode,
467                                           bool &ContainsError);
468 
469   /// BuildInputs - Construct the list of inputs and their types from
470   /// the given arguments.
471   ///
472   /// \param TC - The default host tool chain.
473   /// \param Args - The input arguments.
474   /// \param Inputs - The list to store the resulting compilation
475   /// inputs onto.
476   void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
477                    InputList &Inputs) const;
478 
479   /// BuildActions - Construct the list of actions to perform for the
480   /// given arguments, which are only done for a single architecture.
481   ///
482   /// \param C - The compilation that is being built.
483   /// \param Args - The input arguments.
484   /// \param Actions - The list to store the resulting actions onto.
485   void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
486                     const InputList &Inputs, ActionList &Actions) const;
487 
488   /// BuildUniversalActions - Construct the list of actions to perform
489   /// for the given arguments, which may require a universal build.
490   ///
491   /// \param C - The compilation that is being built.
492   /// \param TC - The default host tool chain.
493   void BuildUniversalActions(Compilation &C, const ToolChain &TC,
494                              const InputList &BAInputs) const;
495 
496   /// BuildOffloadingActions - Construct the list of actions to perform for the
497   /// offloading toolchain that will be embedded in the host.
498   ///
499   /// \param C - The compilation that is being built.
500   /// \param Args - The input arguments.
501   /// \param Input - The input type and arguments
502   /// \param HostAction - The host action used in the offloading toolchain.
503   Action *BuildOffloadingActions(Compilation &C,
504                                  llvm::opt::DerivedArgList &Args,
505                                  const InputTy &Input,
506                                  Action *HostAction) const;
507 
508   /// Returns the set of bound architectures active for this offload kind.
509   /// If there are no bound architctures we return a set containing only the
510   /// empty string. The \p SuppressError option is used to suppress errors.
511   llvm::DenseSet<StringRef>
512   getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
513                   Action::OffloadKind Kind, const ToolChain *TC,
514                   bool SuppressError = false) const;
515 
516   /// Check that the file referenced by Value exists. If it doesn't,
517   /// issue a diagnostic and return false.
518   /// If TypoCorrect is true and the file does not exist, see if it looks
519   /// like a likely typo for a flag and if so print a "did you mean" blurb.
520   bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args,
521                               StringRef Value, types::ID Ty,
522                               bool TypoCorrect) const;
523 
524   /// BuildJobs - Bind actions to concrete tools and translate
525   /// arguments to form the list of jobs to run.
526   ///
527   /// \param C - The compilation that is being built.
528   void BuildJobs(Compilation &C) const;
529 
530   /// ExecuteCompilation - Execute the compilation according to the command line
531   /// arguments and return an appropriate exit code.
532   ///
533   /// This routine handles additional processing that must be done in addition
534   /// to just running the subprocesses, for example reporting errors, setting
535   /// up response files, removing temporary files, etc.
536   int ExecuteCompilation(Compilation &C,
537      SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
538 
539   /// Contains the files in the compilation diagnostic report generated by
540   /// generateCompilationDiagnostics.
541   struct CompilationDiagnosticReport {
542     llvm::SmallVector<std::string, 4> TemporaryFiles;
543   };
544 
545   /// generateCompilationDiagnostics - Generate diagnostics information
546   /// including preprocessed source file(s).
547   ///
548   void generateCompilationDiagnostics(
549       Compilation &C, const Command &FailingCommand,
550       StringRef AdditionalInformation = "",
551       CompilationDiagnosticReport *GeneratedReport = nullptr);
552 
553   enum class CommandStatus {
554     Crash = 1,
555     Error,
556     Ok,
557   };
558 
559   enum class ReproLevel {
560     Off = 0,
561     OnCrash = static_cast<int>(CommandStatus::Crash),
562     OnError = static_cast<int>(CommandStatus::Error),
563     Always = static_cast<int>(CommandStatus::Ok),
564   };
565 
566   bool maybeGenerateCompilationDiagnostics(
567       CommandStatus CS, ReproLevel Level, Compilation &C,
568       const Command &FailingCommand, StringRef AdditionalInformation = "",
569       CompilationDiagnosticReport *GeneratedReport = nullptr) {
570     if (static_cast<int>(CS) > static_cast<int>(Level))
571       return false;
572     if (CS != CommandStatus::Crash)
573       Diags.Report(diag::err_drv_force_crash)
574           << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
575     // Hack to ensure that diagnostic notes get emitted.
576     Diags.setLastDiagnosticIgnored(false);
577     generateCompilationDiagnostics(C, FailingCommand, AdditionalInformation,
578                                    GeneratedReport);
579     return true;
580   }
581 
582   /// @}
583   /// @name Helper Methods
584   /// @{
585 
586   /// PrintActions - Print the list of actions.
587   void PrintActions(const Compilation &C) const;
588 
589   /// PrintHelp - Print the help text.
590   ///
591   /// \param ShowHidden - Show hidden options.
592   void PrintHelp(bool ShowHidden) const;
593 
594   /// PrintVersion - Print the driver version.
595   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
596 
597   /// GetFilePath - Lookup \p Name in the list of file search paths.
598   ///
599   /// \param TC - The tool chain for additional information on
600   /// directories to search.
601   //
602   // FIXME: This should be in CompilationInfo.
603   std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
604 
605   /// GetProgramPath - Lookup \p Name in the list of program search paths.
606   ///
607   /// \param TC - The provided tool chain for additional information on
608   /// directories to search.
609   //
610   // FIXME: This should be in CompilationInfo.
611   std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
612 
613   /// Lookup the path to the Standard library module manifest.
614   ///
615   /// \param C - The compilation.
616   /// \param TC - The tool chain for additional information on
617   /// directories to search.
618   //
619   // FIXME: This should be in CompilationInfo.
620   std::string GetStdModuleManifestPath(const Compilation &C,
621                                        const ToolChain &TC) const;
622 
623   /// HandleAutocompletions - Handle --autocomplete by searching and printing
624   /// possible flags, descriptions, and its arguments.
625   void HandleAutocompletions(StringRef PassedFlags) const;
626 
627   /// HandleImmediateArgs - Handle any arguments which should be
628   /// treated before building actions or binding tools.
629   ///
630   /// \return Whether any compilation should be built for this
631   /// invocation. The compilation can only be modified when
632   /// this function returns false.
633   bool HandleImmediateArgs(Compilation &C);
634 
635   /// ConstructAction - Construct the appropriate action to do for
636   /// \p Phase on the \p Input, taking in to account arguments
637   /// like -fsyntax-only or --analyze.
638   Action *ConstructPhaseAction(
639       Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase,
640       Action *Input,
641       Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
642 
643   /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
644   /// return an InputInfo for the result of running \p A.  Will only construct
645   /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
646   InputInfoList BuildJobsForAction(
647       Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
648       bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
649       std::map<std::pair<const Action *, std::string>, InputInfoList>
650           &CachedResults,
651       Action::OffloadKind TargetDeviceOffloadKind) const;
652 
653   /// Returns the default name for linked images (e.g., "a.out").
654   const char *getDefaultImageName() const;
655 
656   /// Creates a temp file.
657   /// 1. If \p MultipleArch is false or \p BoundArch is empty, the temp file is
658   ///    in the temporary directory with name $Prefix-%%%%%%.$Suffix.
659   /// 2. If \p MultipleArch is true and \p BoundArch is not empty,
660   ///    2a. If \p NeedUniqueDirectory is false, the temp file is in the
661   ///        temporary directory with name $Prefix-$BoundArch-%%%%%.$Suffix.
662   ///    2b. If \p NeedUniqueDirectory is true, the temp file is in a unique
663   ///        subdiretory with random name under the temporary directory, and
664   ///        the temp file itself has name $Prefix-$BoundArch.$Suffix.
665   const char *CreateTempFile(Compilation &C, StringRef Prefix, StringRef Suffix,
666                              bool MultipleArchs = false,
667                              StringRef BoundArch = {},
668                              bool NeedUniqueDirectory = false) const;
669 
670   /// GetNamedOutputPath - Return the name to use for the output of
671   /// the action \p JA. The result is appended to the compilation's
672   /// list of temporary or result files, as appropriate.
673   ///
674   /// \param C - The compilation.
675   /// \param JA - The action of interest.
676   /// \param BaseInput - The original input file that this action was
677   /// triggered by.
678   /// \param BoundArch - The bound architecture.
679   /// \param AtTopLevel - Whether this is a "top-level" action.
680   /// \param MultipleArchs - Whether multiple -arch options were supplied.
681   /// \param NormalizedTriple - The normalized triple of the relevant target.
682   const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
683                                  const char *BaseInput, StringRef BoundArch,
684                                  bool AtTopLevel, bool MultipleArchs,
685                                  StringRef NormalizedTriple) const;
686 
687   /// GetTemporaryPath - Return the pathname of a temporary file to use
688   /// as part of compilation; the file will have the given prefix and suffix.
689   ///
690   /// GCC goes to extra lengths here to be a bit more robust.
691   std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
692 
693   /// GetTemporaryDirectory - Return the pathname of a temporary directory to
694   /// use as part of compilation; the directory will have the given prefix.
695   std::string GetTemporaryDirectory(StringRef Prefix) const;
696 
697   /// Return the pathname of the pch file in clang-cl mode.
698   std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
699 
700   /// ShouldUseClangCompiler - Should the clang compiler be used to
701   /// handle this action.
702   bool ShouldUseClangCompiler(const JobAction &JA) const;
703 
704   /// ShouldUseFlangCompiler - Should the flang compiler be used to
705   /// handle this action.
706   bool ShouldUseFlangCompiler(const JobAction &JA) const;
707 
708   /// ShouldEmitStaticLibrary - Should the linker emit a static library.
709   bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const;
710 
711   /// Returns true if the user has indicated a C++20 header unit mode.
hasHeaderMode()712   bool hasHeaderMode() const { return CXX20HeaderType != HeaderMode_None; }
713 
714   /// Get the mode for handling headers as set by fmodule-header{=}.
getModuleHeaderMode()715   ModuleHeaderMode getModuleHeaderMode() const { return CXX20HeaderType; }
716 
717   /// Returns true if we are performing any kind of LTO.
718   bool isUsingLTO(bool IsOffload = false) const {
719     return getLTOMode(IsOffload) != LTOK_None;
720   }
721 
722   /// Get the specific kind of LTO being performed.
723   LTOKind getLTOMode(bool IsOffload = false) const {
724     return IsOffload ? OffloadLTOMode : LTOMode;
725   }
726 
727 private:
728 
729   /// Tries to load options from configuration files.
730   ///
731   /// \returns true if error occurred.
732   bool loadConfigFiles();
733 
734   /// Tries to load options from default configuration files (deduced from
735   /// executable filename).
736   ///
737   /// \returns true if error occurred.
738   bool loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx);
739 
740   /// Read options from the specified file.
741   ///
742   /// \param [in] FileName File to read.
743   /// \param [in] Search and expansion options.
744   /// \returns true, if error occurred while reading.
745   bool readConfigFile(StringRef FileName, llvm::cl::ExpansionContext &ExpCtx);
746 
747   /// Set the driver mode (cl, gcc, etc) from the value of the `--driver-mode`
748   /// option.
749   void setDriverMode(StringRef DriverModeValue);
750 
751   /// Parse the \p Args list for LTO options and record the type of LTO
752   /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
753   void setLTOMode(const llvm::opt::ArgList &Args);
754 
755   /// Retrieves a ToolChain for a particular \p Target triple.
756   ///
757   /// Will cache ToolChains for the life of the driver object, and create them
758   /// on-demand.
759   const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
760                                 const llvm::Triple &Target) const;
761 
762   /// @}
763 
764   /// Retrieves a ToolChain for a particular device \p Target triple
765   ///
766   /// \param[in] HostTC is the host ToolChain paired with the device
767   ///
768   /// \param[in] TargetDeviceOffloadKind (e.g. OFK_Cuda/OFK_OpenMP/OFK_SYCL) is
769   /// an Offloading action that is optionally passed to a ToolChain (used by
770   /// CUDA, to specify if it's used in conjunction with OpenMP)
771   ///
772   /// Will cache ToolChains for the life of the driver object, and create them
773   /// on-demand.
774   const ToolChain &getOffloadingDeviceToolChain(
775       const llvm::opt::ArgList &Args, const llvm::Triple &Target,
776       const ToolChain &HostTC,
777       const Action::OffloadKind &TargetDeviceOffloadKind) const;
778 
779   /// Get bitmasks for which option flags to include and exclude based on
780   /// the driver mode.
781   llvm::opt::Visibility
782   getOptionVisibilityMask(bool UseDriverMode = true) const;
783 
784   /// Helper used in BuildJobsForAction.  Doesn't use the cache when building
785   /// jobs specifically for the given action, but will use the cache when
786   /// building jobs for the Action's inputs.
787   InputInfoList BuildJobsForActionNoCache(
788       Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
789       bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
790       std::map<std::pair<const Action *, std::string>, InputInfoList>
791           &CachedResults,
792       Action::OffloadKind TargetDeviceOffloadKind) const;
793 
794   /// Return the typical executable name for the specified driver \p Mode.
795   static const char *getExecutableForDriverMode(DriverMode Mode);
796 
797 public:
798   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
799   /// return the grouped values as integers. Numbers which are not
800   /// provided are set to 0.
801   ///
802   /// \return True if the entire string was parsed (9.2), or all
803   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
804   /// groups were parsed but extra characters remain at the end.
805   static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
806                                 unsigned &Micro, bool &HadExtra);
807 
808   /// Parse digits from a string \p Str and fulfill \p Digits with
809   /// the parsed numbers. This method assumes that the max number of
810   /// digits to look for is equal to Digits.size().
811   ///
812   /// \return True if the entire string was parsed and there are
813   /// no extra characters remaining at the end.
814   static bool GetReleaseVersion(StringRef Str,
815                                 MutableArrayRef<unsigned> Digits);
816   /// Compute the default -fmodule-cache-path.
817   /// \return True if the system provides a default cache directory.
818   static bool getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
819 };
820 
821 /// \return True if the last defined optimization level is -Ofast.
822 /// And False otherwise.
823 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
824 
825 /// \return True if the argument combination will end up generating remarks.
826 bool willEmitRemarks(const llvm::opt::ArgList &Args);
827 
828 /// Returns the driver mode option's value, i.e. `X` in `--driver-mode=X`. If \p
829 /// Args doesn't mention one explicitly, tries to deduce from `ProgName`.
830 /// Returns empty on failure.
831 /// Common values are "gcc", "g++", "cpp", "cl" and "flang". Returned value need
832 /// not be one of these.
833 llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef<const char *> Args);
834 
835 /// Checks whether the value produced by getDriverMode is for CL mode.
836 bool IsClangCL(StringRef DriverMode);
837 
838 /// Expand response files from a clang driver or cc1 invocation.
839 ///
840 /// \param Args The arguments that will be expanded.
841 /// \param ClangCLMode Whether clang is in CL mode.
842 /// \param Alloc Allocator for new arguments.
843 /// \param FS Filesystem to use when expanding files.
844 llvm::Error expandResponseFiles(SmallVectorImpl<const char *> &Args,
845                                 bool ClangCLMode, llvm::BumpPtrAllocator &Alloc,
846                                 llvm::vfs::FileSystem *FS = nullptr);
847 
848 /// Apply a space separated list of edits to the input argument lists.
849 /// See applyOneOverrideOption.
850 void applyOverrideOptions(SmallVectorImpl<const char *> &Args,
851                           const char *OverrideOpts,
852                           llvm::StringSet<> &SavedStrings,
853                           raw_ostream *OS = nullptr);
854 
855 } // end namespace driver
856 } // end namespace clang
857 
858 #endif
859