1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef CLANG_DRIVER_DRIVER_H_ 11 #define CLANG_DRIVER_DRIVER_H_ 12 13 #include "clang/Basic/Diagnostic.h" 14 15 #include "clang/Driver/Phases.h" 16 #include "clang/Driver/Types.h" 17 #include "clang/Driver/Util.h" 18 19 #include "llvm/ADT/StringMap.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/Triple.h" 22 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo 23 // lands. 24 #include <list> 25 #include <set> 26 #include <string> 27 28 namespace llvm { 29 template<typename T> class ArrayRef; 30 } 31 namespace clang { 32 namespace driver { 33 class Action; 34 class Arg; 35 class ArgList; 36 class Command; 37 class Compilation; 38 class DerivedArgList; 39 class InputArgList; 40 class InputInfo; 41 class JobAction; 42 class OptTable; 43 class ToolChain; 44 45 /// Driver - Encapsulate logic for constructing compilation processes 46 /// from a set of gcc-driver-like command line arguments. 47 class Driver { 48 OptTable *Opts; 49 50 DiagnosticsEngine &Diags; 51 52 public: 53 // Diag - Forwarding function for diagnostics. Diag(unsigned DiagID)54 DiagnosticBuilder Diag(unsigned DiagID) const { 55 return Diags.Report(DiagID); 56 } 57 58 // FIXME: Privatize once interface is stable. 59 public: 60 /// The name the driver was invoked as. 61 std::string Name; 62 63 /// The path the driver executable was in, as invoked from the 64 /// command line. 65 std::string Dir; 66 67 /// The original path to the clang executable. 68 std::string ClangExecutable; 69 70 /// The path to the installed clang directory, if any. 71 std::string InstalledDir; 72 73 /// The path to the compiler resource directory. 74 std::string ResourceDir; 75 76 /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix' 77 /// functionality. 78 /// FIXME: This type of customization should be removed in favor of the 79 /// universal driver when it is ready. 80 typedef SmallVector<std::string, 4> prefix_list; 81 prefix_list PrefixDirs; 82 83 /// sysroot, if present 84 std::string SysRoot; 85 86 /// If the standard library is used 87 bool UseStdLib; 88 89 /// Default target triple. 90 std::string DefaultTargetTriple; 91 92 /// Default name for linked images (e.g., "a.out"). 93 std::string DefaultImageName; 94 95 /// Driver title to use with help. 96 std::string DriverTitle; 97 98 /// Information about the host which can be overridden by the user. 99 std::string HostBits, HostMachine, HostSystem, HostRelease; 100 101 /// The file to log CC_PRINT_OPTIONS output to, if enabled. 102 const char *CCPrintOptionsFilename; 103 104 /// The file to log CC_PRINT_HEADERS output to, if enabled. 105 const char *CCPrintHeadersFilename; 106 107 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled. 108 const char *CCLogDiagnosticsFilename; 109 110 /// A list of inputs and their types for the given arguments. 111 typedef SmallVector<std::pair<types::ID, const Arg*>, 16> InputList; 112 113 /// Whether the driver should follow g++ like behavior. 114 unsigned CCCIsCXX : 1; 115 116 /// Whether the driver is just the preprocessor. 117 unsigned CCCIsCPP : 1; 118 119 /// Echo commands while executing (in -v style). 120 unsigned CCCEcho : 1; 121 122 /// Only print tool bindings, don't build any jobs. 123 unsigned CCCPrintBindings : 1; 124 125 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to 126 /// CCPrintOptionsFilename or to stderr. 127 unsigned CCPrintOptions : 1; 128 129 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include 130 /// information to CCPrintHeadersFilename or to stderr. 131 unsigned CCPrintHeaders : 1; 132 133 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics 134 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable 135 /// format. 136 unsigned CCLogDiagnostics : 1; 137 138 /// Whether the driver is generating diagnostics for debugging purposes. 139 unsigned CCGenDiagnostics : 1; 140 141 private: 142 /// Name to use when invoking gcc/g++. 143 std::string CCCGenericGCCName; 144 145 /// Whether to check that input files exist when constructing compilation 146 /// jobs. 147 unsigned CheckInputsExist : 1; 148 149 /// Use the clang compiler where possible. 150 unsigned CCCUseClang : 1; 151 152 /// Use clang for handling C++ and Objective-C++ inputs. 153 unsigned CCCUseClangCXX : 1; 154 155 /// Use clang as a preprocessor (clang's preprocessor will still be 156 /// used where an integrated CPP would). 157 unsigned CCCUseClangCPP : 1; 158 159 /// \brief Force use of clang frontend. 160 unsigned ForcedClangUse : 1; 161 162 public: 163 /// Use lazy precompiled headers for PCH support. 164 unsigned CCCUsePCH : 1; 165 166 private: 167 /// Only use clang for the given architectures (only used when 168 /// non-empty). 169 std::set<llvm::Triple::ArchType> CCCClangArchs; 170 171 /// Certain options suppress the 'no input files' warning. 172 bool SuppressMissingInputWarning : 1; 173 174 std::list<std::string> TempFiles; 175 std::list<std::string> ResultFiles; 176 177 /// \brief Cache of all the ToolChains in use by the driver. 178 /// 179 /// This maps from the string representation of a triple to a ToolChain 180 /// created targeting that triple. The driver owns all the ToolChain objects 181 /// stored in it, and will clean them up when torn down. 182 mutable llvm::StringMap<ToolChain *> ToolChains; 183 184 private: 185 /// TranslateInputArgs - Create a new derived argument list from the input 186 /// arguments, after applying the standard argument translations. 187 DerivedArgList *TranslateInputArgs(const InputArgList &Args) const; 188 189 // getFinalPhase - Determine which compilation mode we are in and record 190 // which option we used to determine the final phase. 191 phases::ID getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg = 0) 192 const; 193 194 public: 195 Driver(StringRef _ClangExecutable, 196 StringRef _DefaultTargetTriple, 197 StringRef _DefaultImageName, 198 bool IsProduction, 199 DiagnosticsEngine &_Diags); 200 ~Driver(); 201 202 /// @name Accessors 203 /// @{ 204 205 /// Name to use when invoking gcc/g++. getCCCGenericGCCName()206 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; } 207 208 getOpts()209 const OptTable &getOpts() const { return *Opts; } 210 getDiags()211 const DiagnosticsEngine &getDiags() const { return Diags; } 212 getCheckInputsExist()213 bool getCheckInputsExist() const { return CheckInputsExist; } 214 setCheckInputsExist(bool Value)215 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; } 216 getTitle()217 const std::string &getTitle() { return DriverTitle; } setTitle(std::string Value)218 void setTitle(std::string Value) { DriverTitle = Value; } 219 220 /// \brief Get the path to the main clang executable. getClangProgramPath()221 const char *getClangProgramPath() const { 222 return ClangExecutable.c_str(); 223 } 224 225 /// \brief Get the path to where the clang executable was installed. getInstalledDir()226 const char *getInstalledDir() const { 227 if (!InstalledDir.empty()) 228 return InstalledDir.c_str(); 229 return Dir.c_str(); 230 } setInstalledDir(StringRef Value)231 void setInstalledDir(StringRef Value) { 232 InstalledDir = Value; 233 } 234 shouldForceClangUse()235 bool shouldForceClangUse() const { return ForcedClangUse; } 236 void setForcedClangUse(bool V = true) { ForcedClangUse = V; } 237 238 /// @} 239 /// @name Primary Functionality 240 /// @{ 241 242 /// BuildCompilation - Construct a compilation object for a command 243 /// line argument vector. 244 /// 245 /// \return A compilation, or 0 if none was built for the given 246 /// argument vector. A null return value does not necessarily 247 /// indicate an error condition, the diagnostics should be queried 248 /// to determine if an error occurred. 249 Compilation *BuildCompilation(ArrayRef<const char *> Args); 250 251 /// @name Driver Steps 252 /// @{ 253 254 /// ParseArgStrings - Parse the given list of strings into an 255 /// ArgList. 256 InputArgList *ParseArgStrings(ArrayRef<const char *> Args); 257 258 /// BuildInputs - Construct the list of inputs and their types from 259 /// the given arguments. 260 /// 261 /// \param TC - The default host tool chain. 262 /// \param Args - The input arguments. 263 /// \param Inputs - The list to store the resulting compilation 264 /// inputs onto. 265 void BuildInputs(const ToolChain &TC, const DerivedArgList &Args, 266 InputList &Inputs) const; 267 268 /// BuildActions - Construct the list of actions to perform for the 269 /// given arguments, which are only done for a single architecture. 270 /// 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, const DerivedArgList &Args, 275 const InputList &Inputs, ActionList &Actions) const; 276 277 /// BuildUniversalActions - Construct the list of actions to perform 278 /// for the given arguments, which may require a universal build. 279 /// 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, const DerivedArgList &Args, 284 const InputList &BAInputs, 285 ActionList &Actions) const; 286 287 /// BuildJobs - Bind actions to concrete tools and translate 288 /// arguments to form the list of jobs to run. 289 /// 290 /// \arg C - The compilation that is being built. 291 void BuildJobs(Compilation &C) const; 292 293 /// ExecuteCompilation - Execute the compilation according to the command line 294 /// arguments and return an appropriate exit code. 295 /// 296 /// This routine handles additional processing that must be done in addition 297 /// to just running the subprocesses, for example reporting errors, removing 298 /// temporary files, etc. 299 int ExecuteCompilation(const Compilation &C, 300 const Command *&FailingCommand) const; 301 302 /// generateCompilationDiagnostics - Generate diagnostics information 303 /// including preprocessed source file(s). 304 /// 305 void generateCompilationDiagnostics(Compilation &C, 306 const Command *FailingCommand); 307 308 /// @} 309 /// @name Helper Methods 310 /// @{ 311 312 /// PrintActions - Print the list of actions. 313 void PrintActions(const Compilation &C) const; 314 315 /// PrintHelp - Print the help text. 316 /// 317 /// \param ShowHidden - Show hidden options. 318 void PrintHelp(bool ShowHidden) const; 319 320 /// PrintOptions - Print the list of arguments. 321 void PrintOptions(const ArgList &Args) const; 322 323 /// PrintVersion - Print the driver version. 324 void PrintVersion(const Compilation &C, raw_ostream &OS) const; 325 326 /// GetFilePath - Lookup \arg Name in the list of file search paths. 327 /// 328 /// \arg TC - The tool chain for additional information on 329 /// directories to search. 330 // 331 // FIXME: This should be in CompilationInfo. 332 std::string GetFilePath(const char *Name, const ToolChain &TC) const; 333 334 /// GetProgramPath - Lookup \arg Name in the list of program search 335 /// paths. 336 /// 337 /// \arg TC - The provided tool chain for additional information on 338 /// directories to search. 339 /// 340 /// \arg WantFile - False when searching for an executable file, otherwise 341 /// true. Defaults to false. 342 // 343 // FIXME: This should be in CompilationInfo. 344 std::string GetProgramPath(const char *Name, const ToolChain &TC, 345 bool WantFile = false) const; 346 347 /// HandleImmediateArgs - Handle any arguments which should be 348 /// treated before building actions or binding tools. 349 /// 350 /// \return Whether any compilation should be built for this 351 /// invocation. 352 bool HandleImmediateArgs(const Compilation &C); 353 354 /// ConstructAction - Construct the appropriate action to do for 355 /// \arg Phase on the \arg Input, taking in to account arguments 356 /// like -fsyntax-only or --analyze. 357 Action *ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 358 Action *Input) const; 359 360 361 /// BuildJobsForAction - Construct the jobs to perform for the 362 /// action \arg A. 363 void BuildJobsForAction(Compilation &C, 364 const Action *A, 365 const ToolChain *TC, 366 const char *BoundArch, 367 bool AtTopLevel, 368 const char *LinkingOutput, 369 InputInfo &Result) const; 370 371 /// GetNamedOutputPath - Return the name to use for the output of 372 /// the action \arg JA. The result is appended to the compilation's 373 /// list of temporary or result files, as appropriate. 374 /// 375 /// \param C - The compilation. 376 /// \param JA - The action of interest. 377 /// \param BaseInput - The original input file that this action was 378 /// triggered by. 379 /// \param AtTopLevel - Whether this is a "top-level" action. 380 const char *GetNamedOutputPath(Compilation &C, 381 const JobAction &JA, 382 const char *BaseInput, 383 bool AtTopLevel) const; 384 385 /// GetTemporaryPath - Return the pathname of a temporary file to use 386 /// as part of compilation; the file will have the given prefix and suffix. 387 /// 388 /// GCC goes to extra lengths here to be a bit more robust. 389 std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const; 390 391 /// ShouldUseClangCompilar - Should the clang compiler be used to 392 /// handle this action. 393 bool ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, 394 const llvm::Triple &ArchName) const; 395 396 bool IsUsingLTO(const ArgList &Args) const; 397 398 private: 399 /// \brief Retrieves a ToolChain for a particular target triple. 400 /// 401 /// Will cache ToolChains for the life of the driver object, and create them 402 /// on-demand. 403 const ToolChain &getToolChain(const ArgList &Args, 404 StringRef DarwinArchName = "") const; 405 406 /// @} 407 408 public: 409 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and 410 /// return the grouped values as integers. Numbers which are not 411 /// provided are set to 0. 412 /// 413 /// \return True if the entire string was parsed (9.2), or all 414 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all 415 /// groups were parsed but extra characters remain at the end. 416 static bool GetReleaseVersion(const char *Str, unsigned &Major, 417 unsigned &Minor, unsigned &Micro, 418 bool &HadExtra); 419 }; 420 421 } // end namespace driver 422 } // end namespace clang 423 424 #endif 425