]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Driver/Driver.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306956, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Driver / Driver.h
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/Action.h"
16 #include "clang/Driver/Phases.h"
17 #include "clang/Driver/ToolChain.h"
18 #include "clang/Driver/Types.h"
19 #include "clang/Driver/Util.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22
23 #include <list>
24 #include <map>
25 #include <string>
26
27 namespace llvm {
28 class Triple;
29
30 namespace opt {
31   class Arg;
32   class ArgList;
33   class DerivedArgList;
34   class InputArgList;
35   class OptTable;
36 }
37 }
38
39 namespace clang {
40
41 namespace vfs {
42 class FileSystem;
43 }
44
45 namespace driver {
46
47   class Command;
48   class Compilation;
49   class InputInfo;
50   class JobList;
51   class JobAction;
52   class SanitizerArgs;
53   class ToolChain;
54
55 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
56 enum LTOKind {
57   LTOK_None,
58   LTOK_Full,
59   LTOK_Thin,
60   LTOK_Unknown
61 };
62
63 /// Driver - Encapsulate logic for constructing compilation processes
64 /// from a set of gcc-driver-like command line arguments.
65 class Driver {
66   std::unique_ptr<llvm::opt::OptTable> Opts;
67
68   DiagnosticsEngine &Diags;
69
70   IntrusiveRefCntPtr<vfs::FileSystem> VFS;
71
72   enum DriverMode {
73     GCCMode,
74     GXXMode,
75     CPPMode,
76     CLMode
77   } Mode;
78
79   enum SaveTempsMode {
80     SaveTempsNone,
81     SaveTempsCwd,
82     SaveTempsObj
83   } SaveTemps;
84
85   enum BitcodeEmbedMode {
86     EmbedNone,
87     EmbedMarker,
88     EmbedBitcode
89   } BitcodeEmbed;
90
91   /// LTO mode selected via -f(no-)?lto(=.*)? options.
92   LTOKind LTOMode;
93
94 public:
95   enum OpenMPRuntimeKind {
96     /// An unknown OpenMP runtime. We can't generate effective OpenMP code
97     /// without knowing what runtime to target.
98     OMPRT_Unknown,
99
100     /// The LLVM OpenMP runtime. When completed and integrated, this will become
101     /// the default for Clang.
102     OMPRT_OMP,
103
104     /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
105     /// this runtime but can swallow the pragmas, and find and link against the
106     /// runtime library itself.
107     OMPRT_GOMP,
108
109     /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
110     /// OpenMP runtime. We support this mode for users with existing
111     /// dependencies on this runtime library name.
112     OMPRT_IOMP5
113   };
114
115   // Diag - Forwarding function for diagnostics.
116   DiagnosticBuilder Diag(unsigned DiagID) const {
117     return Diags.Report(DiagID);
118   }
119
120   // FIXME: Privatize once interface is stable.
121 public:
122   /// The name the driver was invoked as.
123   std::string Name;
124
125   /// The path the driver executable was in, as invoked from the
126   /// command line.
127   std::string Dir;
128
129   /// The original path to the clang executable.
130   std::string ClangExecutable;
131
132   /// The path to the installed clang directory, if any.
133   std::string InstalledDir;
134
135   /// The path to the compiler resource directory.
136   std::string ResourceDir;
137
138   /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
139   /// functionality.
140   /// FIXME: This type of customization should be removed in favor of the
141   /// universal driver when it is ready.
142   typedef SmallVector<std::string, 4> prefix_list;
143   prefix_list PrefixDirs;
144
145   /// sysroot, if present
146   std::string SysRoot;
147
148   /// Dynamic loader prefix, if present
149   std::string DyldPrefix;
150
151   /// If the standard library is used
152   bool UseStdLib;
153
154   /// Driver title to use with help.
155   std::string DriverTitle;
156
157   /// Information about the host which can be overridden by the user.
158   std::string HostBits, HostMachine, HostSystem, HostRelease;
159
160   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
161   const char *CCPrintOptionsFilename;
162
163   /// The file to log CC_PRINT_HEADERS output to, if enabled.
164   const char *CCPrintHeadersFilename;
165
166   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
167   const char *CCLogDiagnosticsFilename;
168
169   /// A list of inputs and their types for the given arguments.
170   typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
171       InputList;
172
173   /// Whether the driver should follow g++ like behavior.
174   bool CCCIsCXX() const { return Mode == GXXMode; }
175
176   /// Whether the driver is just the preprocessor.
177   bool CCCIsCPP() const { return Mode == CPPMode; }
178
179   /// Whether the driver should follow gcc like behavior.
180   bool CCCIsCC() const { return Mode == GCCMode; }
181
182   /// Whether the driver should follow cl.exe like behavior.
183   bool IsCLMode() const { return Mode == CLMode; }
184
185   /// Only print tool bindings, don't build any jobs.
186   unsigned CCCPrintBindings : 1;
187
188   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
189   /// CCPrintOptionsFilename or to stderr.
190   unsigned CCPrintOptions : 1;
191
192   /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
193   /// information to CCPrintHeadersFilename or to stderr.
194   unsigned CCPrintHeaders : 1;
195
196   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
197   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
198   /// format.
199   unsigned CCLogDiagnostics : 1;
200
201   /// Whether the driver is generating diagnostics for debugging purposes.
202   unsigned CCGenDiagnostics : 1;
203
204 private:
205   /// Default target triple.
206   std::string DefaultTargetTriple;
207
208   /// Name to use when invoking gcc/g++.
209   std::string CCCGenericGCCName;
210
211   /// Whether to check that input files exist when constructing compilation
212   /// jobs.
213   unsigned CheckInputsExist : 1;
214
215 public:
216   /// Use lazy precompiled headers for PCH support.
217   unsigned CCCUsePCH : 1;
218
219   /// Force clang to emit reproducer for driver invocation. This is enabled
220   /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
221   /// or when using the -gen-reproducer driver flag.
222   unsigned GenReproducer : 1;
223
224 private:
225   /// Certain options suppress the 'no input files' warning.
226   unsigned SuppressMissingInputWarning : 1;
227
228   std::list<std::string> TempFiles;
229   std::list<std::string> ResultFiles;
230
231   /// \brief Cache of all the ToolChains in use by the driver.
232   ///
233   /// This maps from the string representation of a triple to a ToolChain
234   /// created targeting that triple. The driver owns all the ToolChain objects
235   /// stored in it, and will clean them up when torn down.
236   mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
237
238 private:
239   /// TranslateInputArgs - Create a new derived argument list from the input
240   /// arguments, after applying the standard argument translations.
241   llvm::opt::DerivedArgList *
242   TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
243
244   // getFinalPhase - Determine which compilation mode we are in and record 
245   // which option we used to determine the final phase.
246   phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
247                            llvm::opt::Arg **FinalPhaseArg = nullptr) const;
248
249   // Before executing jobs, sets up response files for commands that need them.
250   void setUpResponseFiles(Compilation &C, Command &Cmd);
251
252   void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
253                                  SmallVectorImpl<std::string> &Names) const;
254
255   /// \brief Find the appropriate .crash diagonostic file for the child crash
256   /// under this driver and copy it out to a temporary destination with the
257   /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
258   /// directory for the user to look at.
259   ///
260   /// \param ReproCrashFilename The file path to copy the .crash to.
261   /// \param CrashDiagDir       The suggested directory for the user to look at
262   ///                           in case the search or copy fails.
263   ///
264   /// \returns If the .crash is found and successfully copied return true,
265   /// otherwise false and return the suggested directory in \p CrashDiagDir.
266   bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
267                               SmallString<128> &CrashDiagDir);
268
269 public:
270   Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
271          DiagnosticsEngine &Diags,
272          IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
273
274   /// @name Accessors
275   /// @{
276
277   /// Name to use when invoking gcc/g++.
278   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
279
280   const llvm::opt::OptTable &getOpts() const { return *Opts; }
281
282   const DiagnosticsEngine &getDiags() const { return Diags; }
283
284   vfs::FileSystem &getVFS() const { return *VFS; }
285
286   bool getCheckInputsExist() const { return CheckInputsExist; }
287
288   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
289
290   const std::string &getTitle() { return DriverTitle; }
291   void setTitle(std::string Value) { DriverTitle = std::move(Value); }
292
293   /// \brief Get the path to the main clang executable.
294   const char *getClangProgramPath() const {
295     return ClangExecutable.c_str();
296   }
297
298   /// \brief Get the path to where the clang executable was installed.
299   const char *getInstalledDir() const {
300     if (!InstalledDir.empty())
301       return InstalledDir.c_str();
302     return Dir.c_str();
303   }
304   void setInstalledDir(StringRef Value) {
305     InstalledDir = Value;
306   }
307
308   bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
309   bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
310
311   bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
312   bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
313   bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
314
315   /// Compute the desired OpenMP runtime from the flags provided.
316   OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
317
318   /// @}
319   /// @name Primary Functionality
320   /// @{
321
322   /// CreateOffloadingDeviceToolChains - create all the toolchains required to
323   /// support offloading devices given the programming models specified in the
324   /// current compilation. Also, update the host tool chain kind accordingly.
325   void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
326
327   /// BuildCompilation - Construct a compilation object for a command
328   /// line argument vector.
329   ///
330   /// \return A compilation, or 0 if none was built for the given
331   /// argument vector. A null return value does not necessarily
332   /// indicate an error condition, the diagnostics should be queried
333   /// to determine if an error occurred.
334   Compilation *BuildCompilation(ArrayRef<const char *> Args);
335
336   /// @name Driver Steps
337   /// @{
338
339   /// ParseDriverMode - Look for and handle the driver mode option in Args.
340   void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
341
342   /// ParseArgStrings - Parse the given list of strings into an
343   /// ArgList.
344   llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
345                                           bool &ContainsError);
346
347   /// BuildInputs - Construct the list of inputs and their types from 
348   /// the given arguments.
349   ///
350   /// \param TC - The default host tool chain.
351   /// \param Args - The input arguments.
352   /// \param Inputs - The list to store the resulting compilation 
353   /// inputs onto.
354   void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
355                    InputList &Inputs) const;
356
357   /// BuildActions - Construct the list of actions to perform for the
358   /// given arguments, which are only done for a single architecture.
359   ///
360   /// \param C - The compilation that is being built.
361   /// \param Args - The input arguments.
362   /// \param Actions - The list to store the resulting actions onto.
363   void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
364                     const InputList &Inputs, ActionList &Actions) const;
365
366   /// BuildUniversalActions - Construct the list of actions to perform
367   /// for the given arguments, which may require a universal build.
368   ///
369   /// \param C - The compilation that is being built.
370   /// \param TC - The default host tool chain.
371   void BuildUniversalActions(Compilation &C, const ToolChain &TC,
372                              const InputList &BAInputs) const;
373
374   /// BuildJobs - Bind actions to concrete tools and translate
375   /// arguments to form the list of jobs to run.
376   ///
377   /// \param C - The compilation that is being built.
378   void BuildJobs(Compilation &C) const;
379
380   /// ExecuteCompilation - Execute the compilation according to the command line
381   /// arguments and return an appropriate exit code.
382   ///
383   /// This routine handles additional processing that must be done in addition
384   /// to just running the subprocesses, for example reporting errors, setting
385   /// up response files, removing temporary files, etc.
386   int ExecuteCompilation(Compilation &C,
387      SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
388
389   /// generateCompilationDiagnostics - Generate diagnostics information 
390   /// including preprocessed source file(s).
391   /// 
392   void generateCompilationDiagnostics(Compilation &C,
393                                       const Command &FailingCommand);
394
395   /// @}
396   /// @name Helper Methods
397   /// @{
398
399   /// PrintActions - Print the list of actions.
400   void PrintActions(const Compilation &C) const;
401
402   /// PrintHelp - Print the help text.
403   ///
404   /// \param ShowHidden - Show hidden options.
405   void PrintHelp(bool ShowHidden) const;
406
407   /// PrintVersion - Print the driver version.
408   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
409
410   /// GetFilePath - Lookup \p Name in the list of file search paths.
411   ///
412   /// \param TC - The tool chain for additional information on
413   /// directories to search.
414   //
415   // FIXME: This should be in CompilationInfo.
416   std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
417
418   /// GetProgramPath - Lookup \p Name in the list of program search paths.
419   ///
420   /// \param TC - The provided tool chain for additional information on
421   /// directories to search.
422   //
423   // FIXME: This should be in CompilationInfo.
424   std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
425
426   /// HandleImmediateArgs - Handle any arguments which should be
427   /// treated before building actions or binding tools.
428   ///
429   /// \return Whether any compilation should be built for this
430   /// invocation.
431   bool HandleImmediateArgs(const Compilation &C);
432
433   /// ConstructAction - Construct the appropriate action to do for
434   /// \p Phase on the \p Input, taking in to account arguments
435   /// like -fsyntax-only or --analyze.
436   Action *ConstructPhaseAction(Compilation &C, const llvm::opt::ArgList &Args,
437                                phases::ID Phase, Action *Input) const;
438
439   /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
440   /// return an InputInfo for the result of running \p A.  Will only construct
441   /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
442   InputInfo
443   BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
444                      StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
445                      const char *LinkingOutput,
446                      std::map<std::pair<const Action *, std::string>, InputInfo>
447                          &CachedResults,
448                      Action::OffloadKind TargetDeviceOffloadKind) const;
449
450   /// Returns the default name for linked images (e.g., "a.out").
451   const char *getDefaultImageName() const;
452
453   /// GetNamedOutputPath - Return the name to use for the output of
454   /// the action \p JA. The result is appended to the compilation's
455   /// list of temporary or result files, as appropriate.
456   ///
457   /// \param C - The compilation.
458   /// \param JA - The action of interest.
459   /// \param BaseInput - The original input file that this action was
460   /// triggered by.
461   /// \param BoundArch - The bound architecture. 
462   /// \param AtTopLevel - Whether this is a "top-level" action.
463   /// \param MultipleArchs - Whether multiple -arch options were supplied.
464   /// \param NormalizedTriple - The normalized triple of the relevant target.
465   const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
466                                  const char *BaseInput, StringRef BoundArch,
467                                  bool AtTopLevel, bool MultipleArchs,
468                                  StringRef NormalizedTriple) const;
469
470   /// GetTemporaryPath - Return the pathname of a temporary file to use 
471   /// as part of compilation; the file will have the given prefix and suffix.
472   ///
473   /// GCC goes to extra lengths here to be a bit more robust.
474   std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
475
476   /// Return the pathname of the pch file in clang-cl mode.
477   std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
478
479   /// ShouldUseClangCompiler - Should the clang compiler be used to
480   /// handle this action.
481   bool ShouldUseClangCompiler(const JobAction &JA) const;
482
483   /// Returns true if we are performing any kind of LTO.
484   bool isUsingLTO() const { return LTOMode != LTOK_None; }
485
486   /// Get the specific kind of LTO being performed.
487   LTOKind getLTOMode() const { return LTOMode; }
488
489 private:
490   /// Set the driver mode (cl, gcc, etc) from an option string of the form
491   /// --driver-mode=<mode>.
492   void setDriverModeFromOption(StringRef Opt);
493
494   /// Parse the \p Args list for LTO options and record the type of LTO
495   /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
496   void setLTOMode(const llvm::opt::ArgList &Args);
497
498   /// \brief Retrieves a ToolChain for a particular \p Target triple.
499   ///
500   /// Will cache ToolChains for the life of the driver object, and create them
501   /// on-demand.
502   const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
503                                 const llvm::Triple &Target) const;
504
505   /// @}
506
507   /// \brief Get bitmasks for which option flags to include and exclude based on
508   /// the driver mode.
509   std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
510
511   /// Helper used in BuildJobsForAction.  Doesn't use the cache when building
512   /// jobs specifically for the given action, but will use the cache when
513   /// building jobs for the Action's inputs.
514   InputInfo BuildJobsForActionNoCache(
515       Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
516       bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
517       std::map<std::pair<const Action *, std::string>, InputInfo>
518           &CachedResults,
519       Action::OffloadKind TargetDeviceOffloadKind) const;
520
521 public:
522   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
523   /// return the grouped values as integers. Numbers which are not
524   /// provided are set to 0.
525   ///
526   /// \return True if the entire string was parsed (9.2), or all
527   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
528   /// groups were parsed but extra characters remain at the end.
529   static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
530                                 unsigned &Micro, bool &HadExtra);
531
532   /// Parse digits from a string \p Str and fulfill \p Digits with
533   /// the parsed numbers. This method assumes that the max number of
534   /// digits to look for is equal to Digits.size().
535   ///
536   /// \return True if the entire string was parsed and there are
537   /// no extra characters remaining at the end.
538   static bool GetReleaseVersion(StringRef Str,
539                                 MutableArrayRef<unsigned> Digits);
540 };
541
542 /// \return True if the last defined optimization level is -Ofast.
543 /// And False otherwise.
544 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
545
546 } // end namespace driver
547 } // end namespace clang
548
549 #endif