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