1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_CLANG_DRIVER_DRIVER_H
10 #define LLVM_CLANG_DRIVER_DRIVER_H
12 #include "clang/Basic/Diagnostic.h"
13 #include "clang/Basic/LLVM.h"
14 #include "clang/Driver/Action.h"
15 #include "clang/Driver/Options.h"
16 #include "clang/Driver/Phases.h"
17 #include "clang/Driver/ToolChain.h"
18 #include "clang/Driver/Types.h"
19 #include "clang/Driver/Util.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Support/StringSaver.h"
49 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
57 /// Driver - Encapsulate logic for constructing compilation processes
58 /// from a set of gcc-driver-like command line arguments.
60 DiagnosticsEngine &Diags;
62 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
77 enum BitcodeEmbedMode {
83 /// LTO mode selected via -f(no-)?lto(=.*)? options.
87 enum OpenMPRuntimeKind {
88 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
89 /// without knowing what runtime to target.
92 /// The LLVM OpenMP runtime. When completed and integrated, this will become
93 /// the default for Clang.
96 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
97 /// this runtime but can swallow the pragmas, and find and link against the
98 /// runtime library itself.
101 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
102 /// OpenMP runtime. We support this mode for users with existing
103 /// dependencies on this runtime library name.
107 // Diag - Forwarding function for diagnostics.
108 DiagnosticBuilder Diag(unsigned DiagID) const {
109 return Diags.Report(DiagID);
112 // FIXME: Privatize once interface is stable.
114 /// The name the driver was invoked as.
117 /// The path the driver executable was in, as invoked from the
121 /// The original path to the clang executable.
122 std::string ClangExecutable;
124 /// Target and driver mode components extracted from clang executable name.
125 ParsedClangName ClangNameParts;
127 /// The path to the installed clang directory, if any.
128 std::string InstalledDir;
130 /// The path to the compiler resource directory.
131 std::string ResourceDir;
133 /// System directory for config files.
134 std::string SystemConfigDir;
136 /// User directory for config files.
137 std::string UserConfigDir;
139 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
141 /// FIXME: This type of customization should be removed in favor of the
142 /// universal driver when it is ready.
143 typedef SmallVector<std::string, 4> prefix_list;
144 prefix_list PrefixDirs;
146 /// sysroot, if present
149 /// Dynamic loader prefix, if present
150 std::string DyldPrefix;
152 /// Driver title to use with help.
153 std::string DriverTitle;
155 /// Information about the host which can be overridden by the user.
156 std::string HostBits, HostMachine, HostSystem, HostRelease;
158 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
159 const char *CCPrintOptionsFilename;
161 /// The file to log CC_PRINT_HEADERS output to, if enabled.
162 const char *CCPrintHeadersFilename;
164 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
165 const char *CCLogDiagnosticsFilename;
167 /// A list of inputs and their types for the given arguments.
168 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
171 /// Whether the driver should follow g++ like behavior.
172 bool CCCIsCXX() const { return Mode == GXXMode; }
174 /// Whether the driver is just the preprocessor.
175 bool CCCIsCPP() const { return Mode == CPPMode; }
177 /// Whether the driver should follow gcc like behavior.
178 bool CCCIsCC() const { return Mode == GCCMode; }
180 /// Whether the driver should follow cl.exe like behavior.
181 bool IsCLMode() const { return Mode == CLMode; }
183 /// Only print tool bindings, don't build any jobs.
184 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;
190 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
191 /// information to CCPrintHeadersFilename or to stderr.
192 unsigned CCPrintHeaders : 1;
194 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
195 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
197 unsigned CCLogDiagnostics : 1;
199 /// Whether the driver is generating diagnostics for debugging purposes.
200 unsigned CCGenDiagnostics : 1;
203 /// Raw target triple.
204 std::string TargetTriple;
206 /// Name to use when invoking gcc/g++.
207 std::string CCCGenericGCCName;
209 /// Name of configuration file if used.
210 std::string ConfigFile;
212 /// Allocator for string saver.
213 llvm::BumpPtrAllocator Alloc;
215 /// Object that stores strings read from configuration file.
216 llvm::StringSaver Saver;
218 /// Arguments originated from configuration file.
219 std::unique_ptr<llvm::opt::InputArgList> CfgOptions;
221 /// Arguments originated from command line.
222 std::unique_ptr<llvm::opt::InputArgList> CLOptions;
224 /// Whether to check that input files exist when constructing compilation
226 unsigned CheckInputsExist : 1;
229 /// Force clang to emit reproducer for driver invocation. This is enabled
230 /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
231 /// or when using the -gen-reproducer driver flag.
232 unsigned GenReproducer : 1;
235 /// Certain options suppress the 'no input files' warning.
236 unsigned SuppressMissingInputWarning : 1;
238 /// Cache of all the ToolChains in use by the driver.
240 /// This maps from the string representation of a triple to a ToolChain
241 /// created targeting that triple. The driver owns all the ToolChain objects
242 /// stored in it, and will clean them up when torn down.
243 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
246 /// TranslateInputArgs - Create a new derived argument list from the input
247 /// arguments, after applying the standard argument translations.
248 llvm::opt::DerivedArgList *
249 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
251 // getFinalPhase - Determine which compilation mode we are in and record
252 // which option we used to determine the final phase.
253 // TODO: Much of what getFinalPhase returns are not actually true compiler
254 // modes. Fold this functionality into Types::getCompilationPhases and
256 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
257 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
259 // handleArguments - All code related to claiming and printing diagnostics
260 // related to arguments to the driver are done here.
261 void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args,
262 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);
267 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
268 SmallVectorImpl<std::string> &Names) const;
270 /// Find the appropriate .crash diagonostic file for the child crash
271 /// under this driver and copy it out to a temporary destination with the
272 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
273 /// directory for the user to look at.
275 /// \param ReproCrashFilename The file path to copy the .crash to.
276 /// \param CrashDiagDir The suggested directory for the user to look at
277 /// in case the search or copy fails.
279 /// \returns If the .crash is found and successfully copied return true,
280 /// otherwise false and return the suggested directory in \p CrashDiagDir.
281 bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
282 SmallString<128> &CrashDiagDir);
286 /// Takes the path to a binary that's either in bin/ or lib/ and returns
287 /// the path to clang's resource directory.
288 static std::string GetResourcesPath(StringRef BinaryPath,
289 StringRef CustomResourceDir = "");
291 Driver(StringRef ClangExecutable, StringRef TargetTriple,
292 DiagnosticsEngine &Diags,
293 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
298 /// Name to use when invoking gcc/g++.
299 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
301 const std::string &getConfigFile() const { return ConfigFile; }
303 const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
305 const DiagnosticsEngine &getDiags() const { return Diags; }
307 llvm::vfs::FileSystem &getVFS() const { return *VFS; }
309 bool getCheckInputsExist() const { return CheckInputsExist; }
311 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
313 void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
315 const std::string &getTitle() { return DriverTitle; }
316 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
318 std::string getTargetTriple() const { return TargetTriple; }
320 /// Get the path to the main clang executable.
321 const char *getClangProgramPath() const {
322 return ClangExecutable.c_str();
325 /// Get the path to where the clang executable was installed.
326 const char *getInstalledDir() const {
327 if (!InstalledDir.empty())
328 return InstalledDir.c_str();
331 void setInstalledDir(StringRef Value) {
332 InstalledDir = Value;
335 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
336 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
338 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
339 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
340 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
342 /// Compute the desired OpenMP runtime from the flags provided.
343 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
346 /// @name Primary Functionality
349 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
350 /// support offloading devices given the programming models specified in the
351 /// current compilation. Also, update the host tool chain kind accordingly.
352 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
354 /// BuildCompilation - Construct a compilation object for a command
355 /// line argument vector.
357 /// \return A compilation, or 0 if none was built for the given
358 /// argument vector. A null return value does not necessarily
359 /// indicate an error condition, the diagnostics should be queried
360 /// to determine if an error occurred.
361 Compilation *BuildCompilation(ArrayRef<const char *> Args);
363 /// @name Driver Steps
366 /// ParseDriverMode - Look for and handle the driver mode option in Args.
367 void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
369 /// ParseArgStrings - Parse the given list of strings into an
371 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
373 bool &ContainsError);
375 /// BuildInputs - Construct the list of inputs and their types from
376 /// the given arguments.
378 /// \param TC - The default host tool chain.
379 /// \param Args - The input arguments.
380 /// \param Inputs - The list to store the resulting compilation
382 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
383 InputList &Inputs) const;
385 /// BuildActions - Construct the list of actions to perform for the
386 /// given arguments, which are only done for a single architecture.
388 /// \param C - The compilation that is being built.
389 /// \param Args - The input arguments.
390 /// \param Actions - The list to store the resulting actions onto.
391 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
392 const InputList &Inputs, ActionList &Actions) const;
394 /// BuildUniversalActions - Construct the list of actions to perform
395 /// for the given arguments, which may require a universal build.
397 /// \param C - The compilation that is being built.
398 /// \param TC - The default host tool chain.
399 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
400 const InputList &BAInputs) const;
402 /// Check that the file referenced by Value exists. If it doesn't,
403 /// issue a diagnostic and return false.
404 /// If TypoCorrect is true and the file does not exist, see if it looks
405 /// like a likely typo for a flag and if so print a "did you mean" blurb.
406 bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args,
407 StringRef Value, types::ID Ty,
408 bool TypoCorrect) const;
410 /// BuildJobs - Bind actions to concrete tools and translate
411 /// arguments to form the list of jobs to run.
413 /// \param C - The compilation that is being built.
414 void BuildJobs(Compilation &C) const;
416 /// ExecuteCompilation - Execute the compilation according to the command line
417 /// arguments and return an appropriate exit code.
419 /// This routine handles additional processing that must be done in addition
420 /// to just running the subprocesses, for example reporting errors, setting
421 /// up response files, removing temporary files, etc.
422 int ExecuteCompilation(Compilation &C,
423 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
425 /// Contains the files in the compilation diagnostic report generated by
426 /// generateCompilationDiagnostics.
427 struct CompilationDiagnosticReport {
428 llvm::SmallVector<std::string, 4> TemporaryFiles;
431 /// generateCompilationDiagnostics - Generate diagnostics information
432 /// including preprocessed source file(s).
434 void generateCompilationDiagnostics(
435 Compilation &C, const Command &FailingCommand,
436 StringRef AdditionalInformation = "",
437 CompilationDiagnosticReport *GeneratedReport = nullptr);
440 /// @name Helper Methods
443 /// PrintActions - Print the list of actions.
444 void PrintActions(const Compilation &C) const;
446 /// PrintHelp - Print the help text.
448 /// \param ShowHidden - Show hidden options.
449 void PrintHelp(bool ShowHidden) const;
451 /// PrintVersion - Print the driver version.
452 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
454 /// GetFilePath - Lookup \p Name in the list of file search paths.
456 /// \param TC - The tool chain for additional information on
457 /// directories to search.
459 // FIXME: This should be in CompilationInfo.
460 std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
462 /// GetProgramPath - Lookup \p Name in the list of program search paths.
464 /// \param TC - The provided tool chain for additional information on
465 /// directories to search.
467 // FIXME: This should be in CompilationInfo.
468 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
470 /// HandleAutocompletions - Handle --autocomplete by searching and printing
471 /// possible flags, descriptions, and its arguments.
472 void HandleAutocompletions(StringRef PassedFlags) const;
474 /// HandleImmediateArgs - Handle any arguments which should be
475 /// treated before building actions or binding tools.
477 /// \return Whether any compilation should be built for this
479 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,
487 Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
489 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
490 /// return an InputInfo for the result of running \p A. Will only construct
491 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
493 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
494 StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
495 const char *LinkingOutput,
496 std::map<std::pair<const Action *, std::string>, InputInfo>
498 Action::OffloadKind TargetDeviceOffloadKind) const;
500 /// Returns the default name for linked images (e.g., "a.out").
501 const char *getDefaultImageName() 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.
507 /// \param C - The compilation.
508 /// \param JA - The action of interest.
509 /// \param BaseInput - The original input file that this action was
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;
520 /// GetTemporaryPath - Return the pathname of a temporary file to use
521 /// as part of compilation; the file will have the given prefix and suffix.
523 /// GCC goes to extra lengths here to be a bit more robust.
524 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
526 /// GetTemporaryDirectory - Return the pathname of a temporary directory to
527 /// use as part of compilation; the directory will have the given prefix.
528 std::string GetTemporaryDirectory(StringRef Prefix) const;
530 /// Return the pathname of the pch file in clang-cl mode.
531 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
533 /// ShouldUseClangCompiler - Should the clang compiler be used to
534 /// handle this action.
535 bool ShouldUseClangCompiler(const JobAction &JA) const;
537 /// Returns true if we are performing any kind of LTO.
538 bool isUsingLTO() const { return LTOMode != LTOK_None; }
540 /// Get the specific kind of LTO being performed.
541 LTOKind getLTOMode() const { return LTOMode; }
545 /// Tries to load options from configuration file.
547 /// \returns true if error occurred.
548 bool loadConfigFile();
550 /// Read options from the specified file.
552 /// \param [in] FileName File to read.
553 /// \returns true, if error occurred while reading.
554 bool readConfigFile(StringRef FileName);
556 /// Set the driver mode (cl, gcc, etc) from an option string of the form
557 /// --driver-mode=<mode>.
558 void setDriverModeFromOption(StringRef Opt);
560 /// Parse the \p Args list for LTO options and record the type of LTO
561 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
562 void setLTOMode(const llvm::opt::ArgList &Args);
564 /// Retrieves a ToolChain for a particular \p Target triple.
566 /// Will cache ToolChains for the life of the driver object, and create them
568 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
569 const llvm::Triple &Target) const;
573 /// Get bitmasks for which option flags to include and exclude based on
575 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const;
577 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
578 /// jobs specifically for the given action, but will use the cache when
579 /// building jobs for the Action's inputs.
580 InputInfo BuildJobsForActionNoCache(
581 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
582 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
583 std::map<std::pair<const Action *, std::string>, InputInfo>
585 Action::OffloadKind TargetDeviceOffloadKind) const;
588 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
589 /// return the grouped values as integers. Numbers which are not
590 /// provided are set to 0.
592 /// \return True if the entire string was parsed (9.2), or all
593 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
594 /// groups were parsed but extra characters remain at the end.
595 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
596 unsigned &Micro, bool &HadExtra);
598 /// Parse digits from a string \p Str and fulfill \p Digits with
599 /// the parsed numbers. This method assumes that the max number of
600 /// digits to look for is equal to Digits.size().
602 /// \return True if the entire string was parsed and there are
603 /// no extra characters remaining at the end.
604 static bool GetReleaseVersion(StringRef Str,
605 MutableArrayRef<unsigned> Digits);
606 /// Compute the default -fmodule-cache-path.
607 static void getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
610 /// \return True if the last defined optimization level is -Ofast.
611 /// And False otherwise.
612 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
614 } // end namespace driver
615 } // end namespace clang