Driver.h revision 03013fa9a0bf1ef4b907f5fec006c8f4000fdd21
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/Util.h"
17
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Triple.h"
20#include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo
21                              // lands.
22#include <list>
23#include <set>
24#include <string>
25
26namespace llvm {
27  class raw_ostream;
28}
29namespace clang {
30namespace driver {
31  class Action;
32  class ArgList;
33  class Compilation;
34  class DerivedArgList;
35  class HostInfo;
36  class InputArgList;
37  class InputInfo;
38  class JobAction;
39  class OptTable;
40  class ToolChain;
41
42/// Driver - Encapsulate logic for constructing compilation processes
43/// from a set of gcc-driver-like command line arguments.
44class Driver {
45  OptTable *Opts;
46
47  Diagnostic &Diags;
48
49public:
50  // Diag - Forwarding function for diagnostics.
51  DiagnosticBuilder Diag(unsigned DiagID) const {
52    return Diags.Report(DiagID);
53  }
54
55  // FIXME: Privatize once interface is stable.
56public:
57  /// The name the driver was invoked as.
58  std::string Name;
59
60  /// The path the driver executable was in, as invoked from the
61  /// command line.
62  std::string Dir;
63
64  /// The original path to the clang executable.
65  std::string ClangExecutable;
66
67  /// The path to the installed clang directory, if any.
68  std::string InstalledDir;
69
70  /// The path to the compiler resource directory.
71  std::string ResourceDir;
72
73  /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix'
74  /// functionality.
75  /// FIXME: This type of customization should be removed in favor of the
76  /// universal driver when it is ready.
77  std::string PrefixDir;
78
79  /// Default host triple.
80  std::string DefaultHostTriple;
81
82  /// Default name for linked images (e.g., "a.out").
83  std::string DefaultImageName;
84
85  /// Driver title to use with help.
86  std::string DriverTitle;
87
88  /// Host information for the platform the driver is running as. This
89  /// will generally be the actual host platform, but not always.
90  const HostInfo *Host;
91
92  /// Information about the host which can be overriden by the user.
93  std::string HostBits, HostMachine, HostSystem, HostRelease;
94
95  /// The file to log CC_PRINT_OPTIONS output to, if enabled.
96  const char *CCPrintOptionsFilename;
97
98  /// Whether the driver should follow g++ like behavior.
99  unsigned CCCIsCXX : 1;
100
101  /// Echo commands while executing (in -v style).
102  unsigned CCCEcho : 1;
103
104  /// Only print tool bindings, don't build any jobs.
105  unsigned CCCPrintBindings : 1;
106
107  /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
108  /// CCPrintOptionsFilename or to stderr.
109  unsigned CCPrintOptions : 1;
110
111private:
112  /// Name to use when calling the generic gcc.
113  std::string CCCGenericGCCName;
114
115  /// Whether to check that input files exist when constructing compilation
116  /// jobs.
117  unsigned CheckInputsExist : 1;
118
119  /// Use the clang compiler where possible.
120  unsigned CCCUseClang : 1;
121
122  /// Use clang for handling C++ and Objective-C++ inputs.
123  unsigned CCCUseClangCXX : 1;
124
125  /// Use clang as a preprocessor (clang's preprocessor will still be
126  /// used where an integrated CPP would).
127  unsigned CCCUseClangCPP : 1;
128
129public:
130  /// Use lazy precompiled headers for PCH support.
131  unsigned CCCUsePCH : 1;
132
133private:
134  /// Only use clang for the given architectures (only used when
135  /// non-empty).
136  std::set<llvm::Triple::ArchType> CCCClangArchs;
137
138  /// Certain options suppress the 'no input files' warning.
139  bool SuppressMissingInputWarning : 1;
140
141  std::list<std::string> TempFiles;
142  std::list<std::string> ResultFiles;
143
144private:
145  /// TranslateInputArgs - Create a new derived argument list from the input
146  /// arguments, after applying the standard argument translations.
147  DerivedArgList *TranslateInputArgs(const InputArgList &Args) const;
148
149public:
150  Driver(llvm::StringRef _ClangExecutable,
151         llvm::StringRef _DefaultHostTriple,
152         llvm::StringRef _DefaultImageName,
153         bool IsProduction, bool CXXIsProduction,
154         Diagnostic &_Diags);
155  ~Driver();
156
157  /// @name Accessors
158  /// @{
159
160  /// Name to use when calling the generic gcc.
161  const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
162
163
164  const OptTable &getOpts() const { return *Opts; }
165
166  const Diagnostic &getDiags() const { return Diags; }
167
168  bool getCheckInputsExist() const { return CheckInputsExist; }
169
170  void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
171
172  const std::string &getTitle() { return DriverTitle; }
173  void setTitle(std::string Value) { DriverTitle = Value; }
174
175  /// \brief Get the path to the main clang executable.
176  const char *getClangProgramPath() const {
177    return ClangExecutable.c_str();
178  }
179
180  /// \brief Get the path to where the clang executable was installed.
181  const char *getInstalledDir() const {
182    if (!InstalledDir.empty())
183      return InstalledDir.c_str();
184    return Dir.c_str();
185  }
186  void setInstalledDir(llvm::StringRef Value) {
187    InstalledDir = Value;
188  }
189
190  /// @}
191  /// @name Primary Functionality
192  /// @{
193
194  /// BuildCompilation - Construct a compilation object for a command
195  /// line argument vector.
196  ///
197  /// \return A compilation, or 0 if none was built for the given
198  /// argument vector. A null return value does not necessarily
199  /// indicate an error condition, the diagnostics should be queried
200  /// to determine if an error occurred.
201  Compilation *BuildCompilation(int argc, const char **argv);
202
203  /// @name Driver Steps
204  /// @{
205
206  /// ParseArgStrings - Parse the given list of strings into an
207  /// ArgList.
208  InputArgList *ParseArgStrings(const char **ArgBegin, const char **ArgEnd);
209
210  /// BuildActions - Construct the list of actions to perform for the
211  /// given arguments, which are only done for a single architecture.
212  ///
213  /// \param TC - The default host tool chain.
214  /// \param Args - The input arguments.
215  /// \param Actions - The list to store the resulting actions onto.
216  void BuildActions(const ToolChain &TC, const ArgList &Args,
217                    ActionList &Actions) const;
218
219  /// BuildUniversalActions - Construct the list of actions to perform
220  /// for the given arguments, which may require a universal build.
221  ///
222  /// \param TC - The default host tool chain.
223  /// \param Args - The input arguments.
224  /// \param Actions - The list to store the resulting actions onto.
225  void BuildUniversalActions(const ToolChain &TC, const ArgList &Args,
226                             ActionList &Actions) const;
227
228  /// BuildJobs - Bind actions to concrete tools and translate
229  /// arguments to form the list of jobs to run.
230  ///
231  /// \arg C - The compilation that is being built.
232  void BuildJobs(Compilation &C) const;
233
234  /// ExecuteCompilation - Execute the compilation according to the command line
235  /// arguments and return an appropriate exit code.
236  ///
237  /// This routine handles additional processing that must be done in addition
238  /// to just running the subprocesses, for example reporting errors, removing
239  /// temporary files, etc.
240  int ExecuteCompilation(const Compilation &C) const;
241
242  /// @}
243  /// @name Helper Methods
244  /// @{
245
246  /// PrintActions - Print the list of actions.
247  void PrintActions(const Compilation &C) const;
248
249  /// PrintHelp - Print the help text.
250  ///
251  /// \param ShowHidden - Show hidden options.
252  void PrintHelp(bool ShowHidden) const;
253
254  /// PrintOptions - Print the list of arguments.
255  void PrintOptions(const ArgList &Args) const;
256
257  /// PrintVersion - Print the driver version.
258  void PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const;
259
260  /// GetFilePath - Lookup \arg Name in the list of file search paths.
261  ///
262  /// \arg TC - The tool chain for additional information on
263  /// directories to search.
264  //
265  // FIXME: This should be in CompilationInfo.
266  std::string GetFilePath(const char *Name, const ToolChain &TC) const;
267
268  /// GetProgramPath - Lookup \arg Name in the list of program search
269  /// paths.
270  ///
271  /// \arg TC - The provided tool chain for additional information on
272  /// directories to search.
273  ///
274  /// \arg WantFile - False when searching for an executable file, otherwise
275  /// true.  Defaults to false.
276  //
277  // FIXME: This should be in CompilationInfo.
278  std::string GetProgramPath(const char *Name, const ToolChain &TC,
279                              bool WantFile = false) const;
280
281  /// HandleImmediateArgs - Handle any arguments which should be
282  /// treated before building actions or binding tools.
283  ///
284  /// \return Whether any compilation should be built for this
285  /// invocation.
286  bool HandleImmediateArgs(const Compilation &C);
287
288  /// ConstructAction - Construct the appropriate action to do for
289  /// \arg Phase on the \arg Input, taking in to account arguments
290  /// like -fsyntax-only or --analyze.
291  Action *ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
292                               Action *Input) const;
293
294
295  /// BuildJobsForAction - Construct the jobs to perform for the
296  /// action \arg A.
297  void BuildJobsForAction(Compilation &C,
298                          const Action *A,
299                          const ToolChain *TC,
300                          const char *BoundArch,
301                          bool AtTopLevel,
302                          const char *LinkingOutput,
303                          InputInfo &Result) const;
304
305  /// GetNamedOutputPath - Return the name to use for the output of
306  /// the action \arg JA. The result is appended to the compilation's
307  /// list of temporary or result files, as appropriate.
308  ///
309  /// \param C - The compilation.
310  /// \param JA - The action of interest.
311  /// \param BaseInput - The original input file that this action was
312  /// triggered by.
313  /// \param AtTopLevel - Whether this is a "top-level" action.
314  const char *GetNamedOutputPath(Compilation &C,
315                                 const JobAction &JA,
316                                 const char *BaseInput,
317                                 bool AtTopLevel) const;
318
319  /// GetTemporaryPath - Return the pathname of a temporary file to
320  /// use as part of compilation; the file will have the given suffix.
321  ///
322  /// GCC goes to extra lengths here to be a bit more robust.
323  std::string GetTemporaryPath(const char *Suffix) const;
324
325  /// GetHostInfo - Construct a new host info object for the given
326  /// host triple.
327  const HostInfo *GetHostInfo(const char *HostTriple) const;
328
329  /// ShouldUseClangCompilar - Should the clang compiler be used to
330  /// handle this action.
331  bool ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
332                              const llvm::Triple &ArchName) const;
333
334  /// @}
335
336  /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
337  /// return the grouped values as integers. Numbers which are not
338  /// provided are set to 0.
339  ///
340  /// \return True if the entire string was parsed (9.2), or all
341  /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
342  /// groups were parsed but extra characters remain at the end.
343  static bool GetReleaseVersion(const char *Str, unsigned &Major,
344                                unsigned &Minor, unsigned &Micro,
345                                bool &HadExtra);
346};
347
348} // end namespace driver
349} // end namespace clang
350
351#endif
352