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
50 /// Driver - Encapsulate logic for constructing compilation processes
51 /// from a set of gcc-driver-like command line arguments.
53 llvm::opt::OptTable *Opts;
55 DiagnosticsEngine &Diags;
71 // Diag - Forwarding function for diagnostics.
72 DiagnosticBuilder Diag(unsigned DiagID) const {
73 return Diags.Report(DiagID);
76 // FIXME: Privatize once interface is stable.
78 /// The name the driver was invoked as.
81 /// The path the driver executable was in, as invoked from the
85 /// The original path to the clang executable.
86 std::string ClangExecutable;
88 /// The path to the installed clang directory, if any.
89 std::string InstalledDir;
91 /// The path to the compiler resource directory.
92 std::string ResourceDir;
94 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
96 /// FIXME: This type of customization should be removed in favor of the
97 /// universal driver when it is ready.
98 typedef SmallVector<std::string, 4> prefix_list;
99 prefix_list PrefixDirs;
101 /// sysroot, if present
104 /// Dynamic loader prefix, if present
105 std::string DyldPrefix;
107 /// If the standard library is used
110 /// Default target triple.
111 std::string DefaultTargetTriple;
113 /// Driver title to use with help.
114 std::string DriverTitle;
116 /// Information about the host which can be overridden by the user.
117 std::string HostBits, HostMachine, HostSystem, HostRelease;
119 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
120 const char *CCPrintOptionsFilename;
122 /// The file to log CC_PRINT_HEADERS output to, if enabled.
123 const char *CCPrintHeadersFilename;
125 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
126 const char *CCLogDiagnosticsFilename;
128 /// A list of inputs and their types for the given arguments.
129 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
132 /// Whether the driver should follow g++ like behavior.
133 bool CCCIsCXX() const { return Mode == GXXMode; }
135 /// Whether the driver is just the preprocessor.
136 bool CCCIsCPP() const { return Mode == CPPMode; }
138 /// Whether the driver should follow cl.exe like behavior.
139 bool IsCLMode() const { return Mode == CLMode; }
141 /// Only print tool bindings, don't build any jobs.
142 unsigned CCCPrintBindings : 1;
144 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
145 /// CCPrintOptionsFilename or to stderr.
146 unsigned CCPrintOptions : 1;
148 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
149 /// information to CCPrintHeadersFilename or to stderr.
150 unsigned CCPrintHeaders : 1;
152 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
153 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
155 unsigned CCLogDiagnostics : 1;
157 /// Whether the driver is generating diagnostics for debugging purposes.
158 unsigned CCGenDiagnostics : 1;
161 /// Name to use when invoking gcc/g++.
162 std::string CCCGenericGCCName;
164 /// Whether to check that input files exist when constructing compilation
166 unsigned CheckInputsExist : 1;
169 /// Use lazy precompiled headers for PCH support.
170 unsigned CCCUsePCH : 1;
173 /// Certain options suppress the 'no input files' warning.
174 bool SuppressMissingInputWarning : 1;
176 std::list<std::string> TempFiles;
177 std::list<std::string> ResultFiles;
179 /// \brief Cache of all the ToolChains in use by the driver.
181 /// This maps from the string representation of a triple to a ToolChain
182 /// created targeting that triple. The driver owns all the ToolChain objects
183 /// stored in it, and will clean them up when torn down.
184 mutable llvm::StringMap<ToolChain *> ToolChains;
187 /// TranslateInputArgs - Create a new derived argument list from the input
188 /// arguments, after applying the standard argument translations.
189 llvm::opt::DerivedArgList *
190 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
192 // getFinalPhase - Determine which compilation mode we are in and record
193 // which option we used to determine the final phase.
194 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
195 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
197 // Before executing jobs, sets up response files for commands that need them.
198 void setUpResponseFiles(Compilation &C, Command &Cmd);
200 void generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
201 SmallVectorImpl<std::string> &Names) const;
204 Driver(StringRef _ClangExecutable,
205 StringRef _DefaultTargetTriple,
206 DiagnosticsEngine &_Diags);
212 /// Name to use when invoking gcc/g++.
213 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
215 const llvm::opt::OptTable &getOpts() const { return *Opts; }
217 const DiagnosticsEngine &getDiags() const { return Diags; }
219 bool getCheckInputsExist() const { return CheckInputsExist; }
221 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
223 const std::string &getTitle() { return DriverTitle; }
224 void setTitle(std::string Value) { DriverTitle = Value; }
226 /// \brief Get the path to the main clang executable.
227 const char *getClangProgramPath() const {
228 return ClangExecutable.c_str();
231 /// \brief Get the path to where the clang executable was installed.
232 const char *getInstalledDir() const {
233 if (!InstalledDir.empty())
234 return InstalledDir.c_str();
237 void setInstalledDir(StringRef Value) {
238 InstalledDir = Value;
241 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
242 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
245 /// @name Primary Functionality
248 /// BuildCompilation - Construct a compilation object for a command
249 /// line argument vector.
251 /// \return A compilation, or 0 if none was built for the given
252 /// argument vector. A null return value does not necessarily
253 /// indicate an error condition, the diagnostics should be queried
254 /// to determine if an error occurred.
255 Compilation *BuildCompilation(ArrayRef<const char *> Args);
257 /// @name Driver Steps
260 /// ParseDriverMode - Look for and handle the driver mode option in Args.
261 void ParseDriverMode(ArrayRef<const char *> Args);
263 /// ParseArgStrings - Parse the given list of strings into an
265 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args);
267 /// BuildInputs - Construct the list of inputs and their types from
268 /// the given arguments.
270 /// \param TC - The default host tool chain.
271 /// \param Args - The input arguments.
272 /// \param Inputs - The list to store the resulting compilation
274 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
275 InputList &Inputs) const;
277 /// BuildActions - Construct the list of actions to perform for the
278 /// given arguments, which are only done for a single architecture.
280 /// \param TC - The default host tool chain.
281 /// \param Args - The input arguments.
282 /// \param Actions - The list to store the resulting actions onto.
283 void BuildActions(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
284 const InputList &Inputs, ActionList &Actions) const;
286 /// BuildUniversalActions - Construct the list of actions to perform
287 /// for the given arguments, which may require a universal build.
289 /// \param TC - The default host tool chain.
290 /// \param Args - The input arguments.
291 /// \param Actions - The list to store the resulting actions onto.
292 void BuildUniversalActions(const ToolChain &TC,
293 llvm::opt::DerivedArgList &Args,
294 const InputList &BAInputs,
295 ActionList &Actions) const;
297 /// BuildJobs - Bind actions to concrete tools and translate
298 /// arguments to form the list of jobs to run.
300 /// \param C - The compilation that is being built.
301 void BuildJobs(Compilation &C) const;
303 /// ExecuteCompilation - Execute the compilation according to the command line
304 /// arguments and return an appropriate exit code.
306 /// This routine handles additional processing that must be done in addition
307 /// to just running the subprocesses, for example reporting errors, setting
308 /// up response files, removing temporary files, etc.
309 int ExecuteCompilation(Compilation &C,
310 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
312 /// generateCompilationDiagnostics - Generate diagnostics information
313 /// including preprocessed source file(s).
315 void generateCompilationDiagnostics(Compilation &C,
316 const Command &FailingCommand);
319 /// @name Helper Methods
322 /// PrintActions - Print the list of actions.
323 void PrintActions(const Compilation &C) const;
325 /// PrintHelp - Print the help text.
327 /// \param ShowHidden - Show hidden options.
328 void PrintHelp(bool ShowHidden) const;
330 /// PrintVersion - Print the driver version.
331 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
333 /// GetFilePath - Lookup \p Name in the list of file search paths.
335 /// \param TC - The tool chain for additional information on
336 /// directories to search.
338 // FIXME: This should be in CompilationInfo.
339 std::string GetFilePath(const char *Name, const ToolChain &TC) const;
341 /// GetProgramPath - Lookup \p Name in the list of program search paths.
343 /// \param TC - The provided tool chain for additional information on
344 /// directories to search.
346 // FIXME: This should be in CompilationInfo.
347 std::string GetProgramPath(const char *Name, const ToolChain &TC) const;
349 /// HandleImmediateArgs - Handle any arguments which should be
350 /// treated before building actions or binding tools.
352 /// \return Whether any compilation should be built for this
354 bool HandleImmediateArgs(const Compilation &C);
356 /// ConstructAction - Construct the appropriate action to do for
357 /// \p Phase on the \p Input, taking in to account arguments
358 /// like -fsyntax-only or --analyze.
359 std::unique_ptr<Action>
360 ConstructPhaseAction(const ToolChain &TC, const llvm::opt::ArgList &Args,
361 phases::ID Phase, std::unique_ptr<Action> Input) const;
363 /// BuildJobsForAction - Construct the jobs to perform for the
365 void BuildJobsForAction(Compilation &C,
368 const char *BoundArch,
371 const char *LinkingOutput,
372 InputInfo &Result) const;
374 /// Returns the default name for linked images (e.g., "a.out").
375 const char *getDefaultImageName() const;
377 /// GetNamedOutputPath - Return the name to use for the output of
378 /// the action \p JA. The result is appended to the compilation's
379 /// list of temporary or result files, as appropriate.
381 /// \param C - The compilation.
382 /// \param JA - The action of interest.
383 /// \param BaseInput - The original input file that this action was
385 /// \param BoundArch - The bound architecture.
386 /// \param AtTopLevel - Whether this is a "top-level" action.
387 /// \param MultipleArchs - Whether multiple -arch options were supplied.
388 const char *GetNamedOutputPath(Compilation &C,
390 const char *BaseInput,
391 const char *BoundArch,
393 bool MultipleArchs) const;
395 /// GetTemporaryPath - Return the pathname of a temporary file to use
396 /// as part of compilation; the file will have the given prefix and suffix.
398 /// GCC goes to extra lengths here to be a bit more robust.
399 std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
401 /// ShouldUseClangCompiler - Should the clang compiler be used to
402 /// handle this action.
403 bool ShouldUseClangCompiler(const JobAction &JA) const;
405 bool IsUsingLTO(const llvm::opt::ArgList &Args) const;
408 /// \brief Retrieves a ToolChain for a particular \p Target triple.
410 /// Will cache ToolChains for the life of the driver object, and create them
412 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
413 const llvm::Triple &Target) const;
417 /// \brief Get bitmasks for which option flags to include and exclude based on
419 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
422 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
423 /// return the grouped values as integers. Numbers which are not
424 /// provided are set to 0.
426 /// \return True if the entire string was parsed (9.2), or all
427 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
428 /// groups were parsed but extra characters remain at the end.
429 static bool GetReleaseVersion(const char *Str, unsigned &Major,
430 unsigned &Minor, unsigned &Micro,
434 /// \return True if the last defined optimization level is -Ofast.
435 /// And False otherwise.
436 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
438 } // end namespace driver
439 } // end namespace clang