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;
65 // Diag - Forwarding function for diagnostics.
66 DiagnosticBuilder Diag(unsigned DiagID) const {
67 return Diags.Report(DiagID);
70 // FIXME: Privatize once interface is stable.
72 /// The name the driver was invoked as.
75 /// The path the driver executable was in, as invoked from the
79 /// The original path to the clang executable.
80 std::string ClangExecutable;
82 /// The path to the installed clang directory, if any.
83 std::string InstalledDir;
85 /// The path to the compiler resource directory.
86 std::string ResourceDir;
88 /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix'
90 /// FIXME: This type of customization should be removed in favor of the
91 /// universal driver when it is ready.
92 typedef SmallVector<std::string, 4> prefix_list;
93 prefix_list PrefixDirs;
95 /// sysroot, if present
98 /// Dynamic loader prefix, if present
99 std::string DyldPrefix;
101 /// If the standard library is used
104 /// Default target triple.
105 std::string DefaultTargetTriple;
107 /// Driver title to use with help.
108 std::string DriverTitle;
110 /// Information about the host which can be overridden by the user.
111 std::string HostBits, HostMachine, HostSystem, HostRelease;
113 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
114 const char *CCPrintOptionsFilename;
116 /// The file to log CC_PRINT_HEADERS output to, if enabled.
117 const char *CCPrintHeadersFilename;
119 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
120 const char *CCLogDiagnosticsFilename;
122 /// A list of inputs and their types for the given arguments.
123 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
126 /// Whether the driver should follow g++ like behavior.
127 bool CCCIsCXX() const { return Mode == GXXMode; }
129 /// Whether the driver is just the preprocessor.
130 bool CCCIsCPP() const { return Mode == CPPMode; }
132 /// Whether the driver should follow cl.exe like behavior.
133 bool IsCLMode() const { return Mode == CLMode; }
135 /// Only print tool bindings, don't build any jobs.
136 unsigned CCCPrintBindings : 1;
138 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
139 /// CCPrintOptionsFilename or to stderr.
140 unsigned CCPrintOptions : 1;
142 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
143 /// information to CCPrintHeadersFilename or to stderr.
144 unsigned CCPrintHeaders : 1;
146 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
147 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
149 unsigned CCLogDiagnostics : 1;
151 /// Whether the driver is generating diagnostics for debugging purposes.
152 unsigned CCGenDiagnostics : 1;
155 /// Name to use when invoking gcc/g++.
156 std::string CCCGenericGCCName;
158 /// Whether to check that input files exist when constructing compilation
160 unsigned CheckInputsExist : 1;
163 /// Use lazy precompiled headers for PCH support.
164 unsigned CCCUsePCH : 1;
167 /// Certain options suppress the 'no input files' warning.
168 bool SuppressMissingInputWarning : 1;
170 std::list<std::string> TempFiles;
171 std::list<std::string> ResultFiles;
173 /// \brief Cache of all the ToolChains in use by the driver.
175 /// This maps from the string representation of a triple to a ToolChain
176 /// created targeting that triple. The driver owns all the ToolChain objects
177 /// stored in it, and will clean them up when torn down.
178 mutable llvm::StringMap<ToolChain *> ToolChains;
181 /// TranslateInputArgs - Create a new derived argument list from the input
182 /// arguments, after applying the standard argument translations.
183 llvm::opt::DerivedArgList *
184 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
186 // getFinalPhase - Determine which compilation mode we are in and record
187 // which option we used to determine the final phase.
188 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
189 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
191 // Before executing jobs, sets up response files for commands that need them.
192 void setUpResponseFiles(Compilation &C, Job &J);
194 void generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
195 SmallVectorImpl<std::string> &Names) const;
198 Driver(StringRef _ClangExecutable,
199 StringRef _DefaultTargetTriple,
200 DiagnosticsEngine &_Diags);
206 /// Name to use when invoking gcc/g++.
207 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
209 const llvm::opt::OptTable &getOpts() const { return *Opts; }
211 const DiagnosticsEngine &getDiags() const { return Diags; }
213 bool getCheckInputsExist() const { return CheckInputsExist; }
215 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
217 const std::string &getTitle() { return DriverTitle; }
218 void setTitle(std::string Value) { DriverTitle = Value; }
220 /// \brief Get the path to the main clang executable.
221 const char *getClangProgramPath() const {
222 return ClangExecutable.c_str();
225 /// \brief Get the path to where the clang executable was installed.
226 const char *getInstalledDir() const {
227 if (!InstalledDir.empty())
228 return InstalledDir.c_str();
231 void setInstalledDir(StringRef Value) {
232 InstalledDir = Value;
236 /// @name Primary Functionality
239 /// BuildCompilation - Construct a compilation object for a command
240 /// line argument vector.
242 /// \return A compilation, or 0 if none was built for the given
243 /// argument vector. A null return value does not necessarily
244 /// indicate an error condition, the diagnostics should be queried
245 /// to determine if an error occurred.
246 Compilation *BuildCompilation(ArrayRef<const char *> Args);
248 /// @name Driver Steps
251 /// ParseDriverMode - Look for and handle the driver mode option in Args.
252 void ParseDriverMode(ArrayRef<const char *> Args);
254 /// ParseArgStrings - Parse the given list of strings into an
256 llvm::opt::InputArgList *ParseArgStrings(ArrayRef<const char *> Args);
258 /// BuildInputs - Construct the list of inputs and their types from
259 /// the given arguments.
261 /// \param TC - The default host tool chain.
262 /// \param Args - The input arguments.
263 /// \param Inputs - The list to store the resulting compilation
265 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
266 InputList &Inputs) const;
268 /// BuildActions - Construct the list of actions to perform for the
269 /// given arguments, which are only done for a single architecture.
271 /// \param TC - The default host tool chain.
272 /// \param Args - The input arguments.
273 /// \param Actions - The list to store the resulting actions onto.
274 void BuildActions(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
275 const InputList &Inputs, ActionList &Actions) const;
277 /// BuildUniversalActions - Construct the list of actions to perform
278 /// for the given arguments, which may require a universal build.
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 BuildUniversalActions(const ToolChain &TC,
284 llvm::opt::DerivedArgList &Args,
285 const InputList &BAInputs,
286 ActionList &Actions) const;
288 /// BuildJobs - Bind actions to concrete tools and translate
289 /// arguments to form the list of jobs to run.
291 /// \param C - The compilation that is being built.
292 void BuildJobs(Compilation &C) const;
294 /// ExecuteCompilation - Execute the compilation according to the command line
295 /// arguments and return an appropriate exit code.
297 /// This routine handles additional processing that must be done in addition
298 /// to just running the subprocesses, for example reporting errors, setting
299 /// up response files, removing temporary files, etc.
300 int ExecuteCompilation(Compilation &C,
301 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
303 /// generateCompilationDiagnostics - Generate diagnostics information
304 /// including preprocessed source file(s).
306 void generateCompilationDiagnostics(Compilation &C,
307 const Command &FailingCommand);
310 /// @name Helper Methods
313 /// PrintActions - Print the list of actions.
314 void PrintActions(const Compilation &C) const;
316 /// PrintHelp - Print the help text.
318 /// \param ShowHidden - Show hidden options.
319 void PrintHelp(bool ShowHidden) const;
321 /// PrintVersion - Print the driver version.
322 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
324 /// GetFilePath - Lookup \p Name in the list of file search paths.
326 /// \param TC - The tool chain for additional information on
327 /// directories to search.
329 // FIXME: This should be in CompilationInfo.
330 std::string GetFilePath(const char *Name, const ToolChain &TC) const;
332 /// GetProgramPath - Lookup \p Name in the list of program search paths.
334 /// \param TC - The provided tool chain for additional information on
335 /// directories to search.
337 // FIXME: This should be in CompilationInfo.
338 std::string GetProgramPath(const char *Name, const ToolChain &TC) const;
340 /// HandleImmediateArgs - Handle any arguments which should be
341 /// treated before building actions or binding tools.
343 /// \return Whether any compilation should be built for this
345 bool HandleImmediateArgs(const Compilation &C);
347 /// ConstructAction - Construct the appropriate action to do for
348 /// \p Phase on the \p Input, taking in to account arguments
349 /// like -fsyntax-only or --analyze.
350 std::unique_ptr<Action>
351 ConstructPhaseAction(const llvm::opt::ArgList &Args, phases::ID Phase,
352 std::unique_ptr<Action> Input) const;
354 /// BuildJobsForAction - Construct the jobs to perform for the
356 void BuildJobsForAction(Compilation &C,
359 const char *BoundArch,
362 const char *LinkingOutput,
363 InputInfo &Result) const;
365 /// Returns the default name for linked images (e.g., "a.out").
366 const char *getDefaultImageName() const;
368 /// GetNamedOutputPath - Return the name to use for the output of
369 /// the action \p JA. The result is appended to the compilation's
370 /// list of temporary or result files, as appropriate.
372 /// \param C - The compilation.
373 /// \param JA - The action of interest.
374 /// \param BaseInput - The original input file that this action was
376 /// \param BoundArch - The bound architecture.
377 /// \param AtTopLevel - Whether this is a "top-level" action.
378 /// \param MultipleArchs - Whether multiple -arch options were supplied.
379 const char *GetNamedOutputPath(Compilation &C,
381 const char *BaseInput,
382 const char *BoundArch,
384 bool MultipleArchs) const;
386 /// GetTemporaryPath - Return the pathname of a temporary file to use
387 /// as part of compilation; the file will have the given prefix and suffix.
389 /// GCC goes to extra lengths here to be a bit more robust.
390 std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
392 /// ShouldUseClangCompiler - Should the clang compiler be used to
393 /// handle this action.
394 bool ShouldUseClangCompiler(const JobAction &JA) const;
396 bool IsUsingLTO(const llvm::opt::ArgList &Args) const;
399 /// \brief Retrieves a ToolChain for a particular target triple.
401 /// Will cache ToolChains for the life of the driver object, and create them
403 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
404 StringRef DarwinArchName = "") const;
408 /// \brief Get bitmasks for which option flags to include and exclude based on
410 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
413 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
414 /// return the grouped values as integers. Numbers which are not
415 /// provided are set to 0.
417 /// \return True if the entire string was parsed (9.2), or all
418 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
419 /// groups were parsed but extra characters remain at the end.
420 static bool GetReleaseVersion(const char *Str, unsigned &Major,
421 unsigned &Minor, unsigned &Micro,
425 /// \return True if the last defined optimization level is -Ofast.
426 /// And False otherwise.
427 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
429 } // end namespace driver
430 } // end namespace clang