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 LLVM_CLANG_DRIVER_DRIVER_H 11 #define LLVM_CLANG_DRIVER_DRIVER_H 12 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 22 #include <memory> 23 // lands. 24 #include <list> 25 #include <set> 26 #include <string> 27 28 namespace llvm { 29 namespace opt { 30 class Arg; 31 class ArgList; 32 class DerivedArgList; 33 class InputArgList; 34 class OptTable; 35 } 36 } 37 38 namespace clang { 39 namespace driver { 40 41 class Action; 42 class Command; 43 class Compilation; 44 class InputInfo; 45 class Job; 46 class JobAction; 47 class SanitizerArgs; 48 class ToolChain; 49 50 /// Driver - Encapsulate logic for constructing compilation processes 51 /// from a set of gcc-driver-like command line arguments. 52 class Driver { 53 llvm::opt::OptTable *Opts; 54 55 DiagnosticsEngine &Diags; 56 57 enum DriverMode { 58 GCCMode, 59 GXXMode, 60 CPPMode, 61 CLMode 62 } Mode; 63 64 public: 65 // Diag - Forwarding function for diagnostics. Diag(unsigned DiagID)66 DiagnosticBuilder Diag(unsigned DiagID) const { 67 return Diags.Report(DiagID); 68 } 69 70 // FIXME: Privatize once interface is stable. 71 public: 72 /// The name the driver was invoked as. 73 std::string Name; 74 75 /// The path the driver executable was in, as invoked from the 76 /// command line. 77 std::string Dir; 78 79 /// The original path to the clang executable. 80 std::string ClangExecutable; 81 82 /// The path to the installed clang directory, if any. 83 std::string InstalledDir; 84 85 /// The path to the compiler resource directory. 86 std::string ResourceDir; 87 88 /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix' 89 /// functionality. 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; 94 95 /// sysroot, if present 96 std::string SysRoot; 97 98 /// Dynamic loader prefix, if present 99 std::string DyldPrefix; 100 101 /// If the standard library is used 102 bool UseStdLib; 103 104 /// Default target triple. 105 std::string DefaultTargetTriple; 106 107 /// Driver title to use with help. 108 std::string DriverTitle; 109 110 /// Information about the host which can be overridden by the user. 111 std::string HostBits, HostMachine, HostSystem, HostRelease; 112 113 /// The file to log CC_PRINT_OPTIONS output to, if enabled. 114 const char *CCPrintOptionsFilename; 115 116 /// The file to log CC_PRINT_HEADERS output to, if enabled. 117 const char *CCPrintHeadersFilename; 118 119 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled. 120 const char *CCLogDiagnosticsFilename; 121 122 /// A list of inputs and their types for the given arguments. 123 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16> 124 InputList; 125 126 /// Whether the driver should follow g++ like behavior. CCCIsCXX()127 bool CCCIsCXX() const { return Mode == GXXMode; } 128 129 /// Whether the driver is just the preprocessor. CCCIsCPP()130 bool CCCIsCPP() const { return Mode == CPPMode; } 131 132 /// Whether the driver should follow cl.exe like behavior. IsCLMode()133 bool IsCLMode() const { return Mode == CLMode; } 134 135 /// Only print tool bindings, don't build any jobs. 136 unsigned CCCPrintBindings : 1; 137 138 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to 139 /// CCPrintOptionsFilename or to stderr. 140 unsigned CCPrintOptions : 1; 141 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; 145 146 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics 147 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable 148 /// format. 149 unsigned CCLogDiagnostics : 1; 150 151 /// Whether the driver is generating diagnostics for debugging purposes. 152 unsigned CCGenDiagnostics : 1; 153 154 private: 155 /// Name to use when invoking gcc/g++. 156 std::string CCCGenericGCCName; 157 158 /// Whether to check that input files exist when constructing compilation 159 /// jobs. 160 unsigned CheckInputsExist : 1; 161 162 public: 163 /// Use lazy precompiled headers for PCH support. 164 unsigned CCCUsePCH : 1; 165 166 private: 167 /// Certain options suppress the 'no input files' warning. 168 bool SuppressMissingInputWarning : 1; 169 170 std::list<std::string> TempFiles; 171 std::list<std::string> ResultFiles; 172 173 /// \brief Cache of all the ToolChains in use by the driver. 174 /// 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; 179 180 private: 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; 185 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; 190 191 // Before executing jobs, sets up response files for commands that need them. 192 void setUpResponseFiles(Compilation &C, Job &J); 193 194 void generatePrefixedToolNames(const char *Tool, const ToolChain &TC, 195 SmallVectorImpl<std::string> &Names) const; 196 197 public: 198 Driver(StringRef _ClangExecutable, 199 StringRef _DefaultTargetTriple, 200 DiagnosticsEngine &_Diags); 201 ~Driver(); 202 203 /// @name Accessors 204 /// @{ 205 206 /// Name to use when invoking gcc/g++. getCCCGenericGCCName()207 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; } 208 getOpts()209 const llvm::opt::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 235 /// @} 236 /// @name Primary Functionality 237 /// @{ 238 239 /// BuildCompilation - Construct a compilation object for a command 240 /// line argument vector. 241 /// 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); 247 248 /// @name Driver Steps 249 /// @{ 250 251 /// ParseDriverMode - Look for and handle the driver mode option in Args. 252 void ParseDriverMode(ArrayRef<const char *> Args); 253 254 /// ParseArgStrings - Parse the given list of strings into an 255 /// ArgList. 256 llvm::opt::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, llvm::opt::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, llvm::opt::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, 284 llvm::opt::DerivedArgList &Args, 285 const InputList &BAInputs, 286 ActionList &Actions) const; 287 288 /// BuildJobs - Bind actions to concrete tools and translate 289 /// arguments to form the list of jobs to run. 290 /// 291 /// \param C - The compilation that is being built. 292 void BuildJobs(Compilation &C) const; 293 294 /// ExecuteCompilation - Execute the compilation according to the command line 295 /// arguments and return an appropriate exit code. 296 /// 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); 302 303 /// generateCompilationDiagnostics - Generate diagnostics information 304 /// including preprocessed source file(s). 305 /// 306 void generateCompilationDiagnostics(Compilation &C, 307 const Command &FailingCommand); 308 309 /// @} 310 /// @name Helper Methods 311 /// @{ 312 313 /// PrintActions - Print the list of actions. 314 void PrintActions(const Compilation &C) const; 315 316 /// PrintHelp - Print the help text. 317 /// 318 /// \param ShowHidden - Show hidden options. 319 void PrintHelp(bool ShowHidden) const; 320 321 /// PrintVersion - Print the driver version. 322 void PrintVersion(const Compilation &C, raw_ostream &OS) const; 323 324 /// GetFilePath - Lookup \p Name in the list of file search paths. 325 /// 326 /// \param TC - The tool chain for additional information on 327 /// directories to search. 328 // 329 // FIXME: This should be in CompilationInfo. 330 std::string GetFilePath(const char *Name, const ToolChain &TC) const; 331 332 /// GetProgramPath - Lookup \p Name in the list of program search paths. 333 /// 334 /// \param TC - The provided tool chain for additional information on 335 /// directories to search. 336 // 337 // FIXME: This should be in CompilationInfo. 338 std::string GetProgramPath(const char *Name, const ToolChain &TC) const; 339 340 /// HandleImmediateArgs - Handle any arguments which should be 341 /// treated before building actions or binding tools. 342 /// 343 /// \return Whether any compilation should be built for this 344 /// invocation. 345 bool HandleImmediateArgs(const Compilation &C); 346 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; 353 354 /// BuildJobsForAction - Construct the jobs to perform for the 355 /// action \p A. 356 void BuildJobsForAction(Compilation &C, 357 const Action *A, 358 const ToolChain *TC, 359 const char *BoundArch, 360 bool AtTopLevel, 361 bool MultipleArchs, 362 const char *LinkingOutput, 363 InputInfo &Result) const; 364 365 /// Returns the default name for linked images (e.g., "a.out"). 366 const char *getDefaultImageName() const; 367 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. 371 /// 372 /// \param C - The compilation. 373 /// \param JA - The action of interest. 374 /// \param BaseInput - The original input file that this action was 375 /// triggered by. 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, 380 const JobAction &JA, 381 const char *BaseInput, 382 const char *BoundArch, 383 bool AtTopLevel, 384 bool MultipleArchs) const; 385 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. 388 /// 389 /// GCC goes to extra lengths here to be a bit more robust. 390 std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const; 391 392 /// ShouldUseClangCompiler - Should the clang compiler be used to 393 /// handle this action. 394 bool ShouldUseClangCompiler(const JobAction &JA) const; 395 396 bool IsUsingLTO(const llvm::opt::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 llvm::opt::ArgList &Args, 404 StringRef DarwinArchName = "") const; 405 406 /// @} 407 408 /// \brief Get bitmasks for which option flags to include and exclude based on 409 /// the driver mode. 410 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const; 411 412 public: 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. 416 /// 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, 422 bool &HadExtra); 423 }; 424 425 /// \return True if the last defined optimization level is -Ofast. 426 /// And False otherwise. 427 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args); 428 429 } // end namespace driver 430 } // end namespace clang 431 432 #endif 433