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