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