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;
78 enum BitcodeEmbedMode {
84 /// LTO mode selected via -f(no-)?lto(=.*)? options.
88 enum OpenMPRuntimeKind {
89 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
90 /// without knowing what runtime to target.
93 /// The LLVM OpenMP runtime. When completed and integrated, this will become
94 /// the default for Clang.
97 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
98 /// this runtime but can swallow the pragmas, and find and link against the
99 /// runtime library itself.
102 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
103 /// OpenMP runtime. We support this mode for users with existing
104 /// dependencies on this runtime library name.
108 // Diag - Forwarding function for diagnostics.
109 DiagnosticBuilder Diag(unsigned DiagID) const {
110 return Diags.Report(DiagID);
113 // FIXME: Privatize once interface is stable.
115 /// The name the driver was invoked as.
118 /// The path the driver executable was in, as invoked from the
122 /// The original path to the clang executable.
123 std::string ClangExecutable;
125 /// Target and driver mode components extracted from clang executable name.
126 ParsedClangName ClangNameParts;
128 /// The path to the installed clang directory, if any.
129 std::string InstalledDir;
131 /// The path to the compiler resource directory.
132 std::string ResourceDir;
134 /// System directory for config files.
135 std::string SystemConfigDir;
137 /// User directory for config files.
138 std::string UserConfigDir;
140 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
142 /// FIXME: This type of customization should be removed in favor of the
143 /// universal driver when it is ready.
144 typedef SmallVector<std::string, 4> prefix_list;
145 prefix_list PrefixDirs;
147 /// sysroot, if present
150 /// Dynamic loader prefix, if present
151 std::string DyldPrefix;
153 /// Driver title to use with help.
154 std::string DriverTitle;
156 /// Information about the host which can be overridden by the user.
157 std::string HostBits, HostMachine, HostSystem, HostRelease;
159 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
160 const char *CCPrintOptionsFilename;
162 /// The file to log CC_PRINT_HEADERS output to, if enabled.
163 const char *CCPrintHeadersFilename;
165 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
166 const char *CCLogDiagnosticsFilename;
168 /// A list of inputs and their types for the given arguments.
169 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
172 /// Whether the driver should follow g++ like behavior.
173 bool CCCIsCXX() const { return Mode == GXXMode; }
175 /// Whether the driver is just the preprocessor.
176 bool CCCIsCPP() const { return Mode == CPPMode; }
178 /// Whether the driver should follow gcc like behavior.
179 bool CCCIsCC() const { return Mode == GCCMode; }
181 /// Whether the driver should follow cl.exe like behavior.
182 bool IsCLMode() const { return Mode == CLMode; }
184 /// Whether the driver should invoke flang for fortran inputs.
185 /// Other modes fall back to calling gcc which in turn calls gfortran.
186 bool IsFlangMode() const { return Mode == FlangMode; }
188 /// Only print tool bindings, don't build any jobs.
189 unsigned CCCPrintBindings : 1;
191 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
192 /// CCPrintOptionsFilename or to stderr.
193 unsigned CCPrintOptions : 1;
195 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
196 /// information to CCPrintHeadersFilename or to stderr.
197 unsigned CCPrintHeaders : 1;
199 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
200 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
202 unsigned CCLogDiagnostics : 1;
204 /// Whether the driver is generating diagnostics for debugging purposes.
205 unsigned CCGenDiagnostics : 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
211 typedef int (*CC1ToolFunc)(SmallVectorImpl<const char *> &ArgV);
212 CC1ToolFunc CC1Main = nullptr;
215 /// Raw target triple.
216 std::string TargetTriple;
218 /// Name to use when invoking gcc/g++.
219 std::string CCCGenericGCCName;
221 /// Name of configuration file if used.
222 std::string ConfigFile;
224 /// Allocator for string saver.
225 llvm::BumpPtrAllocator Alloc;
227 /// Object that stores strings read from configuration file.
228 llvm::StringSaver Saver;
230 /// Arguments originated from configuration file.
231 std::unique_ptr<llvm::opt::InputArgList> CfgOptions;
233 /// Arguments originated from command line.
234 std::unique_ptr<llvm::opt::InputArgList> CLOptions;
236 /// Whether to check that input files exist when constructing compilation
238 unsigned CheckInputsExist : 1;
241 /// Force clang to emit reproducer for driver invocation. This is enabled
242 /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
243 /// or when using the -gen-reproducer driver flag.
244 unsigned GenReproducer : 1;
247 /// Certain options suppress the 'no input files' warning.
248 unsigned SuppressMissingInputWarning : 1;
250 /// Cache of all the ToolChains in use by the driver.
252 /// This maps from the string representation of a triple to a ToolChain
253 /// created targeting that triple. The driver owns all the ToolChain objects
254 /// stored in it, and will clean them up when torn down.
255 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
258 /// TranslateInputArgs - Create a new derived argument list from the input
259 /// arguments, after applying the standard argument translations.
260 llvm::opt::DerivedArgList *
261 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
263 // getFinalPhase - Determine which compilation mode we are in and record
264 // which option we used to determine the final phase.
265 // TODO: Much of what getFinalPhase returns are not actually true compiler
266 // modes. Fold this functionality into Types::getCompilationPhases and
268 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
269 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
271 // handleArguments - All code related to claiming and printing diagnostics
272 // related to arguments to the driver are done here.
273 void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args,
274 const InputList &Inputs, ActionList &Actions) const;
276 // Before executing jobs, sets up response files for commands that need them.
277 void setUpResponseFiles(Compilation &C, Command &Cmd);
279 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
280 SmallVectorImpl<std::string> &Names) const;
282 /// Find the appropriate .crash diagonostic file for the child crash
283 /// under this driver and copy it out to a temporary destination with the
284 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
285 /// directory for the user to look at.
287 /// \param ReproCrashFilename The file path to copy the .crash to.
288 /// \param CrashDiagDir The suggested directory for the user to look at
289 /// in case the search or copy fails.
291 /// \returns If the .crash is found and successfully copied return true,
292 /// otherwise false and return the suggested directory in \p CrashDiagDir.
293 bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
294 SmallString<128> &CrashDiagDir);
298 /// Takes the path to a binary that's either in bin/ or lib/ and returns
299 /// the path to clang's resource directory.
300 static std::string GetResourcesPath(StringRef BinaryPath,
301 StringRef CustomResourceDir = "");
303 Driver(StringRef ClangExecutable, StringRef TargetTriple,
304 DiagnosticsEngine &Diags,
305 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
310 /// Name to use when invoking gcc/g++.
311 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
313 const std::string &getConfigFile() const { return ConfigFile; }
315 const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
317 const DiagnosticsEngine &getDiags() const { return Diags; }
319 llvm::vfs::FileSystem &getVFS() const { return *VFS; }
321 bool getCheckInputsExist() const { return CheckInputsExist; }
323 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
325 void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
327 const std::string &getTitle() { return DriverTitle; }
328 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
330 std::string getTargetTriple() const { return TargetTriple; }
332 /// Get the path to the main clang executable.
333 const char *getClangProgramPath() const {
334 return ClangExecutable.c_str();
337 /// Get the path to where the clang executable was installed.
338 const char *getInstalledDir() const {
339 if (!InstalledDir.empty())
340 return InstalledDir.c_str();
343 void setInstalledDir(StringRef Value) {
344 InstalledDir = Value;
347 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
348 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
350 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
351 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
352 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
354 /// Compute the desired OpenMP runtime from the flags provided.
355 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
358 /// @name Primary Functionality
361 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
362 /// support offloading devices given the programming models specified in the
363 /// current compilation. Also, update the host tool chain kind accordingly.
364 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
366 /// BuildCompilation - Construct a compilation object for a command
367 /// line argument vector.
369 /// \return A compilation, or 0 if none was built for the given
370 /// argument vector. A null return value does not necessarily
371 /// indicate an error condition, the diagnostics should be queried
372 /// to determine if an error occurred.
373 Compilation *BuildCompilation(ArrayRef<const char *> Args);
375 /// @name Driver Steps
378 /// ParseDriverMode - Look for and handle the driver mode option in Args.
379 void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
381 /// ParseArgStrings - Parse the given list of strings into an
383 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
385 bool &ContainsError);
387 /// BuildInputs - Construct the list of inputs and their types from
388 /// the given arguments.
390 /// \param TC - The default host tool chain.
391 /// \param Args - The input arguments.
392 /// \param Inputs - The list to store the resulting compilation
394 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
395 InputList &Inputs) const;
397 /// BuildActions - Construct the list of actions to perform for the
398 /// given arguments, which are only done for a single architecture.
400 /// \param C - The compilation that is being built.
401 /// \param Args - The input arguments.
402 /// \param Actions - The list to store the resulting actions onto.
403 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
404 const InputList &Inputs, ActionList &Actions) const;
406 /// BuildUniversalActions - Construct the list of actions to perform
407 /// for the given arguments, which may require a universal build.
409 /// \param C - The compilation that is being built.
410 /// \param TC - The default host tool chain.
411 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
412 const InputList &BAInputs) const;
414 /// Check that the file referenced by Value exists. If it doesn't,
415 /// issue a diagnostic and return false.
416 /// If TypoCorrect is true and the file does not exist, see if it looks
417 /// like a likely typo for a flag and if so print a "did you mean" blurb.
418 bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args,
419 StringRef Value, types::ID Ty,
420 bool TypoCorrect) const;
422 /// BuildJobs - Bind actions to concrete tools and translate
423 /// arguments to form the list of jobs to run.
425 /// \param C - The compilation that is being built.
426 void BuildJobs(Compilation &C) const;
428 /// ExecuteCompilation - Execute the compilation according to the command line
429 /// arguments and return an appropriate exit code.
431 /// This routine handles additional processing that must be done in addition
432 /// to just running the subprocesses, for example reporting errors, setting
433 /// up response files, removing temporary files, etc.
434 int ExecuteCompilation(Compilation &C,
435 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
437 /// Contains the files in the compilation diagnostic report generated by
438 /// generateCompilationDiagnostics.
439 struct CompilationDiagnosticReport {
440 llvm::SmallVector<std::string, 4> TemporaryFiles;
443 /// generateCompilationDiagnostics - Generate diagnostics information
444 /// including preprocessed source file(s).
446 void generateCompilationDiagnostics(
447 Compilation &C, const Command &FailingCommand,
448 StringRef AdditionalInformation = "",
449 CompilationDiagnosticReport *GeneratedReport = nullptr);
452 /// @name Helper Methods
455 /// PrintActions - Print the list of actions.
456 void PrintActions(const Compilation &C) const;
458 /// PrintHelp - Print the help text.
460 /// \param ShowHidden - Show hidden options.
461 void PrintHelp(bool ShowHidden) const;
463 /// PrintVersion - Print the driver version.
464 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
466 /// GetFilePath - Lookup \p Name in the list of file search paths.
468 /// \param TC - The tool chain for additional information on
469 /// directories to search.
471 // FIXME: This should be in CompilationInfo.
472 std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
474 /// GetProgramPath - Lookup \p Name in the list of program search paths.
476 /// \param TC - The provided tool chain for additional information on
477 /// directories to search.
479 // FIXME: This should be in CompilationInfo.
480 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
482 /// HandleAutocompletions - Handle --autocomplete by searching and printing
483 /// possible flags, descriptions, and its arguments.
484 void HandleAutocompletions(StringRef PassedFlags) const;
486 /// HandleImmediateArgs - Handle any arguments which should be
487 /// treated before building actions or binding tools.
489 /// \return Whether any compilation should be built for this
491 bool HandleImmediateArgs(const Compilation &C);
493 /// ConstructAction - Construct the appropriate action to do for
494 /// \p Phase on the \p Input, taking in to account arguments
495 /// like -fsyntax-only or --analyze.
496 Action *ConstructPhaseAction(
497 Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase,
499 Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
501 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
502 /// return an InputInfo for the result of running \p A. Will only construct
503 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
505 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
506 StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
507 const char *LinkingOutput,
508 std::map<std::pair<const Action *, std::string>, InputInfo>
510 Action::OffloadKind TargetDeviceOffloadKind) const;
512 /// Returns the default name for linked images (e.g., "a.out").
513 const char *getDefaultImageName() const;
515 /// GetNamedOutputPath - Return the name to use for the output of
516 /// the action \p JA. The result is appended to the compilation's
517 /// list of temporary or result files, as appropriate.
519 /// \param C - The compilation.
520 /// \param JA - The action of interest.
521 /// \param BaseInput - The original input file that this action was
523 /// \param BoundArch - The bound architecture.
524 /// \param AtTopLevel - Whether this is a "top-level" action.
525 /// \param MultipleArchs - Whether multiple -arch options were supplied.
526 /// \param NormalizedTriple - The normalized triple of the relevant target.
527 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
528 const char *BaseInput, StringRef BoundArch,
529 bool AtTopLevel, bool MultipleArchs,
530 StringRef NormalizedTriple) const;
532 /// GetTemporaryPath - Return the pathname of a temporary file to use
533 /// as part of compilation; the file will have the given prefix and suffix.
535 /// GCC goes to extra lengths here to be a bit more robust.
536 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
538 /// GetTemporaryDirectory - Return the pathname of a temporary directory to
539 /// use as part of compilation; the directory will have the given prefix.
540 std::string GetTemporaryDirectory(StringRef Prefix) const;
542 /// Return the pathname of the pch file in clang-cl mode.
543 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
545 /// ShouldUseClangCompiler - Should the clang compiler be used to
546 /// handle this action.
547 bool ShouldUseClangCompiler(const JobAction &JA) const;
549 /// ShouldUseFlangCompiler - Should the flang compiler be used to
550 /// handle this action.
551 bool ShouldUseFlangCompiler(const JobAction &JA) const;
553 /// Returns true if we are performing any kind of LTO.
554 bool isUsingLTO() const { return LTOMode != LTOK_None; }
556 /// Get the specific kind of LTO being performed.
557 LTOKind getLTOMode() const { return LTOMode; }
561 /// Tries to load options from configuration file.
563 /// \returns true if error occurred.
564 bool loadConfigFile();
566 /// Read options from the specified file.
568 /// \param [in] FileName File to read.
569 /// \returns true, if error occurred while reading.
570 bool readConfigFile(StringRef FileName);
572 /// Set the driver mode (cl, gcc, etc) from an option string of the form
573 /// --driver-mode=<mode>.
574 void setDriverModeFromOption(StringRef Opt);
576 /// Parse the \p Args list for LTO options and record the type of LTO
577 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
578 void setLTOMode(const llvm::opt::ArgList &Args);
580 /// Retrieves a ToolChain for a particular \p Target triple.
582 /// Will cache ToolChains for the life of the driver object, and create them
584 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
585 const llvm::Triple &Target) const;
589 /// Get bitmasks for which option flags to include and exclude based on
591 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const;
593 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
594 /// jobs specifically for the given action, but will use the cache when
595 /// building jobs for the Action's inputs.
596 InputInfo BuildJobsForActionNoCache(
597 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
598 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
599 std::map<std::pair<const Action *, std::string>, InputInfo>
601 Action::OffloadKind TargetDeviceOffloadKind) const;
604 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
605 /// return the grouped values as integers. Numbers which are not
606 /// provided are set to 0.
608 /// \return True if the entire string was parsed (9.2), or all
609 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
610 /// groups were parsed but extra characters remain at the end.
611 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
612 unsigned &Micro, bool &HadExtra);
614 /// Parse digits from a string \p Str and fulfill \p Digits with
615 /// the parsed numbers. This method assumes that the max number of
616 /// digits to look for is equal to Digits.size().
618 /// \return True if the entire string was parsed and there are
619 /// no extra characters remaining at the end.
620 static bool GetReleaseVersion(StringRef Str,
621 MutableArrayRef<unsigned> Digits);
622 /// Compute the default -fmodule-cache-path.
623 static void getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
626 /// \return True if the last defined optimization level is -Ofast.
627 /// And False otherwise.
628 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
630 /// \return True if the argument combination will end up generating remarks.
631 bool willEmitRemarks(const llvm::opt::ArgList &Args);
633 } // end namespace driver
634 } // end namespace clang