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