clang API Documentation

Driver.h
Go to the documentation of this file.
00001 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #ifndef CLANG_DRIVER_DRIVER_H_
00011 #define CLANG_DRIVER_DRIVER_H_
00012 
00013 #include "clang/Basic/Diagnostic.h"
00014 
00015 #include "clang/Driver/Phases.h"
00016 #include "clang/Driver/Types.h"
00017 #include "clang/Driver/Util.h"
00018 
00019 #include "llvm/ADT/StringMap.h"
00020 #include "llvm/ADT/StringRef.h"
00021 #include "llvm/ADT/Triple.h"
00022 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo
00023                               // lands.
00024 #include <list>
00025 #include <set>
00026 #include <string>
00027 
00028 namespace llvm {
00029   template<typename T> class ArrayRef;
00030 }
00031 namespace clang {
00032 namespace driver {
00033   class Action;
00034   class Arg;
00035   class ArgList;
00036   class Command;
00037   class Compilation;
00038   class DerivedArgList;
00039   class InputArgList;
00040   class InputInfo;
00041   class JobAction;
00042   class OptTable;
00043   class ToolChain;
00044 
00045 /// Driver - Encapsulate logic for constructing compilation processes
00046 /// from a set of gcc-driver-like command line arguments.
00047 class Driver {
00048   OptTable *Opts;
00049 
00050   DiagnosticsEngine &Diags;
00051 
00052 public:
00053   // Diag - Forwarding function for diagnostics.
00054   DiagnosticBuilder Diag(unsigned DiagID) const {
00055     return Diags.Report(DiagID);
00056   }
00057 
00058   // FIXME: Privatize once interface is stable.
00059 public:
00060   /// The name the driver was invoked as.
00061   std::string Name;
00062 
00063   /// The path the driver executable was in, as invoked from the
00064   /// command line.
00065   std::string Dir;
00066 
00067   /// The original path to the clang executable.
00068   std::string ClangExecutable;
00069 
00070   /// The path to the installed clang directory, if any.
00071   std::string InstalledDir;
00072 
00073   /// The path to the compiler resource directory.
00074   std::string ResourceDir;
00075 
00076   /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix'
00077   /// functionality.
00078   /// FIXME: This type of customization should be removed in favor of the
00079   /// universal driver when it is ready.
00080   typedef SmallVector<std::string, 4> prefix_list;
00081   prefix_list PrefixDirs;
00082 
00083   /// sysroot, if present
00084   std::string SysRoot;
00085 
00086   /// If the standard library is used
00087   bool UseStdLib;
00088 
00089   /// Default target triple.
00090   std::string DefaultTargetTriple;
00091 
00092   /// Default name for linked images (e.g., "a.out").
00093   std::string DefaultImageName;
00094 
00095   /// Driver title to use with help.
00096   std::string DriverTitle;
00097 
00098   /// Information about the host which can be overridden by the user.
00099   std::string HostBits, HostMachine, HostSystem, HostRelease;
00100 
00101   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
00102   const char *CCPrintOptionsFilename;
00103 
00104   /// The file to log CC_PRINT_HEADERS output to, if enabled.
00105   const char *CCPrintHeadersFilename;
00106 
00107   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
00108   const char *CCLogDiagnosticsFilename;
00109 
00110   /// A list of inputs and their types for the given arguments.
00111   typedef SmallVector<std::pair<types::ID, const Arg*>, 16> InputList;
00112 
00113   /// Whether the driver should follow g++ like behavior.
00114   unsigned CCCIsCXX : 1;
00115 
00116   /// Whether the driver is just the preprocessor.
00117   unsigned CCCIsCPP : 1;
00118 
00119   /// Echo commands while executing (in -v style).
00120   unsigned CCCEcho : 1;
00121 
00122   /// Only print tool bindings, don't build any jobs.
00123   unsigned CCCPrintBindings : 1;
00124 
00125   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
00126   /// CCPrintOptionsFilename or to stderr.
00127   unsigned CCPrintOptions : 1;
00128 
00129   /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
00130   /// information to CCPrintHeadersFilename or to stderr.
00131   unsigned CCPrintHeaders : 1;
00132 
00133   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
00134   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
00135   /// format.
00136   unsigned CCLogDiagnostics : 1;
00137 
00138   /// Whether the driver is generating diagnostics for debugging purposes.
00139   unsigned CCGenDiagnostics : 1;
00140 
00141 private:
00142   /// Name to use when invoking gcc/g++.
00143   std::string CCCGenericGCCName;
00144 
00145   /// Whether to check that input files exist when constructing compilation
00146   /// jobs.
00147   unsigned CheckInputsExist : 1;
00148 
00149   /// Use the clang compiler where possible.
00150   unsigned CCCUseClang : 1;
00151 
00152   /// Use clang for handling C++ and Objective-C++ inputs.
00153   unsigned CCCUseClangCXX : 1;
00154 
00155   /// Use clang as a preprocessor (clang's preprocessor will still be
00156   /// used where an integrated CPP would).
00157   unsigned CCCUseClangCPP : 1;
00158 
00159 public:
00160   /// Use lazy precompiled headers for PCH support.
00161   unsigned CCCUsePCH : 1;
00162 
00163 private:
00164   /// Only use clang for the given architectures (only used when
00165   /// non-empty).
00166   std::set<llvm::Triple::ArchType> CCCClangArchs;
00167 
00168   /// Certain options suppress the 'no input files' warning.
00169   bool SuppressMissingInputWarning : 1;
00170 
00171   std::list<std::string> TempFiles;
00172   std::list<std::string> ResultFiles;
00173 
00174   /// \brief Cache of all the ToolChains in use by the driver.
00175   ///
00176   /// This maps from the string representation of a triple to a ToolChain
00177   /// created targetting that triple. The driver owns all the ToolChain objects
00178   /// stored in it, and will clean them up when torn down.
00179   mutable llvm::StringMap<ToolChain *> ToolChains;
00180 
00181 private:
00182   /// TranslateInputArgs - Create a new derived argument list from the input
00183   /// arguments, after applying the standard argument translations.
00184   DerivedArgList *TranslateInputArgs(const InputArgList &Args) const;
00185 
00186   // getFinalPhase - Determine which compilation mode we are in and record 
00187   // which option we used to determine the final phase.
00188   phases::ID getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg = 0)
00189     const;
00190 
00191 public:
00192   Driver(StringRef _ClangExecutable,
00193          StringRef _DefaultTargetTriple,
00194          StringRef _DefaultImageName,
00195          bool IsProduction,
00196          DiagnosticsEngine &_Diags);
00197   ~Driver();
00198 
00199   /// @name Accessors
00200   /// @{
00201 
00202   /// Name to use when invoking gcc/g++.
00203   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
00204 
00205 
00206   const OptTable &getOpts() const { return *Opts; }
00207 
00208   const DiagnosticsEngine &getDiags() const { return Diags; }
00209 
00210   bool getCheckInputsExist() const { return CheckInputsExist; }
00211 
00212   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
00213 
00214   const std::string &getTitle() { return DriverTitle; }
00215   void setTitle(std::string Value) { DriverTitle = Value; }
00216 
00217   /// \brief Get the path to the main clang executable.
00218   const char *getClangProgramPath() const {
00219     return ClangExecutable.c_str();
00220   }
00221 
00222   /// \brief Get the path to where the clang executable was installed.
00223   const char *getInstalledDir() const {
00224     if (!InstalledDir.empty())
00225       return InstalledDir.c_str();
00226     return Dir.c_str();
00227   }
00228   void setInstalledDir(StringRef Value) {
00229     InstalledDir = Value;
00230   }
00231 
00232   /// @}
00233   /// @name Primary Functionality
00234   /// @{
00235 
00236   /// BuildCompilation - Construct a compilation object for a command
00237   /// line argument vector.
00238   ///
00239   /// \return A compilation, or 0 if none was built for the given
00240   /// argument vector. A null return value does not necessarily
00241   /// indicate an error condition, the diagnostics should be queried
00242   /// to determine if an error occurred.
00243   Compilation *BuildCompilation(ArrayRef<const char *> Args);
00244 
00245   /// @name Driver Steps
00246   /// @{
00247 
00248   /// ParseArgStrings - Parse the given list of strings into an
00249   /// ArgList.
00250   InputArgList *ParseArgStrings(ArrayRef<const char *> Args);
00251 
00252   /// BuildInputs - Construct the list of inputs and their types from 
00253   /// the given arguments.
00254   ///
00255   /// \param TC - The default host tool chain.
00256   /// \param Args - The input arguments.
00257   /// \param Inputs - The list to store the resulting compilation 
00258   /// inputs onto.
00259   void BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
00260                    InputList &Inputs) const;
00261 
00262   /// BuildActions - Construct the list of actions to perform for the
00263   /// given arguments, which are only done for a single architecture.
00264   ///
00265   /// \param TC - The default host tool chain.
00266   /// \param Args - The input arguments.
00267   /// \param Actions - The list to store the resulting actions onto.
00268   void BuildActions(const ToolChain &TC, const DerivedArgList &Args,
00269                     const InputList &Inputs, ActionList &Actions) const;
00270 
00271   /// BuildUniversalActions - Construct the list of actions to perform
00272   /// for the given arguments, which may require a universal build.
00273   ///
00274   /// \param TC - The default host tool chain.
00275   /// \param Args - The input arguments.
00276   /// \param Actions - The list to store the resulting actions onto.
00277   void BuildUniversalActions(const ToolChain &TC, const DerivedArgList &Args,
00278                              const InputList &BAInputs,
00279                              ActionList &Actions) const;
00280 
00281   /// BuildJobs - Bind actions to concrete tools and translate
00282   /// arguments to form the list of jobs to run.
00283   ///
00284   /// \arg C - The compilation that is being built.
00285   void BuildJobs(Compilation &C) const;
00286 
00287   /// ExecuteCompilation - Execute the compilation according to the command line
00288   /// arguments and return an appropriate exit code.
00289   ///
00290   /// This routine handles additional processing that must be done in addition
00291   /// to just running the subprocesses, for example reporting errors, removing
00292   /// temporary files, etc.
00293   int ExecuteCompilation(const Compilation &C,
00294                          const Command *&FailingCommand) const;
00295   
00296   /// generateCompilationDiagnostics - Generate diagnostics information 
00297   /// including preprocessed source file(s).
00298   /// 
00299   void generateCompilationDiagnostics(Compilation &C,
00300                                       const Command *FailingCommand);
00301 
00302   /// @}
00303   /// @name Helper Methods
00304   /// @{
00305 
00306   /// PrintActions - Print the list of actions.
00307   void PrintActions(const Compilation &C) const;
00308 
00309   /// PrintHelp - Print the help text.
00310   ///
00311   /// \param ShowHidden - Show hidden options.
00312   void PrintHelp(bool ShowHidden) const;
00313 
00314   /// PrintOptions - Print the list of arguments.
00315   void PrintOptions(const ArgList &Args) const;
00316 
00317   /// PrintVersion - Print the driver version.
00318   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
00319 
00320   /// GetFilePath - Lookup \arg Name in the list of file search paths.
00321   ///
00322   /// \arg TC - The tool chain for additional information on
00323   /// directories to search.
00324   //
00325   // FIXME: This should be in CompilationInfo.
00326   std::string GetFilePath(const char *Name, const ToolChain &TC) const;
00327 
00328   /// GetProgramPath - Lookup \arg Name in the list of program search
00329   /// paths.
00330   ///
00331   /// \arg TC - The provided tool chain for additional information on
00332   /// directories to search.
00333   ///
00334   /// \arg WantFile - False when searching for an executable file, otherwise
00335   /// true.  Defaults to false.
00336   //
00337   // FIXME: This should be in CompilationInfo.
00338   std::string GetProgramPath(const char *Name, const ToolChain &TC,
00339                               bool WantFile = false) const;
00340 
00341   /// HandleImmediateArgs - Handle any arguments which should be
00342   /// treated before building actions or binding tools.
00343   ///
00344   /// \return Whether any compilation should be built for this
00345   /// invocation.
00346   bool HandleImmediateArgs(const Compilation &C);
00347 
00348   /// ConstructAction - Construct the appropriate action to do for
00349   /// \arg Phase on the \arg Input, taking in to account arguments
00350   /// like -fsyntax-only or --analyze.
00351   Action *ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
00352                                Action *Input) const;
00353 
00354 
00355   /// BuildJobsForAction - Construct the jobs to perform for the
00356   /// action \arg A.
00357   void BuildJobsForAction(Compilation &C,
00358                           const Action *A,
00359                           const ToolChain *TC,
00360                           const char *BoundArch,
00361                           bool AtTopLevel,
00362                           const char *LinkingOutput,
00363                           InputInfo &Result) const;
00364 
00365   /// GetNamedOutputPath - Return the name to use for the output of
00366   /// the action \arg JA. The result is appended to the compilation's
00367   /// list of temporary or result files, as appropriate.
00368   ///
00369   /// \param C - The compilation.
00370   /// \param JA - The action of interest.
00371   /// \param BaseInput - The original input file that this action was
00372   /// triggered by.
00373   /// \param AtTopLevel - Whether this is a "top-level" action.
00374   const char *GetNamedOutputPath(Compilation &C,
00375                                  const JobAction &JA,
00376                                  const char *BaseInput,
00377                                  bool AtTopLevel) const;
00378 
00379   /// GetTemporaryPath - Return the pathname of a temporary file to use 
00380   /// as part of compilation; the file will have the given prefix and suffix.
00381   ///
00382   /// GCC goes to extra lengths here to be a bit more robust.
00383   std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
00384 
00385   /// ShouldUseClangCompilar - Should the clang compiler be used to
00386   /// handle this action.
00387   bool ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
00388                               const llvm::Triple &ArchName) const;
00389 
00390   bool IsUsingLTO(const ArgList &Args) const;
00391 
00392 private:
00393   /// \brief Retrieves a ToolChain for a particular target triple.
00394   ///
00395   /// Will cache ToolChains for the life of the driver object, and create them
00396   /// on-demand.
00397   const ToolChain &getToolChain(const ArgList &Args,
00398                                 StringRef DarwinArchName = "") const;
00399 
00400   /// @}
00401 
00402 public:
00403   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
00404   /// return the grouped values as integers. Numbers which are not
00405   /// provided are set to 0.
00406   ///
00407   /// \return True if the entire string was parsed (9.2), or all
00408   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
00409   /// groups were parsed but extra characters remain at the end.
00410   static bool GetReleaseVersion(const char *Str, unsigned &Major,
00411                                 unsigned &Minor, unsigned &Micro,
00412                                 bool &HadExtra);
00413 };
00414 
00415 } // end namespace driver
00416 } // end namespace clang
00417 
00418 #endif