Driver.h 30 KB

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