1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_CLANG_DRIVER_DRIVER_H
11 #define LLVM_CLANG_DRIVER_DRIVER_H
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/Phases.h"
17 #include "clang/Driver/Types.h"
18 #include "clang/Driver/Util.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
54 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
62 /// Driver - Encapsulate logic for constructing compilation processes
63 /// from a set of gcc-driver-like command line arguments.
65 llvm::opt::OptTable *Opts;
67 DiagnosticsEngine &Diags;
69 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
84 enum BitcodeEmbedMode {
90 /// LTO mode selected via -f(no-)?lto(=.*)? options.
94 enum OpenMPRuntimeKind {
95 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
96 /// without knowing what runtime to target.
99 /// The LLVM OpenMP runtime. When completed and integrated, this will become
100 /// the default for Clang.
103 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
104 /// this runtime but can swallow the pragmas, and find and link against the
105 /// runtime library itself.
108 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
109 /// OpenMP runtime. We support this mode for users with existing
110 /// dependencies on this runtime library name.
114 // Diag - Forwarding function for diagnostics.
115 DiagnosticBuilder Diag(unsigned DiagID) const {
116 return Diags.Report(DiagID);
119 // FIXME: Privatize once interface is stable.
121 /// The name the driver was invoked as.
124 /// The path the driver executable was in, as invoked from the
128 /// The original path to the clang executable.
129 std::string ClangExecutable;
131 /// The path to the installed clang directory, if any.
132 std::string InstalledDir;
134 /// The path to the compiler resource directory.
135 std::string ResourceDir;
137 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
139 /// FIXME: This type of customization should be removed in favor of the
140 /// universal driver when it is ready.
141 typedef SmallVector<std::string, 4> prefix_list;
142 prefix_list PrefixDirs;
144 /// sysroot, if present
147 /// Dynamic loader prefix, if present
148 std::string DyldPrefix;
150 /// If the standard library is used
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 /// Only print tool bindings, don't build any jobs.
185 unsigned CCCPrintBindings : 1;
187 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
188 /// CCPrintOptionsFilename or to stderr.
189 unsigned CCPrintOptions : 1;
191 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
192 /// information to CCPrintHeadersFilename or to stderr.
193 unsigned CCPrintHeaders : 1;
195 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
196 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
198 unsigned CCLogDiagnostics : 1;
200 /// Whether the driver is generating diagnostics for debugging purposes.
201 unsigned CCGenDiagnostics : 1;
204 /// Default target triple.
205 std::string DefaultTargetTriple;
207 /// Name to use when invoking gcc/g++.
208 std::string CCCGenericGCCName;
210 /// Whether to check that input files exist when constructing compilation
212 unsigned CheckInputsExist : 1;
215 /// Use lazy precompiled headers for PCH support.
216 unsigned CCCUsePCH : 1;
219 /// Certain options suppress the 'no input files' warning.
220 unsigned SuppressMissingInputWarning : 1;
222 std::list<std::string> TempFiles;
223 std::list<std::string> ResultFiles;
225 /// \brief Cache of all the ToolChains in use by the driver.
227 /// This maps from the string representation of a triple to a ToolChain
228 /// created targeting that triple. The driver owns all the ToolChain objects
229 /// stored in it, and will clean them up when torn down.
230 mutable llvm::StringMap<ToolChain *> ToolChains;
233 /// TranslateInputArgs - Create a new derived argument list from the input
234 /// arguments, after applying the standard argument translations.
235 llvm::opt::DerivedArgList *
236 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
238 // getFinalPhase - Determine which compilation mode we are in and record
239 // which option we used to determine the final phase.
240 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
241 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
243 // Before executing jobs, sets up response files for commands that need them.
244 void setUpResponseFiles(Compilation &C, Command &Cmd);
246 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
247 SmallVectorImpl<std::string> &Names) const;
249 /// \brief Find the appropriate .crash diagonostic file for the child crash
250 /// under this driver and copy it out to a temporary destination with the
251 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
252 /// directory for the user to look at.
254 /// \param ReproCrashFilename The file path to copy the .crash to.
255 /// \param CrashDiagDir The suggested directory for the user to look at
256 /// in case the search or copy fails.
258 /// \returns If the .crash is found and successfully copied return true,
259 /// otherwise false and return the suggested directory in \p CrashDiagDir.
260 bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
261 SmallString<128> &CrashDiagDir);
264 Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
265 DiagnosticsEngine &Diags,
266 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
272 /// Name to use when invoking gcc/g++.
273 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
275 const llvm::opt::OptTable &getOpts() const { return *Opts; }
277 const DiagnosticsEngine &getDiags() const { return Diags; }
279 vfs::FileSystem &getVFS() const { return *VFS; }
281 bool getCheckInputsExist() const { return CheckInputsExist; }
283 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
285 const std::string &getTitle() { return DriverTitle; }
286 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
288 /// \brief Get the path to the main clang executable.
289 const char *getClangProgramPath() const {
290 return ClangExecutable.c_str();
293 /// \brief Get the path to where the clang executable was installed.
294 const char *getInstalledDir() const {
295 if (!InstalledDir.empty())
296 return InstalledDir.c_str();
299 void setInstalledDir(StringRef Value) {
300 InstalledDir = Value;
303 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
304 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
306 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
307 bool embedBitcodeInObject() const {
308 // LTO has no object file output so ignore embed bitcode option in LTO.
309 return (BitcodeEmbed == EmbedBitcode) && !isUsingLTO();
311 bool embedBitcodeMarkerOnly() const {
312 return (BitcodeEmbed == EmbedMarker) && !isUsingLTO();
315 /// Compute the desired OpenMP runtime from the flags provided.
316 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
319 /// @name Primary Functionality
322 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
323 /// support offloading devices given the programming models specified in the
324 /// current compilation. Also, update the host tool chain kind accordingly.
325 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
327 /// BuildCompilation - Construct a compilation object for a command
328 /// line argument vector.
330 /// \return A compilation, or 0 if none was built for the given
331 /// argument vector. A null return value does not necessarily
332 /// indicate an error condition, the diagnostics should be queried
333 /// to determine if an error occurred.
334 Compilation *BuildCompilation(ArrayRef<const char *> Args);
336 /// @name Driver Steps
339 /// ParseDriverMode - Look for and handle the driver mode option in Args.
340 void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
342 /// ParseArgStrings - Parse the given list of strings into an
344 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args);
346 /// BuildInputs - Construct the list of inputs and their types from
347 /// the given arguments.
349 /// \param TC - The default host tool chain.
350 /// \param Args - The input arguments.
351 /// \param Inputs - The list to store the resulting compilation
353 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
354 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.
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;
365 /// BuildUniversalActions - Construct the list of actions to perform
366 /// for the given arguments, which may require a universal build.
368 /// \param C - The compilation that is being built.
369 /// \param TC - The default host tool chain.
370 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
371 const InputList &BAInputs) const;
373 /// BuildJobs - Bind actions to concrete tools and translate
374 /// arguments to form the list of jobs to run.
376 /// \param C - The compilation that is being built.
377 void BuildJobs(Compilation &C) const;
379 /// ExecuteCompilation - Execute the compilation according to the command line
380 /// arguments and return an appropriate exit code.
382 /// This routine handles additional processing that must be done in addition
383 /// to just running the subprocesses, for example reporting errors, setting
384 /// up response files, removing temporary files, etc.
385 int ExecuteCompilation(Compilation &C,
386 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
388 /// generateCompilationDiagnostics - Generate diagnostics information
389 /// including preprocessed source file(s).
391 void generateCompilationDiagnostics(Compilation &C,
392 const Command &FailingCommand);
395 /// @name Helper Methods
398 /// PrintActions - Print the list of actions.
399 void PrintActions(const Compilation &C) const;
401 /// PrintHelp - Print the help text.
403 /// \param ShowHidden - Show hidden options.
404 void PrintHelp(bool ShowHidden) const;
406 /// PrintVersion - Print the driver version.
407 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
409 /// GetFilePath - Lookup \p Name in the list of file search paths.
411 /// \param TC - The tool chain for additional information on
412 /// directories to search.
414 // FIXME: This should be in CompilationInfo.
415 std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
417 /// GetProgramPath - Lookup \p Name in the list of program search paths.
419 /// \param TC - The provided tool chain for additional information on
420 /// directories to search.
422 // FIXME: This should be in CompilationInfo.
423 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
425 /// HandleImmediateArgs - Handle any arguments which should be
426 /// treated before building actions or binding tools.
428 /// \return Whether any compilation should be built for this
430 bool HandleImmediateArgs(const Compilation &C);
432 /// ConstructAction - Construct the appropriate action to do for
433 /// \p Phase on the \p Input, taking in to account arguments
434 /// like -fsyntax-only or --analyze.
435 Action *ConstructPhaseAction(Compilation &C, const llvm::opt::ArgList &Args,
436 phases::ID Phase, Action *Input) const;
438 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
439 /// return an InputInfo for the result of running \p A. Will only construct
440 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
442 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
443 StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
444 const char *LinkingOutput,
445 std::map<std::pair<const Action *, std::string>, InputInfo>
447 Action::OffloadKind TargetDeviceOffloadKind) const;
449 /// Returns the default name for linked images (e.g., "a.out").
450 const char *getDefaultImageName() const;
452 /// GetNamedOutputPath - Return the name to use for the output of
453 /// the action \p JA. The result is appended to the compilation's
454 /// list of temporary or result files, as appropriate.
456 /// \param C - The compilation.
457 /// \param JA - The action of interest.
458 /// \param BaseInput - The original input file that this action was
460 /// \param BoundArch - The bound architecture.
461 /// \param AtTopLevel - Whether this is a "top-level" action.
462 /// \param MultipleArchs - Whether multiple -arch options were supplied.
463 /// \param NormalizedTriple - The normalized triple of the relevant target.
464 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
465 const char *BaseInput, StringRef BoundArch,
466 bool AtTopLevel, bool MultipleArchs,
467 StringRef NormalizedTriple) const;
469 /// GetTemporaryPath - Return the pathname of a temporary file to use
470 /// as part of compilation; the file will have the given prefix and suffix.
472 /// GCC goes to extra lengths here to be a bit more robust.
473 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
475 /// Return the pathname of the pch file in clang-cl mode.
476 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
478 /// ShouldUseClangCompiler - Should the clang compiler be used to
479 /// handle this action.
480 bool ShouldUseClangCompiler(const JobAction &JA) const;
482 /// Returns true if we are performing any kind of LTO.
483 bool isUsingLTO() const { return LTOMode != LTOK_None; }
485 /// Get the specific kind of LTO being performed.
486 LTOKind getLTOMode() const { return LTOMode; }
489 /// Set the driver mode (cl, gcc, etc) from an option string of the form
490 /// --driver-mode=<mode>.
491 void setDriverModeFromOption(StringRef Opt);
493 /// Parse the \p Args list for LTO options and record the type of LTO
494 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
495 void setLTOMode(const llvm::opt::ArgList &Args);
497 /// \brief Retrieves a ToolChain for a particular \p Target triple.
499 /// Will cache ToolChains for the life of the driver object, and create them
501 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
502 const llvm::Triple &Target) const;
506 /// \brief Get bitmasks for which option flags to include and exclude based on
508 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
510 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
511 /// jobs specifically for the given action, but will use the cache when
512 /// building jobs for the Action's inputs.
513 InputInfo BuildJobsForActionNoCache(
514 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
515 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
516 std::map<std::pair<const Action *, std::string>, InputInfo>
518 Action::OffloadKind TargetDeviceOffloadKind) const;
521 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
522 /// return the grouped values as integers. Numbers which are not
523 /// provided are set to 0.
525 /// \return True if the entire string was parsed (9.2), or all
526 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
527 /// groups were parsed but extra characters remain at the end.
528 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
529 unsigned &Micro, bool &HadExtra);
531 /// Parse digits from a string \p Str and fulfill \p Digits with
532 /// the parsed numbers. This method assumes that the max number of
533 /// digits to look for is equal to Digits.size().
535 /// \return True if the entire string was parsed and there are
536 /// no extra characters remaining at the end.
537 static bool GetReleaseVersion(StringRef Str,
538 MutableArrayRef<unsigned> Digits);
541 /// \return True if the last defined optimization level is -Ofast.
542 /// And False otherwise.
543 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
545 } // end namespace driver
546 } // end namespace clang