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/Phases.h"
16 #include "clang/Driver/Types.h"
17 #include "clang/Driver/Util.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo lands.
56 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
64 /// Driver - Encapsulate logic for constructing compilation processes
65 /// from a set of gcc-driver-like command line arguments.
67 llvm::opt::OptTable *Opts;
69 DiagnosticsEngine &Diags;
71 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
86 enum BitcodeEmbedMode {
92 /// LTO mode selected via -f(no-)?lto(=.*)? options.
96 // Diag - Forwarding function for diagnostics.
97 DiagnosticBuilder Diag(unsigned DiagID) const {
98 return Diags.Report(DiagID);
101 // FIXME: Privatize once interface is stable.
103 /// The name the driver was invoked as.
106 /// The path the driver executable was in, as invoked from the
110 /// The original path to the clang executable.
111 std::string ClangExecutable;
113 /// The path to the installed clang directory, if any.
114 std::string InstalledDir;
116 /// The path to the compiler resource directory.
117 std::string ResourceDir;
119 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
121 /// FIXME: This type of customization should be removed in favor of the
122 /// universal driver when it is ready.
123 typedef SmallVector<std::string, 4> prefix_list;
124 prefix_list PrefixDirs;
126 /// sysroot, if present
129 /// Dynamic loader prefix, if present
130 std::string DyldPrefix;
132 /// If the standard library is used
135 /// Default target triple.
136 std::string DefaultTargetTriple;
138 /// Driver title to use with help.
139 std::string DriverTitle;
141 /// Information about the host which can be overridden by the user.
142 std::string HostBits, HostMachine, HostSystem, HostRelease;
144 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
145 const char *CCPrintOptionsFilename;
147 /// The file to log CC_PRINT_HEADERS output to, if enabled.
148 const char *CCPrintHeadersFilename;
150 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
151 const char *CCLogDiagnosticsFilename;
153 /// A list of inputs and their types for the given arguments.
154 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
157 /// Whether the driver should follow g++ like behavior.
158 bool CCCIsCXX() const { return Mode == GXXMode; }
160 /// Whether the driver is just the preprocessor.
161 bool CCCIsCPP() const { return Mode == CPPMode; }
163 /// Whether the driver should follow cl.exe like behavior.
164 bool IsCLMode() const { return Mode == CLMode; }
166 /// Only print tool bindings, don't build any jobs.
167 unsigned CCCPrintBindings : 1;
169 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
170 /// CCPrintOptionsFilename or to stderr.
171 unsigned CCPrintOptions : 1;
173 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
174 /// information to CCPrintHeadersFilename or to stderr.
175 unsigned CCPrintHeaders : 1;
177 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
178 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
180 unsigned CCLogDiagnostics : 1;
182 /// Whether the driver is generating diagnostics for debugging purposes.
183 unsigned CCGenDiagnostics : 1;
186 /// Name to use when invoking gcc/g++.
187 std::string CCCGenericGCCName;
189 /// Whether to check that input files exist when constructing compilation
191 unsigned CheckInputsExist : 1;
194 /// Use lazy precompiled headers for PCH support.
195 unsigned CCCUsePCH : 1;
198 /// Certain options suppress the 'no input files' warning.
199 unsigned SuppressMissingInputWarning : 1;
201 std::list<std::string> TempFiles;
202 std::list<std::string> ResultFiles;
204 /// \brief Cache of all the ToolChains in use by the driver.
206 /// This maps from the string representation of a triple to a ToolChain
207 /// created targeting that triple. The driver owns all the ToolChain objects
208 /// stored in it, and will clean them up when torn down.
209 mutable llvm::StringMap<ToolChain *> ToolChains;
212 /// TranslateInputArgs - Create a new derived argument list from the input
213 /// arguments, after applying the standard argument translations.
214 llvm::opt::DerivedArgList *
215 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
217 // getFinalPhase - Determine which compilation mode we are in and record
218 // which option we used to determine the final phase.
219 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
220 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
222 // Before executing jobs, sets up response files for commands that need them.
223 void setUpResponseFiles(Compilation &C, Command &Cmd);
225 void generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
226 SmallVectorImpl<std::string> &Names) const;
229 Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
230 DiagnosticsEngine &Diags,
231 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
237 /// Name to use when invoking gcc/g++.
238 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
240 const llvm::opt::OptTable &getOpts() const { return *Opts; }
242 const DiagnosticsEngine &getDiags() const { return Diags; }
244 vfs::FileSystem &getVFS() const { return *VFS; }
246 bool getCheckInputsExist() const { return CheckInputsExist; }
248 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
250 const std::string &getTitle() { return DriverTitle; }
251 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
253 /// \brief Get the path to the main clang executable.
254 const char *getClangProgramPath() const {
255 return ClangExecutable.c_str();
258 /// \brief Get the path to where the clang executable was installed.
259 const char *getInstalledDir() const {
260 if (!InstalledDir.empty())
261 return InstalledDir.c_str();
264 void setInstalledDir(StringRef Value) {
265 InstalledDir = Value;
268 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
269 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
271 bool embedBitcodeEnabled() const { return BitcodeEmbed == EmbedBitcode; }
272 bool embedBitcodeMarkerOnly() const { return BitcodeEmbed == EmbedMarker; }
275 /// @name Primary Functionality
278 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
279 /// support offloading devices given the programming models specified in the
280 /// current compilation. Also, update the host tool chain kind accordingly.
281 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
283 /// BuildCompilation - Construct a compilation object for a command
284 /// line argument vector.
286 /// \return A compilation, or 0 if none was built for the given
287 /// argument vector. A null return value does not necessarily
288 /// indicate an error condition, the diagnostics should be queried
289 /// to determine if an error occurred.
290 Compilation *BuildCompilation(ArrayRef<const char *> Args);
292 /// @name Driver Steps
295 /// ParseDriverMode - Look for and handle the driver mode option in Args.
296 void ParseDriverMode(ArrayRef<const char *> Args);
298 /// ParseArgStrings - Parse the given list of strings into an
300 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args);
302 /// BuildInputs - Construct the list of inputs and their types from
303 /// the given arguments.
305 /// \param TC - The default host tool chain.
306 /// \param Args - The input arguments.
307 /// \param Inputs - The list to store the resulting compilation
309 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
310 InputList &Inputs) const;
312 /// BuildActions - Construct the list of actions to perform for the
313 /// given arguments, which are only done for a single architecture.
315 /// \param C - The compilation that is being built.
316 /// \param Args - The input arguments.
317 /// \param Actions - The list to store the resulting actions onto.
318 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
319 const InputList &Inputs, ActionList &Actions) const;
321 /// BuildUniversalActions - Construct the list of actions to perform
322 /// for the given arguments, which may require a universal build.
324 /// \param C - The compilation that is being built.
325 /// \param TC - The default host tool chain.
326 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
327 const InputList &BAInputs) const;
329 /// BuildJobs - Bind actions to concrete tools and translate
330 /// arguments to form the list of jobs to run.
332 /// \param C - The compilation that is being built.
333 void BuildJobs(Compilation &C) const;
335 /// ExecuteCompilation - Execute the compilation according to the command line
336 /// arguments and return an appropriate exit code.
338 /// This routine handles additional processing that must be done in addition
339 /// to just running the subprocesses, for example reporting errors, setting
340 /// up response files, removing temporary files, etc.
341 int ExecuteCompilation(Compilation &C,
342 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
344 /// generateCompilationDiagnostics - Generate diagnostics information
345 /// including preprocessed source file(s).
347 void generateCompilationDiagnostics(Compilation &C,
348 const Command &FailingCommand);
351 /// @name Helper Methods
354 /// PrintActions - Print the list of actions.
355 void PrintActions(const Compilation &C) const;
357 /// PrintHelp - Print the help text.
359 /// \param ShowHidden - Show hidden options.
360 void PrintHelp(bool ShowHidden) const;
362 /// PrintVersion - Print the driver version.
363 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
365 /// GetFilePath - Lookup \p Name in the list of file search paths.
367 /// \param TC - The tool chain for additional information on
368 /// directories to search.
370 // FIXME: This should be in CompilationInfo.
371 std::string GetFilePath(const char *Name, const ToolChain &TC) const;
373 /// GetProgramPath - Lookup \p Name in the list of program search paths.
375 /// \param TC - The provided tool chain for additional information on
376 /// directories to search.
378 // FIXME: This should be in CompilationInfo.
379 std::string GetProgramPath(const char *Name, const ToolChain &TC) const;
381 /// HandleImmediateArgs - Handle any arguments which should be
382 /// treated before building actions or binding tools.
384 /// \return Whether any compilation should be built for this
386 bool HandleImmediateArgs(const Compilation &C);
388 /// ConstructAction - Construct the appropriate action to do for
389 /// \p Phase on the \p Input, taking in to account arguments
390 /// like -fsyntax-only or --analyze.
391 Action *ConstructPhaseAction(Compilation &C, const llvm::opt::ArgList &Args,
392 phases::ID Phase, Action *Input) const;
394 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
395 /// return an InputInfo for the result of running \p A. Will only construct
396 /// jobs for a given (Action, ToolChain, BoundArch) tuple once.
398 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
399 const char *BoundArch, bool AtTopLevel, bool MultipleArchs,
400 const char *LinkingOutput,
401 std::map<std::pair<const Action *, std::string>, InputInfo>
403 bool BuildForOffloadDevice) const;
405 /// Returns the default name for linked images (e.g., "a.out").
406 const char *getDefaultImageName() const;
408 /// GetNamedOutputPath - Return the name to use for the output of
409 /// the action \p JA. The result is appended to the compilation's
410 /// list of temporary or result files, as appropriate.
412 /// \param C - The compilation.
413 /// \param JA - The action of interest.
414 /// \param BaseInput - The original input file that this action was
416 /// \param BoundArch - The bound architecture.
417 /// \param AtTopLevel - Whether this is a "top-level" action.
418 /// \param MultipleArchs - Whether multiple -arch options were supplied.
419 /// \param NormalizedTriple - The normalized triple of the relevant target.
420 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
421 const char *BaseInput, const char *BoundArch,
422 bool AtTopLevel, bool MultipleArchs,
423 StringRef NormalizedTriple) const;
425 /// GetTemporaryPath - Return the pathname of a temporary file to use
426 /// as part of compilation; the file will have the given prefix and suffix.
428 /// GCC goes to extra lengths here to be a bit more robust.
429 std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
431 /// Return the pathname of the pch file in clang-cl mode.
432 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
434 /// ShouldUseClangCompiler - Should the clang compiler be used to
435 /// handle this action.
436 bool ShouldUseClangCompiler(const JobAction &JA) const;
438 /// Returns true if we are performing any kind of LTO.
439 bool isUsingLTO() const { return LTOMode != LTOK_None; }
441 /// Get the specific kind of LTO being performed.
442 LTOKind getLTOMode() const { return LTOMode; }
445 /// Parse the \p Args list for LTO options and record the type of LTO
446 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
447 void setLTOMode(const llvm::opt::ArgList &Args);
449 /// \brief Retrieves a ToolChain for a particular \p Target triple.
451 /// Will cache ToolChains for the life of the driver object, and create them
453 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
454 const llvm::Triple &Target) const;
458 /// \brief Get bitmasks for which option flags to include and exclude based on
460 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
462 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
463 /// jobs specifically for the given action, but will use the cache when
464 /// building jobs for the Action's inputs.
465 InputInfo BuildJobsForActionNoCache(
466 Compilation &C, const Action *A, const ToolChain *TC,
467 const char *BoundArch, bool AtTopLevel, bool MultipleArchs,
468 const char *LinkingOutput,
469 std::map<std::pair<const Action *, std::string>, InputInfo>
471 bool BuildForOffloadDevice) const;
474 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
475 /// return the grouped values as integers. Numbers which are not
476 /// provided are set to 0.
478 /// \return True if the entire string was parsed (9.2), or all
479 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
480 /// groups were parsed but extra characters remain at the end.
481 static bool GetReleaseVersion(const char *Str, unsigned &Major,
482 unsigned &Minor, unsigned &Micro,
485 /// Parse digits from a string \p Str and fulfill \p Digits with
486 /// the parsed numbers. This method assumes that the max number of
487 /// digits to look for is equal to Digits.size().
489 /// \return True if the entire string was parsed and there are
490 /// no extra characters remaining at the end.
491 static bool GetReleaseVersion(const char *Str,
492 MutableArrayRef<unsigned> Digits);
495 /// \return True if the last defined optimization level is -Ofast.
496 /// And False otherwise.
497 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
499 } // end namespace driver
500 } // end namespace clang