clang  3.8.0
CompilerInvocation.cpp
Go to the documentation of this file.
1 //===--- CompilerInvocation.cpp -------------------------------------------===//
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 
11 #include "clang/Basic/Builtins.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Config/config.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/Util.h"
21 #include "clang/Frontend/Utils.h"
25 #include "llvm/ADT/Hashing.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/Linker/Linker.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Option/Option.h"
36 #include "llvm/Support/CodeGen.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include <atomic>
44 #include <memory>
45 #include <sys/stat.h>
46 #include <system_error>
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // Initialization.
51 //===----------------------------------------------------------------------===//
52 
54  : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
55  DiagnosticOpts(new DiagnosticOptions()),
56  HeaderSearchOpts(new HeaderSearchOptions()),
57  PreprocessorOpts(new PreprocessorOptions()) {}
58 
61  LangOpts(new LangOptions(*X.getLangOpts())),
62  TargetOpts(new TargetOptions(X.getTargetOpts())),
63  DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
64  HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
65  PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
66 
68 
69 //===----------------------------------------------------------------------===//
70 // Deserialization (from args)
71 //===----------------------------------------------------------------------===//
72 
73 using namespace clang::driver;
74 using namespace clang::driver::options;
75 using namespace llvm::opt;
76 
77 //
78 
79 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
80  DiagnosticsEngine &Diags) {
81  unsigned DefaultOpt = 0;
82  if (IK == IK_OpenCL && !Args.hasArg(OPT_cl_opt_disable))
83  DefaultOpt = 2;
84 
85  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
86  if (A->getOption().matches(options::OPT_O0))
87  return 0;
88 
89  if (A->getOption().matches(options::OPT_Ofast))
90  return 3;
91 
92  assert (A->getOption().matches(options::OPT_O));
93 
94  StringRef S(A->getValue());
95  if (S == "s" || S == "z" || S.empty())
96  return 2;
97 
98  return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
99  }
100 
101  return DefaultOpt;
102 }
103 
104 static unsigned getOptimizationLevelSize(ArgList &Args) {
105  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
106  if (A->getOption().matches(options::OPT_O)) {
107  switch (A->getValue()[0]) {
108  default:
109  return 0;
110  case 's':
111  return 1;
112  case 'z':
113  return 2;
114  }
115  }
116  }
117  return 0;
118 }
119 
120 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
121  OptSpecifier GroupWithValue,
122  std::vector<std::string> &Diagnostics) {
123  for (Arg *A : Args.filtered(Group)) {
124  if (A->getOption().getKind() == Option::FlagClass) {
125  // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
126  // its name (minus the "W" or "R" at the beginning) to the warning list.
127  Diagnostics.push_back(A->getOption().getName().drop_front(1));
128  } else if (A->getOption().matches(GroupWithValue)) {
129  // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
130  Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
131  } else {
132  // Otherwise, add its value (for OPT_W_Joined and similar).
133  for (const char *Arg : A->getValues())
134  Diagnostics.emplace_back(Arg);
135  }
136  }
137 }
138 
139 static void getAllNoBuiltinFuncValues(ArgList &Args,
140  std::vector<std::string> &Funcs) {
142  for (const auto &Arg : Args) {
143  const Option &O = Arg->getOption();
144  if (O.matches(options::OPT_fno_builtin_)) {
145  const char *FuncName = Arg->getValue();
146  if (Builtin::Context::isBuiltinFunc(FuncName))
147  Values.push_back(FuncName);
148  }
149  }
150  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
151 }
152 
153 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
154  DiagnosticsEngine &Diags) {
155  using namespace options;
156  bool Success = true;
157  if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
158  StringRef Name = A->getValue();
159  AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
160 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
161  .Case(CMDFLAG, NAME##Model)
162 #include "clang/StaticAnalyzer/Core/Analyses.def"
163  .Default(NumStores);
164  if (Value == NumStores) {
165  Diags.Report(diag::err_drv_invalid_value)
166  << A->getAsString(Args) << Name;
167  Success = false;
168  } else {
169  Opts.AnalysisStoreOpt = Value;
170  }
171  }
172 
173  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
174  StringRef Name = A->getValue();
175  AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
176 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
177  .Case(CMDFLAG, NAME##Model)
178 #include "clang/StaticAnalyzer/Core/Analyses.def"
179  .Default(NumConstraints);
180  if (Value == NumConstraints) {
181  Diags.Report(diag::err_drv_invalid_value)
182  << A->getAsString(Args) << Name;
183  Success = false;
184  } else {
186  }
187  }
188 
189  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
190  StringRef Name = A->getValue();
191  AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
192 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
193  .Case(CMDFLAG, PD_##NAME)
194 #include "clang/StaticAnalyzer/Core/Analyses.def"
195  .Default(NUM_ANALYSIS_DIAG_CLIENTS);
196  if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
197  Diags.Report(diag::err_drv_invalid_value)
198  << A->getAsString(Args) << Name;
199  Success = false;
200  } else {
201  Opts.AnalysisDiagOpt = Value;
202  }
203  }
204 
205  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
206  StringRef Name = A->getValue();
207  AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
208 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
209  .Case(CMDFLAG, NAME)
210 #include "clang/StaticAnalyzer/Core/Analyses.def"
211  .Default(NumPurgeModes);
212  if (Value == NumPurgeModes) {
213  Diags.Report(diag::err_drv_invalid_value)
214  << A->getAsString(Args) << Name;
215  Success = false;
216  } else {
217  Opts.AnalysisPurgeOpt = Value;
218  }
219  }
220 
221  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
222  StringRef Name = A->getValue();
223  AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
224 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
225  .Case(CMDFLAG, NAME)
226 #include "clang/StaticAnalyzer/Core/Analyses.def"
227  .Default(NumInliningModes);
228  if (Value == NumInliningModes) {
229  Diags.Report(diag::err_drv_invalid_value)
230  << A->getAsString(Args) << Name;
231  Success = false;
232  } else {
233  Opts.InliningMode = Value;
234  }
235  }
236 
237  Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
238  Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
239 
241  Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
243  Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
244  Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
245  Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
246  Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
247  Opts.AnalyzeNestedBlocks =
248  Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
249  Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
250  Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
251  Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
252  Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
253  Opts.maxBlockVisitOnPath =
254  getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
255  Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
256  Opts.InlineMaxStackDepth =
257  getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
258  Opts.InlineMaxStackDepth, Diags);
259 
260  Opts.CheckersControlList.clear();
261  for (const Arg *A :
262  Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
263  A->claim();
264  bool enable = (A->getOption().getID() == OPT_analyzer_checker);
265  // We can have a list of comma separated checker names, e.g:
266  // '-analyzer-checker=cocoa,unix'
267  StringRef checkerList = A->getValue();
268  SmallVector<StringRef, 4> checkers;
269  checkerList.split(checkers, ",");
270  for (StringRef checker : checkers)
271  Opts.CheckersControlList.emplace_back(checker, enable);
272  }
273 
274  // Go through the analyzer configuration options.
275  for (const Arg *A : Args.filtered(OPT_analyzer_config)) {
276  A->claim();
277  // We can have a list of comma separated config names, e.g:
278  // '-analyzer-config key1=val1,key2=val2'
279  StringRef configList = A->getValue();
280  SmallVector<StringRef, 4> configVals;
281  configList.split(configVals, ",");
282  for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
283  StringRef key, val;
284  std::tie(key, val) = configVals[i].split("=");
285  if (val.empty()) {
286  Diags.Report(SourceLocation(),
287  diag::err_analyzer_config_no_value) << configVals[i];
288  Success = false;
289  break;
290  }
291  if (val.find('=') != StringRef::npos) {
292  Diags.Report(SourceLocation(),
293  diag::err_analyzer_config_multiple_values)
294  << configVals[i];
295  Success = false;
296  break;
297  }
298  Opts.Config[key] = val;
299  }
300  }
301 
302  return Success;
303 }
304 
305 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
306  Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
307  Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
308  return true;
309 }
310 
311 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
312  Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
313  Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
314 }
315 
316 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
317  if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
318  StringRef Value = A->getValue();
319  if (Value == "small" || Value == "kernel" || Value == "medium" ||
320  Value == "large")
321  return Value;
322  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
323  }
324  return "default";
325 }
326 
327 /// \brief Create a new Regex instance out of the string value in \p RpassArg.
328 /// It returns a pointer to the newly generated Regex instance.
329 static std::shared_ptr<llvm::Regex>
331  Arg *RpassArg) {
332  StringRef Val = RpassArg->getValue();
333  std::string RegexError;
334  std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
335  if (!Pattern->isValid(RegexError)) {
336  Diags.Report(diag::err_drv_optimization_remark_pattern)
337  << RegexError << RpassArg->getAsString(Args);
338  Pattern.reset();
339  }
340  return Pattern;
341 }
342 
343 static bool parseDiagnosticLevelMask(StringRef FlagName,
344  const std::vector<std::string> &Levels,
345  DiagnosticsEngine *Diags,
346  DiagnosticLevelMask &M) {
347  bool Success = true;
348  for (const auto &Level : Levels) {
349  DiagnosticLevelMask const PM =
350  llvm::StringSwitch<DiagnosticLevelMask>(Level)
351  .Case("note", DiagnosticLevelMask::Note)
352  .Case("remark", DiagnosticLevelMask::Remark)
353  .Case("warning", DiagnosticLevelMask::Warning)
354  .Case("error", DiagnosticLevelMask::Error)
355  .Default(DiagnosticLevelMask::None);
356  if (PM == DiagnosticLevelMask::None) {
357  Success = false;
358  if (Diags)
359  Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
360  }
361  M = M | PM;
362  }
363  return Success;
364 }
365 
366 static void parseSanitizerKinds(StringRef FlagName,
367  const std::vector<std::string> &Sanitizers,
368  DiagnosticsEngine &Diags, SanitizerSet &S) {
369  for (const auto &Sanitizer : Sanitizers) {
370  SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
371  if (K == 0)
372  Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
373  else
374  S.set(K, true);
375  }
376 }
377 
378 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
379  DiagnosticsEngine &Diags,
380  const TargetOptions &TargetOpts) {
381  using namespace options;
382  bool Success = true;
383  llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
384 
385  unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
386  // TODO: This could be done in Driver
387  unsigned MaxOptLevel = 3;
388  if (OptimizationLevel > MaxOptLevel) {
389  // If the optimization level is not supported, fall back on the default
390  // optimization
391  Diags.Report(diag::warn_drv_optimization_value)
392  << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
393  OptimizationLevel = MaxOptLevel;
394  }
395  Opts.OptimizationLevel = OptimizationLevel;
396 
397  // We must always run at least the always inlining pass.
398  Opts.setInlining(
399  (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalInlining
401  // -fno-inline-functions overrides OptimizationLevel > 1.
402  Opts.NoInline = Args.hasArg(OPT_fno_inline);
403  Opts.setInlining(Args.hasArg(OPT_fno_inline_functions) ?
404  CodeGenOptions::OnlyAlwaysInlining : Opts.getInlining());
405 
406  if (Arg *A = Args.getLastArg(OPT_fveclib)) {
407  StringRef Name = A->getValue();
408  if (Name == "Accelerate")
409  Opts.setVecLib(CodeGenOptions::Accelerate);
410  else if (Name == "none")
411  Opts.setVecLib(CodeGenOptions::NoLibrary);
412  else
413  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
414  }
415 
416  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
417  unsigned Val =
418  llvm::StringSwitch<unsigned>(A->getValue())
419  .Case("line-tables-only", CodeGenOptions::DebugLineTablesOnly)
420  .Case("limited", CodeGenOptions::LimitedDebugInfo)
421  .Case("standalone", CodeGenOptions::FullDebugInfo)
422  .Default(~0U);
423  if (Val == ~0U)
424  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
425  << A->getValue();
426  else
427  Opts.setDebugInfo(static_cast<CodeGenOptions::DebugInfoKind>(Val));
428  }
429  if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
430  unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
431  .Case("gdb", CodeGenOptions::DebuggerKindGDB)
432  .Case("lldb", CodeGenOptions::DebuggerKindLLDB)
433  .Case("sce", CodeGenOptions::DebuggerKindSCE)
434  .Default(~0U);
435  if (Val == ~0U)
436  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
437  << A->getValue();
438  else
439  Opts.setDebuggerTuning(static_cast<CodeGenOptions::DebuggerKind>(Val));
440  }
441  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
442  Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
443  Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
444  Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
445  Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
446  Opts.DebugExplicitImport = Triple.isPS4CPU();
447 
448  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
449  Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
450 
451  if (const Arg *A =
452  Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
453  Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
454 
455  Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns);
456  Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
457  Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
458  Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
459  Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
460  OPT_fuse_register_sized_bitfield_access);
461  Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
462  Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
463  Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
464  Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants);
465  Opts.NoCommon = Args.hasArg(OPT_fno_common);
466  Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
467  Opts.OptimizeSize = getOptimizationLevelSize(Args);
468  Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
469  Args.hasArg(OPT_ffreestanding));
470  if (Opts.SimplifyLibCalls)
472  Opts.UnrollLoops =
473  Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
474  (Opts.OptimizationLevel > 1 && !Opts.OptimizeSize));
475  Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
476 
477  Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
478  Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
479  Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
480  Opts.ProfileInstrGenerate = Args.hasArg(OPT_fprofile_instr_generate) ||
481  Args.hasArg(OPT_fprofile_instr_generate_EQ);
482  Opts.InstrProfileOutput = Args.getLastArgValue(OPT_fprofile_instr_generate_EQ);
483  Opts.InstrProfileInput = Args.getLastArgValue(OPT_fprofile_instr_use_EQ);
484  Opts.CoverageMapping =
485  Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
486  Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
487  Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
488  Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
489  Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
490  Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
491  Opts.CodeModel = getCodeModel(Args, Diags);
492  Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
493  Opts.DisableFPElim =
494  (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg));
495  Opts.DisableFree = Args.hasArg(OPT_disable_free);
496  Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
497  Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
498  if (Arg *A = Args.getLastArg(OPT_meabi)) {
499  StringRef Value = A->getValue();
500  llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
501  .Case("default", llvm::EABI::Default)
502  .Case("4", llvm::EABI::EABI4)
503  .Case("5", llvm::EABI::EABI5)
504  .Case("gnu", llvm::EABI::GNU)
505  .Default(llvm::EABI::Unknown);
506  if (EABIVersion == llvm::EABI::Unknown)
507  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
508  << Value;
509  else
510  Opts.EABIVersion = Value;
511  }
512  Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable);
513  Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
514  Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
515  Args.hasArg(OPT_cl_finite_math_only) ||
516  Args.hasArg(OPT_cl_fast_relaxed_math));
517  Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
518  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
519  Args.hasArg(OPT_cl_finite_math_only) ||
520  Args.hasArg(OPT_cl_fast_relaxed_math));
521  Opts.NoSignedZeros = Args.hasArg(OPT_fno_signed_zeros);
522  Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
523  Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
524  Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
525  Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
526  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
527  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
528  Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
529  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
530  Opts.IncrementalLinkerCompatible =
531  Args.hasArg(OPT_mincremental_linker_compatible);
532  Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
533  Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
534  Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
535  Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
536  Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
537  Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
538  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
539  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
540  Args.hasArg(OPT_cl_fast_relaxed_math);
541  Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
542  Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
543  Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
544  if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
545  Diags.Report(diag::err_drv_invalid_value)
546  << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
547  << Opts.ThreadModel;
548  Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
549  Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
550 
551  Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
552  OPT_fno_function_sections, false);
553  Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
554  OPT_fno_data_sections, false);
555  Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
556  OPT_fno_unique_section_names, true);
557 
558  Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
559 
560  Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
561  const Arg *A = Args.getLastArg(OPT_flto, OPT_flto_EQ);
562  Opts.EmitFunctionSummary = A && A->containsValue("thin");
563  if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
564  if (IK != IK_LLVM_IR)
565  Diags.Report(diag::err_drv_argument_only_allowed_with)
566  << A->getAsString(Args) << "-x ir";
567  Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
568  }
569 
570  Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
571 
572  Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive);
573  Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
574  Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
575 
576  Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
577  Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
578 
579  Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
580  Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
581  Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
582  if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
583  Opts.CoverageFile = Args.getLastArgValue(OPT_coverage_file);
584  Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
585  Opts.CoverageNoFunctionNamesInData =
586  Args.hasArg(OPT_coverage_no_function_names_in_data);
587  Opts.CoverageExitBlockBeforeBody =
588  Args.hasArg(OPT_coverage_exit_block_before_body);
589  if (Args.hasArg(OPT_coverage_version_EQ)) {
590  StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
591  if (CoverageVersion.size() != 4) {
592  Diags.Report(diag::err_drv_invalid_value)
593  << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
594  << CoverageVersion;
595  } else {
596  memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
597  }
598  }
599  }
600 
601  Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
602  Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
603  Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
604  Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections);
605  Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
606  for (auto A : Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
607  unsigned LinkFlags = llvm::Linker::Flags::None;
608  if (A->getOption().matches(OPT_mlink_cuda_bitcode))
609  LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded |
610  llvm::Linker::Flags::InternalizeLinkedSymbols;
611  Opts.LinkBitcodeFiles.push_back(std::make_pair(LinkFlags, A->getValue()));
612  }
613  Opts.SanitizeCoverageType =
614  getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
615  Opts.SanitizeCoverageIndirectCalls =
616  Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
617  Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
618  Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
619  Opts.SanitizeCoverage8bitCounters =
620  Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
621  Opts.SanitizeMemoryTrackOrigins =
622  getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
623  Opts.SanitizeMemoryUseAfterDtor =
624  Args.hasArg(OPT_fsanitize_memory_use_after_dtor);
625  Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
626  Opts.SSPBufferSize =
627  getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
628  Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
629  if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
630  StringRef Val = A->getValue();
631  unsigned StackAlignment = Opts.StackAlignment;
632  Val.getAsInteger(10, StackAlignment);
633  Opts.StackAlignment = StackAlignment;
634  }
635 
636  if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
637  StringRef Val = A->getValue();
638  unsigned StackProbeSize = Opts.StackProbeSize;
639  Val.getAsInteger(0, StackProbeSize);
640  Opts.StackProbeSize = StackProbeSize;
641  }
642 
643  if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
644  StringRef Name = A->getValue();
645  unsigned Method = llvm::StringSwitch<unsigned>(Name)
646  .Case("legacy", CodeGenOptions::Legacy)
647  .Case("non-legacy", CodeGenOptions::NonLegacy)
648  .Case("mixed", CodeGenOptions::Mixed)
649  .Default(~0U);
650  if (Method == ~0U) {
651  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
652  Success = false;
653  } else {
654  Opts.setObjCDispatchMethod(
655  static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
656  }
657  }
658 
659  Opts.EmulatedTLS =
660  Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
661 
662  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
663  StringRef Name = A->getValue();
664  unsigned Model = llvm::StringSwitch<unsigned>(Name)
665  .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
666  .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
667  .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
668  .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
669  .Default(~0U);
670  if (Model == ~0U) {
671  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
672  Success = false;
673  } else {
674  Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
675  }
676  }
677 
678  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
679  StringRef Val = A->getValue();
680  if (Val == "fast")
681  Opts.setFPContractMode(CodeGenOptions::FPC_Fast);
682  else if (Val == "on")
683  Opts.setFPContractMode(CodeGenOptions::FPC_On);
684  else if (Val == "off")
685  Opts.setFPContractMode(CodeGenOptions::FPC_Off);
686  else
687  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
688  }
689 
690  if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
691  if (A->getOption().matches(OPT_fpcc_struct_return)) {
692  Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
693  } else {
694  assert(A->getOption().matches(OPT_freg_struct_return));
695  Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
696  }
697  }
698 
699  Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
700  bool NeedLocTracking = false;
701 
702  if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
704  GenerateOptimizationRemarkRegex(Diags, Args, A);
705  NeedLocTracking = true;
706  }
707 
708  if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
710  GenerateOptimizationRemarkRegex(Diags, Args, A);
711  NeedLocTracking = true;
712  }
713 
714  if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
716  GenerateOptimizationRemarkRegex(Diags, Args, A);
717  NeedLocTracking = true;
718  }
719 
720  // If the user requested to use a sample profile for PGO, then the
721  // backend will need to track source location information so the profile
722  // can be incorporated into the IR.
723  if (!Opts.SampleProfileFile.empty())
724  NeedLocTracking = true;
725 
726  // If the user requested a flag that requires source locations available in
727  // the backend, make sure that the backend tracks source location information.
728  if (NeedLocTracking && Opts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
729  Opts.setDebugInfo(CodeGenOptions::LocTrackingOnly);
730 
731  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
732 
733  // Parse -fsanitize-recover= arguments.
734  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
735  parseSanitizerKinds("-fsanitize-recover=",
736  Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
737  Opts.SanitizeRecover);
738  parseSanitizerKinds("-fsanitize-trap=",
739  Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
740  Opts.SanitizeTrap);
741 
743  Args.getAllArgValues(OPT_fcuda_include_gpubinary);
744 
745  return Success;
746 }
747 
749  ArgList &Args) {
750  using namespace options;
751  Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
752  Opts.Targets = Args.getAllArgValues(OPT_MT);
753  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
754  Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
755  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
756  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
757  Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
758  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
759  Opts.PrintShowIncludes = Args.hasArg(OPT_show_includes);
760  Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
762  Args.getLastArgValue(OPT_module_dependency_dir);
763  if (Args.hasArg(OPT_MV))
765  // Add sanitizer blacklists as extra dependencies.
766  // They won't be discovered by the regular preprocessor, so
767  // we let make / ninja to know about this implicit dependency.
768  Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
769  auto ModuleFiles = Args.getAllArgValues(OPT_fmodule_file);
770  Opts.ExtraDeps.insert(Opts.ExtraDeps.end(), ModuleFiles.begin(),
771  ModuleFiles.end());
772 }
773 
774 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
775  DiagnosticsEngine *Diags) {
776  using namespace options;
777  bool Success = true;
778 
779  Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
780  if (Arg *A =
781  Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
782  Opts.DiagnosticSerializationFile = A->getValue();
783  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
784  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
785  Opts.Pedantic = Args.hasArg(OPT_pedantic);
786  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
787  Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
788  Opts.ShowColors = Args.hasArg(OPT_fcolor_diagnostics);
789  Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
790  OPT_fno_show_column,
791  /*Default=*/true);
792  Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
793  Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
794  Opts.ShowOptionNames = Args.hasArg(OPT_fdiagnostics_show_option);
795 
796  llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
797 
798  // Default behavior is to not to show note include stacks.
799  Opts.ShowNoteIncludeStack = false;
800  if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
801  OPT_fno_diagnostics_show_note_include_stack))
802  if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
803  Opts.ShowNoteIncludeStack = true;
804 
805  StringRef ShowOverloads =
806  Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
807  if (ShowOverloads == "best")
808  Opts.setShowOverloads(Ovl_Best);
809  else if (ShowOverloads == "all")
810  Opts.setShowOverloads(Ovl_All);
811  else {
812  Success = false;
813  if (Diags)
814  Diags->Report(diag::err_drv_invalid_value)
815  << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
816  << ShowOverloads;
817  }
818 
819  StringRef ShowCategory =
820  Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
821  if (ShowCategory == "none")
822  Opts.ShowCategories = 0;
823  else if (ShowCategory == "id")
824  Opts.ShowCategories = 1;
825  else if (ShowCategory == "name")
826  Opts.ShowCategories = 2;
827  else {
828  Success = false;
829  if (Diags)
830  Diags->Report(diag::err_drv_invalid_value)
831  << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
832  << ShowCategory;
833  }
834 
835  StringRef Format =
836  Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
837  if (Format == "clang")
838  Opts.setFormat(DiagnosticOptions::Clang);
839  else if (Format == "msvc")
840  Opts.setFormat(DiagnosticOptions::MSVC);
841  else if (Format == "msvc-fallback") {
842  Opts.setFormat(DiagnosticOptions::MSVC);
843  Opts.CLFallbackMode = true;
844  } else if (Format == "vi")
845  Opts.setFormat(DiagnosticOptions::Vi);
846  else {
847  Success = false;
848  if (Diags)
849  Diags->Report(diag::err_drv_invalid_value)
850  << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
851  << Format;
852  }
853 
854  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
855  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
856  Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
857  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify);
859  Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
860  Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
861  Diags, DiagMask);
862  if (Args.hasArg(OPT_verify_ignore_unexpected))
863  DiagMask = DiagnosticLevelMask::All;
864  Opts.setVerifyIgnoreUnexpected(DiagMask);
865  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
866  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
867  Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
868  Opts.MacroBacktraceLimit =
869  getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
871  Opts.TemplateBacktraceLimit = getLastArgIntValue(
872  Args, OPT_ftemplate_backtrace_limit,
874  Opts.ConstexprBacktraceLimit = getLastArgIntValue(
875  Args, OPT_fconstexpr_backtrace_limit,
877  Opts.SpellCheckingLimit = getLastArgIntValue(
878  Args, OPT_fspell_checking_limit,
880  Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
882  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
883  Opts.TabStop = DiagnosticOptions::DefaultTabStop;
884  if (Diags)
885  Diags->Report(diag::warn_ignoring_ftabstop_value)
886  << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
887  }
888  Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
889  addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
890  addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
891 
892  return Success;
893 }
894 
895 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
896  Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
897 }
898 
899 /// Parse the argument to the -ftest-module-file-extension
900 /// command-line argument.
901 ///
902 /// \returns true on error, false on success.
903 static bool parseTestModuleFileExtensionArg(StringRef Arg,
904  std::string &BlockName,
905  unsigned &MajorVersion,
906  unsigned &MinorVersion,
907  bool &Hashed,
908  std::string &UserInfo) {
910  Arg.split(Args, ':', 5);
911  if (Args.size() < 5)
912  return true;
913 
914  BlockName = Args[0];
915  if (Args[1].getAsInteger(10, MajorVersion)) return true;
916  if (Args[2].getAsInteger(10, MinorVersion)) return true;
917  if (Args[3].getAsInteger(2, Hashed)) return true;
918  if (Args.size() > 4)
919  UserInfo = Args[4];
920  return false;
921 }
922 
923 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
924  DiagnosticsEngine &Diags) {
925  using namespace options;
927  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
928  switch (A->getOption().getID()) {
929  default:
930  llvm_unreachable("Invalid option in group!");
931  case OPT_ast_list:
932  Opts.ProgramAction = frontend::ASTDeclList; break;
933  case OPT_ast_dump:
934  case OPT_ast_dump_lookups:
935  Opts.ProgramAction = frontend::ASTDump; break;
936  case OPT_ast_print:
937  Opts.ProgramAction = frontend::ASTPrint; break;
938  case OPT_ast_view:
939  Opts.ProgramAction = frontend::ASTView; break;
940  case OPT_dump_raw_tokens:
942  case OPT_dump_tokens:
943  Opts.ProgramAction = frontend::DumpTokens; break;
944  case OPT_S:
946  case OPT_emit_llvm_bc:
947  Opts.ProgramAction = frontend::EmitBC; break;
948  case OPT_emit_html:
949  Opts.ProgramAction = frontend::EmitHTML; break;
950  case OPT_emit_llvm:
951  Opts.ProgramAction = frontend::EmitLLVM; break;
952  case OPT_emit_llvm_only:
954  case OPT_emit_codegen_only:
956  case OPT_emit_obj:
957  Opts.ProgramAction = frontend::EmitObj; break;
958  case OPT_fixit_EQ:
959  Opts.FixItSuffix = A->getValue();
960  // fall-through!
961  case OPT_fixit:
962  Opts.ProgramAction = frontend::FixIt; break;
963  case OPT_emit_module:
965  case OPT_emit_pch:
966  Opts.ProgramAction = frontend::GeneratePCH; break;
967  case OPT_emit_pth:
968  Opts.ProgramAction = frontend::GeneratePTH; break;
969  case OPT_init_only:
970  Opts.ProgramAction = frontend::InitOnly; break;
971  case OPT_fsyntax_only:
973  case OPT_module_file_info:
975  case OPT_verify_pch:
976  Opts.ProgramAction = frontend::VerifyPCH; break;
977  case OPT_print_decl_contexts:
979  case OPT_print_preamble:
981  case OPT_E:
983  case OPT_rewrite_macros:
985  case OPT_rewrite_objc:
986  Opts.ProgramAction = frontend::RewriteObjC; break;
987  case OPT_rewrite_test:
988  Opts.ProgramAction = frontend::RewriteTest; break;
989  case OPT_analyze:
990  Opts.ProgramAction = frontend::RunAnalysis; break;
991  case OPT_migrate:
993  case OPT_Eonly:
995  }
996  }
997 
998  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
999  Opts.Plugins.emplace_back(A->getValue(0));
1001  Opts.ActionName = A->getValue();
1002 
1003  for (const Arg *AA : Args.filtered(OPT_plugin_arg))
1004  if (AA->getValue(0) == Opts.ActionName)
1005  Opts.PluginArgs.emplace_back(AA->getValue(1));
1006  }
1007 
1008  Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1009  Opts.AddPluginArgs.resize(Opts.AddPluginActions.size());
1010  for (int i = 0, e = Opts.AddPluginActions.size(); i != e; ++i)
1011  for (const Arg *A : Args.filtered(OPT_plugin_arg))
1012  if (A->getValue(0) == Opts.AddPluginActions[i])
1013  Opts.AddPluginArgs[i].emplace_back(A->getValue(1));
1014 
1015  for (const std::string &Arg :
1016  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1017  std::string BlockName;
1018  unsigned MajorVersion;
1019  unsigned MinorVersion;
1020  bool Hashed;
1021  std::string UserInfo;
1022  if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1023  MinorVersion, Hashed, UserInfo)) {
1024  Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1025 
1026  continue;
1027  }
1028 
1029  // Add the testing module file extension.
1030  Opts.ModuleFileExtensions.push_back(
1031  new TestModuleFileExtension(BlockName, MajorVersion, MinorVersion,
1032  Hashed, UserInfo));
1033  }
1034 
1035  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1036  Opts.CodeCompletionAt =
1037  ParsedSourceLocation::FromString(A->getValue());
1038  if (Opts.CodeCompletionAt.FileName.empty())
1039  Diags.Report(diag::err_drv_invalid_value)
1040  << A->getAsString(Args) << A->getValue();
1041  }
1042  Opts.DisableFree = Args.hasArg(OPT_disable_free);
1043 
1044  Opts.OutputFile = Args.getLastArgValue(OPT_o);
1045  Opts.Plugins = Args.getAllArgValues(OPT_load);
1046  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1047  Opts.ShowHelp = Args.hasArg(OPT_help);
1048  Opts.ShowStats = Args.hasArg(OPT_print_stats);
1049  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1050  Opts.ShowVersion = Args.hasArg(OPT_version);
1051  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1052  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1053  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1054  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1055  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1056  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1057  Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
1058  Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
1059  Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
1060  Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
1062  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1063  Opts.ModuleFiles = Args.getAllArgValues(OPT_fmodule_file);
1064  Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1065  Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
1066 
1068  = Args.hasArg(OPT_code_completion_macros);
1070  = Args.hasArg(OPT_code_completion_patterns);
1072  = !Args.hasArg(OPT_no_code_completion_globals);
1074  = Args.hasArg(OPT_code_completion_brief_comments);
1075 
1077  = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
1078  Opts.AuxTriple =
1079  llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple));
1080 
1081  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1082  OPT_arcmt_modify,
1083  OPT_arcmt_migrate)) {
1084  switch (A->getOption().getID()) {
1085  default:
1086  llvm_unreachable("missed a case");
1087  case OPT_arcmt_check:
1089  break;
1090  case OPT_arcmt_modify:
1092  break;
1093  case OPT_arcmt_migrate:
1095  break;
1096  }
1097  }
1098  Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
1100  = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1102  = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1103 
1104  if (Args.hasArg(OPT_objcmt_migrate_literals))
1106  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1108  if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1110  if (Args.hasArg(OPT_objcmt_migrate_property))
1112  if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1114  if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1116  if (Args.hasArg(OPT_objcmt_migrate_annotation))
1118  if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1120  if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1122  if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1124  if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1126  if (Args.hasArg(OPT_objcmt_atomic_property))
1128  if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1130  if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1132  if (Args.hasArg(OPT_objcmt_migrate_all))
1134 
1135  Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
1136 
1139  Diags.Report(diag::err_drv_argument_not_allowed_with)
1140  << "ARC migration" << "ObjC migration";
1141  }
1142 
1143  InputKind DashX = IK_None;
1144  if (const Arg *A = Args.getLastArg(OPT_x)) {
1145  DashX = llvm::StringSwitch<InputKind>(A->getValue())
1146  .Case("c", IK_C)
1147  .Case("cl", IK_OpenCL)
1148  .Case("cuda", IK_CUDA)
1149  .Case("c++", IK_CXX)
1150  .Case("objective-c", IK_ObjC)
1151  .Case("objective-c++", IK_ObjCXX)
1152  .Case("cpp-output", IK_PreprocessedC)
1153  .Case("assembler-with-cpp", IK_Asm)
1154  .Case("c++-cpp-output", IK_PreprocessedCXX)
1155  .Case("cuda-cpp-output", IK_PreprocessedCuda)
1156  .Case("objective-c-cpp-output", IK_PreprocessedObjC)
1157  .Case("objc-cpp-output", IK_PreprocessedObjC)
1158  .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX)
1159  .Case("objc++-cpp-output", IK_PreprocessedObjCXX)
1160  .Case("c-header", IK_C)
1161  .Case("cl-header", IK_OpenCL)
1162  .Case("objective-c-header", IK_ObjC)
1163  .Case("c++-header", IK_CXX)
1164  .Case("objective-c++-header", IK_ObjCXX)
1165  .Cases("ast", "pcm", IK_AST)
1166  .Case("ir", IK_LLVM_IR)
1167  .Default(IK_None);
1168  if (DashX == IK_None)
1169  Diags.Report(diag::err_drv_invalid_value)
1170  << A->getAsString(Args) << A->getValue();
1171  }
1172 
1173  // '-' is the default input if none is given.
1174  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1175  Opts.Inputs.clear();
1176  if (Inputs.empty())
1177  Inputs.push_back("-");
1178  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1179  InputKind IK = DashX;
1180  if (IK == IK_None) {
1182  StringRef(Inputs[i]).rsplit('.').second);
1183  // FIXME: Remove this hack.
1184  if (i == 0)
1185  DashX = IK;
1186  }
1187  Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
1188  }
1189 
1190  return DashX;
1191 }
1192 
1193 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1194  void *MainAddr) {
1195  std::string ClangExecutable =
1196  llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1197  StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
1198 
1199  // Compute the path to the resource directory.
1200  StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1201  SmallString<128> P(Dir);
1202  if (ClangResourceDir != "")
1203  llvm::sys::path::append(P, ClangResourceDir);
1204  else
1205  llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX,
1206  "clang", CLANG_VERSION_STRING);
1207 
1208  return P.str();
1209 }
1210 
1211 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args) {
1212  using namespace options;
1213  Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
1214  Opts.Verbose = Args.hasArg(OPT_v);
1215  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
1216  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
1217  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
1218  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1219  Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1220  Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
1221  Opts.ModuleCachePath = Args.getLastArgValue(OPT_fmodules_cache_path);
1222  Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
1223  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
1224  Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
1225  Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
1227  getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1228  Opts.ModuleCachePruneAfter =
1229  getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
1231  Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1232  Opts.BuildSessionTimestamp =
1233  getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
1235  Args.hasArg(OPT_fmodules_validate_system_headers);
1236  if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1237  Opts.ModuleFormat = A->getValue();
1238 
1239  for (const Arg *A : Args.filtered(OPT_fmodules_ignore_macro)) {
1240  StringRef MacroDef = A->getValue();
1241  Opts.ModulesIgnoreMacros.insert(MacroDef.split('=').first);
1242  }
1243 
1244  // Add -I..., -F..., and -index-header-map options in order.
1245  bool IsIndexHeaderMap = false;
1246  for (const Arg *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
1247  if (A->getOption().matches(OPT_index_header_map)) {
1248  // -index-header-map applies to the next -I or -F.
1249  IsIndexHeaderMap = true;
1250  continue;
1251  }
1252 
1254  IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1255 
1256  Opts.AddPath(A->getValue(), Group,
1257  /*IsFramework=*/A->getOption().matches(OPT_F), true);
1258  IsIndexHeaderMap = false;
1259  }
1260 
1261  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
1262  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1263  for (const Arg *A :
1264  Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
1265  if (A->getOption().matches(OPT_iprefix))
1266  Prefix = A->getValue();
1267  else if (A->getOption().matches(OPT_iwithprefix))
1268  Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
1269  else
1270  Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
1271  }
1272 
1273  for (const Arg *A : Args.filtered(OPT_idirafter))
1274  Opts.AddPath(A->getValue(), frontend::After, false, true);
1275  for (const Arg *A : Args.filtered(OPT_iquote))
1276  Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
1277  for (const Arg *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
1278  Opts.AddPath(A->getValue(), frontend::System, false,
1279  !A->getOption().matches(OPT_iwithsysroot));
1280  for (const Arg *A : Args.filtered(OPT_iframework))
1281  Opts.AddPath(A->getValue(), frontend::System, true, true);
1282 
1283  // Add the paths for the various language specific isystem flags.
1284  for (const Arg *A : Args.filtered(OPT_c_isystem))
1285  Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
1286  for (const Arg *A : Args.filtered(OPT_cxx_isystem))
1287  Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
1288  for (const Arg *A : Args.filtered(OPT_objc_isystem))
1289  Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
1290  for (const Arg *A : Args.filtered(OPT_objcxx_isystem))
1291  Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1292 
1293  // Add the internal paths from a driver that detects standard include paths.
1294  for (const Arg *A :
1295  Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1297  if (A->getOption().matches(OPT_internal_externc_isystem))
1298  Group = frontend::ExternCSystem;
1299  Opts.AddPath(A->getValue(), Group, false, true);
1300  }
1301 
1302  // Add the path prefixes which are implicitly treated as being system headers.
1303  for (const Arg *A :
1304  Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1305  Opts.AddSystemHeaderPrefix(
1306  A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1307 
1308  for (const Arg *A : Args.filtered(OPT_ivfsoverlay))
1309  Opts.AddVFSOverlayFile(A->getValue());
1310 }
1311 
1313  LangStandard::Kind LangStd) {
1314  // Set some properties which depend solely on the input kind; it would be nice
1315  // to move these to the language standard, and have the driver resolve the
1316  // input kind + language standard.
1317  if (IK == IK_Asm) {
1318  Opts.AsmPreprocessor = 1;
1319  } else if (IK == IK_ObjC ||
1320  IK == IK_ObjCXX ||
1321  IK == IK_PreprocessedObjC ||
1322  IK == IK_PreprocessedObjCXX) {
1323  Opts.ObjC1 = Opts.ObjC2 = 1;
1324  }
1325 
1326  if (LangStd == LangStandard::lang_unspecified) {
1327  // Based on the base language, pick one.
1328  switch (IK) {
1329  case IK_None:
1330  case IK_AST:
1331  case IK_LLVM_IR:
1332  llvm_unreachable("Invalid input kind!");
1333  case IK_OpenCL:
1334  LangStd = LangStandard::lang_opencl;
1335  break;
1336  case IK_CUDA:
1337  case IK_PreprocessedCuda:
1338  LangStd = LangStandard::lang_cuda;
1339  break;
1340  case IK_Asm:
1341  case IK_C:
1342  case IK_PreprocessedC:
1343  case IK_ObjC:
1344  case IK_PreprocessedObjC:
1345  LangStd = LangStandard::lang_gnu11;
1346  break;
1347  case IK_CXX:
1348  case IK_PreprocessedCXX:
1349  case IK_ObjCXX:
1350  case IK_PreprocessedObjCXX:
1351  LangStd = LangStandard::lang_gnucxx98;
1352  break;
1353  }
1354  }
1355 
1356  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1357  Opts.LineComment = Std.hasLineComments();
1358  Opts.C99 = Std.isC99();
1359  Opts.C11 = Std.isC11();
1360  Opts.CPlusPlus = Std.isCPlusPlus();
1361  Opts.CPlusPlus11 = Std.isCPlusPlus11();
1362  Opts.CPlusPlus14 = Std.isCPlusPlus14();
1363  Opts.CPlusPlus1z = Std.isCPlusPlus1z();
1364  Opts.Digraphs = Std.hasDigraphs();
1365  Opts.GNUMode = Std.isGNUMode();
1366  Opts.GNUInline = Std.isC89();
1367  Opts.HexFloats = Std.hasHexFloats();
1368  Opts.ImplicitInt = Std.hasImplicitInt();
1369 
1370  // Set OpenCL Version.
1371  Opts.OpenCL = LangStd == LangStandard::lang_opencl || IK == IK_OpenCL;
1372  if (LangStd == LangStandard::lang_opencl)
1373  Opts.OpenCLVersion = 100;
1374  else if (LangStd == LangStandard::lang_opencl11)
1375  Opts.OpenCLVersion = 110;
1376  else if (LangStd == LangStandard::lang_opencl12)
1377  Opts.OpenCLVersion = 120;
1378  else if (LangStd == LangStandard::lang_opencl20)
1379  Opts.OpenCLVersion = 200;
1380 
1381  // OpenCL has some additional defaults.
1382  if (Opts.OpenCL) {
1383  Opts.AltiVec = 0;
1384  Opts.ZVector = 0;
1385  Opts.CXXOperatorNames = 1;
1386  Opts.LaxVectorConversions = 0;
1387  Opts.DefaultFPContract = 1;
1388  Opts.NativeHalfType = 1;
1389  }
1390 
1391  Opts.CUDA = IK == IK_CUDA || IK == IK_PreprocessedCuda ||
1392  LangStd == LangStandard::lang_cuda;
1393 
1394  // OpenCL and C++ both have bool, true, false keywords.
1395  Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1396 
1397  // OpenCL has half keyword
1398  Opts.Half = Opts.OpenCL;
1399 
1400  // C++ has wchar_t keyword.
1401  Opts.WChar = Opts.CPlusPlus;
1402 
1403  Opts.GNUKeywords = Opts.GNUMode;
1404  Opts.CXXOperatorNames = Opts.CPlusPlus;
1405 
1406  Opts.DollarIdents = !Opts.AsmPreprocessor;
1407 }
1408 
1409 /// Attempt to parse a visibility value out of the given argument.
1410 static Visibility parseVisibility(Arg *arg, ArgList &args,
1411  DiagnosticsEngine &diags) {
1412  StringRef value = arg->getValue();
1413  if (value == "default") {
1414  return DefaultVisibility;
1415  } else if (value == "hidden" || value == "internal") {
1416  return HiddenVisibility;
1417  } else if (value == "protected") {
1418  // FIXME: diagnose if target does not support protected visibility
1419  return ProtectedVisibility;
1420  }
1421 
1422  diags.Report(diag::err_drv_invalid_value)
1423  << arg->getAsString(args) << value;
1424  return DefaultVisibility;
1425 }
1426 
1427 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
1428  DiagnosticsEngine &Diags) {
1429  // FIXME: Cleanup per-file based stuff.
1431  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
1432  LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1433 #define LANGSTANDARD(id, name, desc, features) \
1434  .Case(name, LangStandard::lang_##id)
1435 #include "clang/Frontend/LangStandards.def"
1437  if (LangStd == LangStandard::lang_unspecified)
1438  Diags.Report(diag::err_drv_invalid_value)
1439  << A->getAsString(Args) << A->getValue();
1440  else {
1441  // Valid standard, check to make sure language and standard are
1442  // compatible.
1443  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1444  switch (IK) {
1445  case IK_C:
1446  case IK_ObjC:
1447  case IK_PreprocessedC:
1448  case IK_PreprocessedObjC:
1449  if (!(Std.isC89() || Std.isC99()))
1450  Diags.Report(diag::err_drv_argument_not_allowed_with)
1451  << A->getAsString(Args) << "C/ObjC";
1452  break;
1453  case IK_CXX:
1454  case IK_ObjCXX:
1455  case IK_PreprocessedCXX:
1456  case IK_PreprocessedObjCXX:
1457  if (!Std.isCPlusPlus())
1458  Diags.Report(diag::err_drv_argument_not_allowed_with)
1459  << A->getAsString(Args) << "C++/ObjC++";
1460  break;
1461  case IK_OpenCL:
1462  if (!Std.isC99())
1463  Diags.Report(diag::err_drv_argument_not_allowed_with)
1464  << A->getAsString(Args) << "OpenCL";
1465  break;
1466  case IK_CUDA:
1467  case IK_PreprocessedCuda:
1468  if (!Std.isCPlusPlus())
1469  Diags.Report(diag::err_drv_argument_not_allowed_with)
1470  << A->getAsString(Args) << "CUDA";
1471  break;
1472  default:
1473  break;
1474  }
1475  }
1476  }
1477 
1478  // -cl-std only applies for OpenCL language standards.
1479  // Override the -std option in this case.
1480  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
1481  LangStandard::Kind OpenCLLangStd
1482  = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1483  .Case("CL", LangStandard::lang_opencl)
1484  .Case("CL1.1", LangStandard::lang_opencl11)
1485  .Case("CL1.2", LangStandard::lang_opencl12)
1486  .Case("CL2.0", LangStandard::lang_opencl20)
1488 
1489  if (OpenCLLangStd == LangStandard::lang_unspecified) {
1490  Diags.Report(diag::err_drv_invalid_value)
1491  << A->getAsString(Args) << A->getValue();
1492  }
1493  else
1494  LangStd = OpenCLLangStd;
1495  }
1496 
1497  CompilerInvocation::setLangDefaults(Opts, IK, LangStd);
1498 
1499  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
1500  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
1501  // while a subset (the non-C++ GNU keywords) is provided by GCC's
1502  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
1503  // name, as it doesn't seem a useful distinction.
1504  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
1505  Opts.GNUKeywords);
1506 
1507  if (Args.hasArg(OPT_fno_operator_names))
1508  Opts.CXXOperatorNames = 0;
1509 
1510  if (Args.hasArg(OPT_fcuda_is_device))
1511  Opts.CUDAIsDevice = 1;
1512 
1513  if (Args.hasArg(OPT_fcuda_allow_host_calls_from_host_device))
1514  Opts.CUDAAllowHostCallsFromHostDevice = 1;
1515 
1516  if (Args.hasArg(OPT_fcuda_disable_target_call_checks))
1517  Opts.CUDADisableTargetCallChecks = 1;
1518 
1519  if (Args.hasArg(OPT_fcuda_target_overloads))
1520  Opts.CUDATargetOverloads = 1;
1521 
1522  if (Opts.ObjC1) {
1523  if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
1524  StringRef value = arg->getValue();
1525  if (Opts.ObjCRuntime.tryParse(value))
1526  Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
1527  }
1528 
1529  if (Args.hasArg(OPT_fobjc_gc_only))
1530  Opts.setGC(LangOptions::GCOnly);
1531  else if (Args.hasArg(OPT_fobjc_gc))
1532  Opts.setGC(LangOptions::HybridGC);
1533  else if (Args.hasArg(OPT_fobjc_arc)) {
1534  Opts.ObjCAutoRefCount = 1;
1535  if (!Opts.ObjCRuntime.allowsARC())
1536  Diags.Report(diag::err_arc_unsupported_on_runtime);
1537  }
1538 
1539  // ObjCWeakRuntime tracks whether the runtime supports __weak, not
1540  // whether the feature is actually enabled. This is predominantly
1541  // determined by -fobjc-runtime, but we allow it to be overridden
1542  // from the command line for testing purposes.
1543  if (Args.hasArg(OPT_fobjc_runtime_has_weak))
1544  Opts.ObjCWeakRuntime = 1;
1545  else
1546  Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
1547 
1548  // ObjCWeak determines whether __weak is actually enabled.
1549  // Note that we allow -fno-objc-weak to disable this even in ARC mode.
1550  if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
1551  if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
1552  assert(!Opts.ObjCWeak);
1553  } else if (Opts.getGC() != LangOptions::NonGC) {
1554  Diags.Report(diag::err_objc_weak_with_gc);
1555  } else if (!Opts.ObjCWeakRuntime) {
1556  Diags.Report(diag::err_objc_weak_unsupported);
1557  } else {
1558  Opts.ObjCWeak = 1;
1559  }
1560  } else if (Opts.ObjCAutoRefCount) {
1561  Opts.ObjCWeak = Opts.ObjCWeakRuntime;
1562  }
1563 
1564  if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
1565  Opts.ObjCInferRelatedResultType = 0;
1566 
1567  if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
1568  Opts.ObjCSubscriptingLegacyRuntime =
1570  }
1571 
1572  if (Args.hasArg(OPT_fgnu89_inline)) {
1573  if (Opts.CPlusPlus)
1574  Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fgnu89-inline"
1575  << "C++/ObjC++";
1576  else
1577  Opts.GNUInline = 1;
1578  }
1579 
1580  if (Args.hasArg(OPT_fapple_kext)) {
1581  if (!Opts.CPlusPlus)
1582  Diags.Report(diag::warn_c_kext);
1583  else
1584  Opts.AppleKext = 1;
1585  }
1586 
1587  if (Args.hasArg(OPT_print_ivar_layout))
1588  Opts.ObjCGCBitmapPrint = 1;
1589  if (Args.hasArg(OPT_fno_constant_cfstrings))
1590  Opts.NoConstantCFStrings = 1;
1591 
1592  if (Args.hasArg(OPT_faltivec))
1593  Opts.AltiVec = 1;
1594 
1595  if (Args.hasArg(OPT_fzvector))
1596  Opts.ZVector = 1;
1597 
1598  if (Args.hasArg(OPT_pthread))
1599  Opts.POSIXThreads = 1;
1600 
1601  // The value-visibility mode defaults to "default".
1602  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
1603  Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
1604  } else {
1605  Opts.setValueVisibilityMode(DefaultVisibility);
1606  }
1607 
1608  // The type-visibility mode defaults to the value-visibility mode.
1609  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
1610  Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
1611  } else {
1612  Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
1613  }
1614 
1615  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
1616  Opts.InlineVisibilityHidden = 1;
1617 
1618  if (Args.hasArg(OPT_ftrapv)) {
1619  Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
1620  // Set the handler, if one is specified.
1621  Opts.OverflowHandler =
1622  Args.getLastArgValue(OPT_ftrapv_handler);
1623  }
1624  else if (Args.hasArg(OPT_fwrapv))
1625  Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
1626 
1627  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
1628  Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
1629  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
1630  Opts.MSCompatibilityVersion = 0;
1631  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
1632  VersionTuple VT;
1633  if (VT.tryParse(A->getValue()))
1634  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1635  << A->getValue();
1636  Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
1637  VT.getMinor().getValueOr(0) * 100000 +
1638  VT.getSubminor().getValueOr(0);
1639  }
1640 
1641  // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
1642  // is specified, or -std is set to a conforming mode.
1643  // Trigraphs are disabled by default in c++1z onwards.
1644  Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus1z;
1645  Opts.Trigraphs =
1646  Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
1647 
1648  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
1649  OPT_fno_dollars_in_identifiers,
1650  Opts.DollarIdents);
1651  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
1652  Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
1653  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
1654  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
1655  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
1656  Opts.ConstStrings);
1657  if (Args.hasArg(OPT_fno_lax_vector_conversions))
1658  Opts.LaxVectorConversions = 0;
1659  if (Args.hasArg(OPT_fno_threadsafe_statics))
1660  Opts.ThreadsafeStatics = 0;
1661  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
1662  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
1663  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
1664  Opts.SjLjExceptions = Args.hasArg(OPT_fsjlj_exceptions);
1665  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
1666 
1667  Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
1668  Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
1669  Opts.Blocks = Args.hasArg(OPT_fblocks);
1670  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
1671  Opts.Coroutines = Args.hasArg(OPT_fcoroutines);
1672  Opts.Modules = Args.hasArg(OPT_fmodules);
1673  Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
1674  Opts.ModulesDeclUse =
1675  Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
1676  Opts.ModulesLocalVisibility =
1677  Args.hasArg(OPT_fmodules_local_submodule_visibility);
1678  Opts.ModulesSearchAll = Opts.Modules &&
1679  !Args.hasArg(OPT_fno_modules_search_all) &&
1680  Args.hasArg(OPT_fmodules_search_all);
1681  Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
1682  Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
1683  Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
1684  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
1685  Opts.ShortWChar = Args.hasFlag(OPT_fshort_wchar, OPT_fno_short_wchar, false);
1686  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
1687  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
1688  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
1689  if (!Opts.NoBuiltin)
1691  Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
1692  Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
1693  Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
1694  Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
1695  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
1696  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
1697  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
1698  Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
1699  Opts.InstantiationDepth =
1700  getLastArgIntValue(Args, OPT_ftemplate_depth, 256, Diags);
1701  Opts.ArrowDepth =
1702  getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
1703  Opts.ConstexprCallDepth =
1704  getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
1705  Opts.ConstexprStepLimit =
1706  getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
1707  Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
1708  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
1709  Opts.NumLargeByValueCopy =
1710  getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
1711  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
1713  Args.getLastArgValue(OPT_fconstant_string_class);
1714  Opts.ObjCDefaultSynthProperties =
1715  !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
1716  Opts.EncodeExtendedBlockSig =
1717  Args.hasArg(OPT_fencode_extended_block_signature);
1718  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
1719  Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
1720  Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
1721  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
1722  Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags);
1723  Opts.Static = Args.hasArg(OPT_static_define);
1724  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
1725  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
1726  || Args.hasArg(OPT_fdump_record_layouts);
1727  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
1728  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
1729  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
1730  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
1731  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
1732  Opts.MRTD = Args.hasArg(OPT_mrtd);
1733  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
1734  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
1735  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
1736  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
1737  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
1738  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
1739  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
1740  Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name);
1741  Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
1742  Opts.ImplementationOfModule =
1743  Args.getLastArgValue(OPT_fmodule_implementation_of);
1744  Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
1745  std::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end());
1746  Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
1747  Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns);
1748  Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
1749 
1750  // __declspec is enabled by default for the PS4 by the driver, and also
1751  // enabled for Microsoft Extensions or Borland Extensions, here.
1752  //
1753  // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
1754  // CUDA extension, however it is required for supporting cuda_builtin_vars.h,
1755  // which uses __declspec(property). Once that has been rewritten in terms of
1756  // something more generic, remove the Opts.CUDA term here.
1757  Opts.DeclSpecKeyword =
1758  Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
1759  (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
1760 
1761  if (!Opts.CurrentModule.empty() && !Opts.ImplementationOfModule.empty() &&
1762  Opts.CurrentModule != Opts.ImplementationOfModule) {
1763  Diags.Report(diag::err_conflicting_module_names)
1764  << Opts.CurrentModule << Opts.ImplementationOfModule;
1765  }
1766 
1767  // For now, we only support local submodule visibility in C++ (because we
1768  // heavily depend on the ODR for merging redefinitions).
1769  if (Opts.ModulesLocalVisibility && !Opts.CPlusPlus)
1770  Diags.Report(diag::err_drv_argument_not_allowed_with)
1771  << "-fmodules-local-submodule-visibility" << "C";
1772 
1773  if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
1774  switch (llvm::StringSwitch<unsigned>(A->getValue())
1775  .Case("target", LangOptions::ASMM_Target)
1776  .Case("no", LangOptions::ASMM_Off)
1777  .Case("yes", LangOptions::ASMM_On)
1778  .Default(255)) {
1779  default:
1780  Diags.Report(diag::err_drv_invalid_value)
1781  << "-faddress-space-map-mangling=" << A->getValue();
1782  break;
1784  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
1785  break;
1786  case LangOptions::ASMM_On:
1787  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
1788  break;
1789  case LangOptions::ASMM_Off:
1790  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
1791  break;
1792  }
1793  }
1794 
1795  if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
1797  llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
1798  A->getValue())
1799  .Case("single",
1801  .Case("multiple",
1803  .Case("virtual",
1805  .Default(LangOptions::PPTMK_BestCase);
1806  if (InheritanceModel == LangOptions::PPTMK_BestCase)
1807  Diags.Report(diag::err_drv_invalid_value)
1808  << "-fms-memptr-rep=" << A->getValue();
1809 
1810  Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
1811  }
1812 
1813  // Check if -fopenmp is specified.
1814  Opts.OpenMP = Args.hasArg(options::OPT_fopenmp);
1815  Opts.OpenMPUseTLS =
1816  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
1817  Opts.OpenMPIsDevice =
1818  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
1819 
1820  // Get the OpenMP target triples if any.
1821  if (Arg *A = Args.getLastArg(options::OPT_omptargets_EQ)) {
1822 
1823  for (unsigned i = 0; i < A->getNumValues(); ++i) {
1824  llvm::Triple TT(A->getValue(i));
1825 
1826  if (TT.getArch() == llvm::Triple::UnknownArch)
1827  Diags.Report(clang::diag::err_drv_invalid_omp_target) << A->getValue(i);
1828  else
1829  Opts.OMPTargetTriples.push_back(TT);
1830  }
1831  }
1832 
1833  // Get OpenMP host file path if any and report if a non existent file is
1834  // found
1835  if (Arg *A = Args.getLastArg(options::OPT_omp_host_ir_file_path)) {
1836  Opts.OMPHostIRFile = A->getValue();
1837  if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
1838  Diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
1839  << Opts.OMPHostIRFile;
1840  }
1841 
1842  // Record whether the __DEPRECATED define was requested.
1843  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
1844  OPT_fno_deprecated_macro,
1845  Opts.Deprecated);
1846 
1847  // FIXME: Eliminate this dependency.
1848  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
1849  OptSize = getOptimizationLevelSize(Args);
1850  Opts.Optimize = Opt != 0;
1851  Opts.OptimizeSize = OptSize != 0;
1852 
1853  // This is the __NO_INLINE__ define, which just depends on things like the
1854  // optimization level and -fno-inline, not actually whether the backend has
1855  // inlining enabled.
1856  Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline);
1857 
1858  Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
1859  Args.hasArg(OPT_cl_fast_relaxed_math);
1860  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
1861  Args.hasArg(OPT_cl_finite_math_only) ||
1862  Args.hasArg(OPT_cl_fast_relaxed_math);
1863  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
1864  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
1865  Args.hasArg(OPT_cl_fast_relaxed_math);
1866 
1867  Opts.RetainCommentsFromSystemHeaders =
1868  Args.hasArg(OPT_fretain_comments_from_system_headers);
1869 
1870  unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
1871  switch (SSP) {
1872  default:
1873  Diags.Report(diag::err_drv_invalid_value)
1874  << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
1875  break;
1876  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
1877  case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
1878  case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
1879  case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
1880  }
1881 
1882  // Parse -fsanitize= arguments.
1883  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
1884  Diags, Opts.Sanitize);
1885  // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
1886  Opts.SanitizeAddressFieldPadding =
1887  getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
1888  Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
1889 }
1890 
1891 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
1892  FileManager &FileMgr,
1893  DiagnosticsEngine &Diags) {
1894  using namespace options;
1895  Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
1896  Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
1897  if (const Arg *A = Args.getLastArg(OPT_token_cache))
1898  Opts.TokenCache = A->getValue();
1899  else
1900  Opts.TokenCache = Opts.ImplicitPTHInclude;
1901  Opts.UsePredefines = !Args.hasArg(OPT_undef);
1902  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
1903  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
1904 
1905  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
1906  for (const Arg *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
1907  Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
1908 
1909  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
1910  StringRef Value(A->getValue());
1911  size_t Comma = Value.find(',');
1912  unsigned Bytes = 0;
1913  unsigned EndOfLine = 0;
1914 
1915  if (Comma == StringRef::npos ||
1916  Value.substr(0, Comma).getAsInteger(10, Bytes) ||
1917  Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
1918  Diags.Report(diag::err_drv_preamble_format);
1919  else {
1920  Opts.PrecompiledPreambleBytes.first = Bytes;
1921  Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
1922  }
1923  }
1924 
1925  // Add macros from the command line.
1926  for (const Arg *A : Args.filtered(OPT_D, OPT_U)) {
1927  if (A->getOption().matches(OPT_D))
1928  Opts.addMacroDef(A->getValue());
1929  else
1930  Opts.addMacroUndef(A->getValue());
1931  }
1932 
1933  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
1934 
1935  // Add the ordered list of -includes.
1936  for (const Arg *A : Args.filtered(OPT_include))
1937  Opts.Includes.emplace_back(A->getValue());
1938 
1939  for (const Arg *A : Args.filtered(OPT_chain_include))
1940  Opts.ChainedIncludes.emplace_back(A->getValue());
1941 
1942  // Include 'altivec.h' if -faltivec option present
1943  if (Args.hasArg(OPT_faltivec))
1944  Opts.Includes.emplace_back("altivec.h");
1945 
1946  for (const Arg *A : Args.filtered(OPT_remap_file)) {
1947  std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
1948 
1949  if (Split.second.empty()) {
1950  Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
1951  continue;
1952  }
1953 
1954  Opts.addRemappedFile(Split.first, Split.second);
1955  }
1956 
1957  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
1958  StringRef Name = A->getValue();
1959  unsigned Library = llvm::StringSwitch<unsigned>(Name)
1960  .Case("libc++", ARCXX_libcxx)
1961  .Case("libstdc++", ARCXX_libstdcxx)
1962  .Case("none", ARCXX_nolib)
1963  .Default(~0U);
1964  if (Library == ~0U)
1965  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1966  else
1968  }
1969 }
1970 
1972  ArgList &Args,
1974  using namespace options;
1975 
1976  switch (Action) {
1977  case frontend::ASTDeclList:
1978  case frontend::ASTDump:
1979  case frontend::ASTPrint:
1980  case frontend::ASTView:
1982  case frontend::EmitBC:
1983  case frontend::EmitHTML:
1984  case frontend::EmitLLVM:
1987  case frontend::EmitObj:
1988  case frontend::FixIt:
1990  case frontend::GeneratePCH:
1991  case frontend::GeneratePTH:
1994  case frontend::VerifyPCH:
1997  case frontend::RewriteObjC:
1998  case frontend::RewriteTest:
1999  case frontend::RunAnalysis:
2001  Opts.ShowCPP = 0;
2002  break;
2003 
2005  case frontend::DumpTokens:
2006  case frontend::InitOnly:
2011  Opts.ShowCPP = !Args.hasArg(OPT_dM);
2012  break;
2013  }
2014 
2015  Opts.ShowComments = Args.hasArg(OPT_C);
2016  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
2017  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
2018  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
2019  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
2020  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
2021 }
2022 
2023 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) {
2024  using namespace options;
2025  Opts.ABI = Args.getLastArgValue(OPT_target_abi);
2026  Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
2027  Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
2028  Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
2029  Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
2030  Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
2031  Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
2032  // Use the default target triple if unspecified.
2033  if (Opts.Triple.empty())
2034  Opts.Triple = llvm::sys::getDefaultTargetTriple();
2035 }
2036 
2038  const char *const *ArgBegin,
2039  const char *const *ArgEnd,
2040  DiagnosticsEngine &Diags) {
2041  bool Success = true;
2042 
2043  // Parse the arguments.
2044  std::unique_ptr<OptTable> Opts(createDriverOptTable());
2045  const unsigned IncludedFlagsBitmask = options::CC1Option;
2046  unsigned MissingArgIndex, MissingArgCount;
2047  InputArgList Args =
2048  Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
2049  MissingArgCount, IncludedFlagsBitmask);
2050 
2051  // Check for missing argument error.
2052  if (MissingArgCount) {
2053  Diags.Report(diag::err_drv_missing_argument)
2054  << Args.getArgString(MissingArgIndex) << MissingArgCount;
2055  Success = false;
2056  }
2057 
2058  // Issue errors on unknown arguments.
2059  for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
2060  Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
2061  Success = false;
2062  }
2063 
2064  Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
2065  Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
2067  Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags);
2070  // FIXME: We shouldn't have to pass the DashX option around here
2071  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags);
2072  ParseTargetArgs(Res.getTargetOpts(), Args);
2073  Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
2074  Res.getTargetOpts());
2076  if (DashX == IK_AST || DashX == IK_LLVM_IR) {
2077  // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
2078  // PassManager in BackendUtil.cpp. They need to be initializd no matter
2079  // what the input type is.
2080  if (Args.hasArg(OPT_fobjc_arc))
2081  Res.getLangOpts()->ObjCAutoRefCount = 1;
2082  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2083  Diags, Res.getLangOpts()->Sanitize);
2084  } else {
2085  // Other LangOpts are only initialzed when the input is not AST or LLVM IR.
2086  ParseLangArgs(*Res.getLangOpts(), Args, DashX, Diags);
2088  Res.getLangOpts()->ObjCExceptions = 1;
2089  }
2090  // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of
2091  // PCH file and find the original header name. Remove the need to do that in
2092  // ParsePreprocessorArgs and remove the FileManager
2093  // parameters from the function and the "FileManager.h" #include.
2094  FileManager FileMgr(Res.getFileSystemOpts());
2095  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, FileMgr, Diags);
2098  return Success;
2099 }
2100 
2101 namespace {
2102 
2103  class ModuleSignature {
2105  unsigned CurBit;
2106  uint64_t CurValue;
2107 
2108  public:
2109  ModuleSignature() : CurBit(0), CurValue(0) { }
2110 
2111  void add(uint64_t Value, unsigned Bits);
2112  void add(StringRef Value);
2113  void flush();
2114 
2115  llvm::APInt getAsInteger() const;
2116  };
2117 }
2118 
2119 void ModuleSignature::add(uint64_t Value, unsigned int NumBits) {
2120  CurValue |= Value << CurBit;
2121  if (CurBit + NumBits < 64) {
2122  CurBit += NumBits;
2123  return;
2124  }
2125 
2126  // Add the current word.
2127  Data.push_back(CurValue);
2128 
2129  if (CurBit)
2130  CurValue = Value >> (64-CurBit);
2131  else
2132  CurValue = 0;
2133  CurBit = (CurBit+NumBits) & 63;
2134 }
2135 
2136 void ModuleSignature::flush() {
2137  if (CurBit == 0)
2138  return;
2139 
2140  Data.push_back(CurValue);
2141  CurBit = 0;
2142  CurValue = 0;
2143 }
2144 
2145 void ModuleSignature::add(StringRef Value) {
2146  for (auto &c : Value)
2147  add(c, 8);
2148 }
2149 
2150 llvm::APInt ModuleSignature::getAsInteger() const {
2151  return llvm::APInt(Data.size() * 64, Data);
2152 }
2153 
2155  // Note: For QoI reasons, the things we use as a hash here should all be
2156  // dumped via the -module-info flag.
2157  using llvm::hash_code;
2158  using llvm::hash_value;
2159  using llvm::hash_combine;
2160 
2161  // Start the signature with the compiler version.
2162  // FIXME: We'd rather use something more cryptographically sound than
2163  // CityHash, but this will do for now.
2164  hash_code code = hash_value(getClangFullRepositoryVersion());
2165 
2166  // Extend the signature with the language options
2167 #define LANGOPT(Name, Bits, Default, Description) \
2168  code = hash_combine(code, LangOpts->Name);
2169 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
2170  code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
2171 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
2172 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
2173 #include "clang/Basic/LangOptions.def"
2174 
2175  for (StringRef Feature : LangOpts->ModuleFeatures)
2176  code = hash_combine(code, Feature);
2177 
2178  // Extend the signature with the target options.
2179  code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
2180  TargetOpts->ABI);
2181  for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i)
2182  code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]);
2183 
2184  // Extend the signature with preprocessor options.
2185  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
2186  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
2187  code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
2188 
2189  for (std::vector<std::pair<std::string, bool/*isUndef*/>>::const_iterator
2190  I = getPreprocessorOpts().Macros.begin(),
2191  IEnd = getPreprocessorOpts().Macros.end();
2192  I != IEnd; ++I) {
2193  // If we're supposed to ignore this macro for the purposes of modules,
2194  // don't put it into the hash.
2195  if (!hsOpts.ModulesIgnoreMacros.empty()) {
2196  // Check whether we're ignoring this macro.
2197  StringRef MacroDef = I->first;
2198  if (hsOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first))
2199  continue;
2200  }
2201 
2202  code = hash_combine(code, I->first, I->second);
2203  }
2204 
2205  // Extend the signature with the sysroot and other header search options.
2206  code = hash_combine(code, hsOpts.Sysroot,
2207  hsOpts.ModuleFormat,
2208  hsOpts.UseDebugInfo,
2209  hsOpts.UseBuiltinIncludes,
2211  hsOpts.UseStandardCXXIncludes,
2212  hsOpts.UseLibcxx);
2213  code = hash_combine(code, hsOpts.ResourceDir);
2214 
2215  // Extend the signature with the user build path.
2216  code = hash_combine(code, hsOpts.ModuleUserBuildPath);
2217 
2218  // Extend the signature with the module file extensions.
2219  const FrontendOptions &frontendOpts = getFrontendOpts();
2220  for (auto ext : frontendOpts.ModuleFileExtensions) {
2221  code = ext->hashExtension(code);
2222  }
2223 
2224  // Darwin-specific hack: if we have a sysroot, use the contents and
2225  // modification time of
2226  // $sysroot/System/Library/CoreServices/SystemVersion.plist
2227  // as part of the module hash.
2228  if (!hsOpts.Sysroot.empty()) {
2229  SmallString<128> systemVersionFile;
2230  systemVersionFile += hsOpts.Sysroot;
2231  llvm::sys::path::append(systemVersionFile, "System");
2232  llvm::sys::path::append(systemVersionFile, "Library");
2233  llvm::sys::path::append(systemVersionFile, "CoreServices");
2234  llvm::sys::path::append(systemVersionFile, "SystemVersion.plist");
2235 
2236  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
2237  llvm::MemoryBuffer::getFile(systemVersionFile);
2238  if (buffer) {
2239  code = hash_combine(code, buffer.get()->getBuffer());
2240 
2241  struct stat statBuf;
2242  if (stat(systemVersionFile.c_str(), &statBuf) == 0)
2243  code = hash_combine(code, statBuf.st_mtime);
2244  }
2245  }
2246 
2247  return llvm::APInt(64, code).toString(36, /*Signed=*/false);
2248 }
2249 
2250 namespace clang {
2251 
2252 template<typename IntTy>
2253 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
2254  IntTy Default,
2255  DiagnosticsEngine *Diags) {
2256  IntTy Res = Default;
2257  if (Arg *A = Args.getLastArg(Id)) {
2258  if (StringRef(A->getValue()).getAsInteger(10, Res)) {
2259  if (Diags)
2260  Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
2261  << A->getValue();
2262  }
2263  }
2264  return Res;
2265 }
2266 
2267 
2268 // Declared in clang/Frontend/Utils.h.
2269 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
2270  DiagnosticsEngine *Diags) {
2271  return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
2272 }
2273 
2274 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
2275  uint64_t Default,
2276  DiagnosticsEngine *Diags) {
2277  return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
2278 }
2279 
2280 void BuryPointer(const void *Ptr) {
2281  // This function may be called only a small fixed amount of times per each
2282  // invocation, otherwise we do actually have a leak which we want to report.
2283  // If this function is called more than kGraveYardMaxSize times, the pointers
2284  // will not be properly buried and a leak detector will report a leak, which
2285  // is what we want in such case.
2286  static const size_t kGraveYardMaxSize = 16;
2287  LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
2288  static std::atomic<unsigned> GraveYardSize;
2289  unsigned Idx = GraveYardSize++;
2290  if (Idx >= kGraveYardMaxSize)
2291  return;
2292  GraveYard[Idx] = Ptr;
2293 }
2294 
2297  DiagnosticsEngine &Diags) {
2298  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
2299  return vfs::getRealFileSystem();
2300 
2303  // earlier vfs files are on the bottom
2304  for (const std::string &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
2305  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
2306  llvm::MemoryBuffer::getFile(File);
2307  if (!Buffer) {
2308  Diags.Report(diag::err_missing_vfs_overlay_file) << File;
2310  }
2311 
2313  vfs::getVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr);
2314  if (!FS.get()) {
2315  Diags.Report(diag::err_invalid_vfs_overlay) << File;
2317  }
2318  Overlay->pushOverlay(FS);
2319  }
2320  return Overlay;
2321 }
2322 } // end namespace clang
HeaderSearchOptions & getHeaderSearchOpts()
static Visibility parseVisibility(Arg *arg, ArgList &args, DiagnosticsEngine &diags)
Attempt to parse a visibility value out of the given argument.
Expand macros but not #includes.
std::string OutputFile
The output file, if any.
static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args)
static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args)
unsigned InlineMaxStackDepth
The inlining stack depth limit.
Paths for '#include <>' added by '-I'.
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
std::string ObjCMTWhiteListPath
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
Enable migration to add conforming protocols.
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
void addMacroUndef(StringRef Name)
std::vector< std::vector< std::string > > AddPluginArgs
Args to pass to the additional plugins.
Generate pre-compiled module.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
unsigned ImplicitModuleMaps
Implicit module maps.
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:115
static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args)
Defines the clang::FileManager interface and associated types.
Parse and perform semantic analysis.
Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
std::string ModuleUserBuildPath
The directory used for a user build.
static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags)
unsigned IncludeGlobals
Show top-level decls in code completion results.
Emit a .bc file.
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:79
Like System, but headers are implicitly wrapped in extern "C".
DependencyOutputOptions & getDependencyOutputOpts()
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
std::shared_ptr< llvm::Regex > OptimizationRemarkMissedPattern
Regular expression to select optimizations for which we should enable missed optimization remarks...
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
LangStandard - Information about the properties of a particular language standard.
Definition: LangStandard.h:39
static bool isBuiltinFunc(const char *Name)
Returns true if this is a libc/libm function without the '__builtin_' prefix.
Definition: Builtins.cpp:51
bool isGNUMode() const
isGNUMode - Language includes GNU extensions.
Definition: LangStandard.h:86
unsigned IncludeModuleFiles
Include module file dependencies.
Parse ASTs and print them.
Like System, but only used for C++.
std::string EABIVersion
The EABI version to use.
std::string HeaderIncludeOutputFile
The file to write header include output to.
std::vector< std::string > Includes
static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector< std::string > &Levels, DiagnosticsEngine *Diags, DiagnosticLevelMask &M)
Optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
Definition: VersionTuple.h:72
unsigned visualizeExplodedGraphWithGraphViz
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Show all overloads.
Like System, but only used for ObjC++.
Emit only debug info necessary for generating line number tables (-gline-tables-only).
std::unique_ptr< llvm::MemoryBuffer > Buffer
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1117
static bool CreateFromArgs(CompilerInvocation &Res, const char *const *ArgBegin, const char *const *ArgEnd, DiagnosticsEngine &Diags)
Create a compiler invocation from a list of input options.
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:192
#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, DiagnosticsEngine &Diags, const TargetOptions &TargetOpts)
std::vector< std::string > RewriteMapFiles
Set of files definining the rules for the symbol rewriting.
bool hasLineComments() const
Language supports '//' comments.
Definition: LangStandard.h:59
Options for controlling comment parsing.
static const LangStandard & getLangStandardForKind(Kind K)
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:35
std::string ImplicitPTHInclude
The implicit PTH input included at the start of the translation unit, or empty.
static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
Options for controlling the target.
Definition: TargetOptions.h:24
void AddPath(StringRef Path, frontend::IncludeDirGroup Group, bool IsFramework, bool IgnoreSysRoot)
AddPath - Add the Path path to the specified Group list.
bool allowsARC() const
Does this runtime allow ARC at all?
Definition: ObjCRuntime.h:140
void addRemappedFile(StringRef From, StringRef To)
std::string CoverageFile
The filename with path we use for coverage files.
Enable migration to NS_ENUM/NS_OPTIONS macros.
std::vector< std::string > PluginArgs
Args to pass to the plugin.
std::string FixItSuffix
If given, the new suffix for fix-it rewritten files.
std::string SplitDwarfFile
The name for the split debug info file that we'll break out.
Like System, but searched after the system directories.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
std::string ModuleCachePath
The directory used for the module cache.
std::string DebugPass
Enable additional debugging information.
llvm::SmallSetVector< std::string, 16 > ModulesIgnoreMacros
The set of macro names that should be ignored for the purposes of computing the module hash...
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Parse and apply any fixits to the source.
std::vector< std::string > Reciprocals
Definition: TargetOptions.h:49
std::vector< std::string > CudaGpuBinaryFileNames
A list of file names passed with -fcuda-include-gpubinary options to forward to CUDA runtime back-end...
Enable annotation of ObjCMethods of all kinds.
void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader)
AddSystemHeaderPrefix - Override whether #include directives naming a path starting with Prefix shoul...
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:37
IntrusiveRefCntPtr< FileSystem > getVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Gets a FileSystem for a virtual file system described in YAML format.
std::map< std::string, std::string > DebugPrefixMap
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
std::string FPMath
If given, the unit to use for floating point math.
Definition: TargetOptions.h:34
bool isCPlusPlus11() const
isCPlusPlus11 - Language is a C++11 variant (or later).
Definition: LangStandard.h:74
static std::shared_ptr< llvm::Regex > GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args, Arg *RpassArg)
Create a new Regex instance out of the string value in RpassArg.
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
Definition: LangStandard.h:71
unsigned IncludeSystemHeaders
Include system header dependencies.
Don't generate debug info.
Translate input source into HTML.
unsigned DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Emit location information but do not generate debug info in the output.
Enable migration to modern ObjC readwrite property.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
unsigned eagerlyAssumeBinOpBifurcation
The flag regulates if we should eagerly assume evaluations of conditionals, thus, bifurcating the pat...
std::vector< std::string > ASTMergeFiles
The list of AST files to merge.
std::string CodeModel
The code model to use (-mcmodel).
Print DeclContext and their Decls.
std::vector< std::string > ModulesEmbedFiles
The list of files to embed into the compiled module file.
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
Definition: Visibility.h:44
unsigned IncludeCodePatterns
Show code patterns in code completion results.
A module file extension used for testing purposes.
Action - Represent an abstract compilation step to perform.
Definition: Action.h:41
A file system that allows overlaying one AbstractFileSystem on top of another.
Generate LLVM IR, but do not emit anything.
static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
CodeGenOptions & getCodeGenOpts()
unsigned ShowStats
Show frontend performance metrics and statistics.
static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args)
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:32
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned FixWhatYouCan
Apply fixes even if there are unfixable errors.
std::vector< std::string > Warnings
The list of -W...
std::vector< std::pair< std::string, bool > > CheckersControlList
Pair of checker name and enable/disable.
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
AnalysisStores
AnalysisStores - Set of available analysis store models.
detail::InMemoryDirectory::const_iterator I
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, FileManager &FileMgr, DiagnosticsEngine &Diags)
unsigned FixAndRecompile
Apply fixes and recompile.
std::string FloatABI
The ABI to use for passing floating point arguments.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:107
PreprocessorOutputOptions & getPreprocessorOutputOpts()
std::string ThreadModel
The thread model to use.
FrontendOptions & getFrontendOpts()
AnnotatingParser & P
std::vector< std::string > DependentLibraries
A list of dependent libraries.
static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id, IntTy Default, DiagnosticsEngine *Diags)
MigratorOptions & getMigratorOpts()
annotate property with NS_RETURNS_INNER_POINTER
char CoverageVersion[4]
The version string to put into coverage files.
Dump out preprocessed tokens.
std::string CurrentModule
The name of the current module.
Definition: LangOptions.h:96
AnalysisDiagClients AnalysisDiagOpt
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
void AddVFSOverlayFile(StringRef Name)
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g., -E).
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
Enable migration to modern ObjC literals.
bool isCPlusPlus14() const
isCPlusPlus14 - Language is a C++14 variant (or later).
Definition: LangStandard.h:77
uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, uint64_t Default, DiagnosticsEngine *Diags=nullptr)
unsigned UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
AnalysisInliningMode InliningMode
The mode of function selection used during inlining.
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:110
static std::string GetResourcesPath(const char *Argv0, void *MainAddr)
Get the directory where the compiler headers reside, relative to the compiler binary (found by the pa...
unsigned ModuleCachePruneInterval
The interval (in seconds) between pruning operations.
bool hasDigraphs() const
hasDigraphs - Language supports digraphs.
Definition: LangStandard.h:83
std::vector< std::string > Plugins
The list of plugins to load.
Show just the "best" overload candidates.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:121
std::set< std::string > DeserializedPCHDeclsToErrorOn
This is a set of names for decls that we do not want to be deserialized, and we emit an error if they...
unsigned RewriteIncludes
Preprocess include directives only.
unsigned ShowTimers
Show timers for individual actions.
std::string LinkerVersion
If given, the version string of the linker in use.
Definition: TargetOptions.h:40
Only execute frontend initialization.
bool isCPlusPlus1z() const
isCPlusPlus1z - Language is a C++17 variant (or later).
Definition: LangStandard.h:80
Defines version macros and version-related utility functions for Clang.
std::string RelocationModel
The name of the relocation model to use.
Print the "preamble" of the input file.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
bool isC89() const
isC89 - Language is a superset of C89.
Definition: LangStandard.h:62
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
Definition: ObjCRuntime.cpp:44
unsigned ShowHeaderIncludes
Show header inclusions (-H).
std::shared_ptr< llvm::Regex > OptimizationRemarkPattern
Regular expression to select optimizations for which we should enable optimization remarks...
Rewriter playground.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned ModulesEmbedAllFiles
Whether we should embed all used files into the PCM file.
AnalysisInliningMode
AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
Objects with "protected" visibility are seen by the dynamic linker but always dynamically resolve to ...
Definition: Visibility.h:40
unsigned ShowMacros
Print macro definitions.
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:85
static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, ArgList &Args, frontend::ActionKind Action)
unsigned FixOnlyWarnings
Apply fixes only for warnings.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
bool hasImplicitInt() const
hasImplicitInt - Language allows variables to be typed as int implicitly.
Definition: LangStandard.h:92
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector< std::string > &Diagnostics)
std::string AuxTriple
Auxiliary triple for CUDA compilation.
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:31
bool isC99() const
isC99 - Language is a superset of C99.
Definition: LangStandard.h:65
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:61
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr)
Fill out Opts based on the options given in Args.
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:37
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
bool isC11() const
isC11 - Language is a superset of C11.
Definition: LangStandard.h:68
AnalysisStores AnalysisStoreOpt
enum clang::FrontendOptions::@155 ARCMTAction
Encodes a location in the source.
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
Generate machine code, but don't emit anything.
std::vector< std::string > ModuleFiles
The list of additional prebuilt module files to load before processing the input. ...
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
Options for controlling the compiler diagnostics engine.
std::vector< FrontendInputFile > Inputs
The input files and their types.
unsigned ModulesValidateSystemHeaders
Whether to validate system input files when a module is loaded.
AnalyzerOptionsRef getAnalyzerOpts() const
ConfigTable Config
A key-value table of use-specified configuration values.
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)
Parse ASTs and view them in Graphviz.
std::vector< std::string > Remarks
The list of -R...
unsigned visualizeExplodedGraphWithUbiGraph
Parse ASTs and list Decl nodes.
unsigned Verbose
Whether header search information should be output as for -v.
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:90
static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector< std::string > &Funcs)
std::string InstrProfileInput
Name of the profile file to use as input for -fprofile-instr-use.
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
unsigned getMajor() const
Retrieve the major version number.
Definition: VersionTuple.h:69
unsigned ASTDumpLookups
Whether we include lookup table dumps in AST dumps.
std::vector< std::string > ExtraDeps
A list of filenames to be used as extra dependencies for every target.
Load and verify that a PCH file is usable.
static void setLangDefaults(LangOptions &Opts, InputKind IK, LangStandard::Kind LangStd=LangStandard::lang_unspecified)
Set language defaults for the given input language and language standard in the given LangOptions obj...
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
unsigned UseLineDirectives
Use #line instead of GCC-style # N.
Like System, but only used for ObjC.
unsigned ShowVersion
Show the -version text.
Enable converting setter/getter expressions to property-dot syntx.
std::shared_ptr< llvm::Regex > OptimizationRemarkAnalysisPattern
Regular expression to select optimizations for which we should enable optimization analyses...
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
Definition: TargetOptions.h:43
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
void addMacroDef(StringRef Name)
'#include ""' paths, added by 'gcc -iquote'.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::vector< std::string > MacroIncludes
unsigned ShowHelp
Show the -help text.
std::string OverrideRecordLayoutsFile
File name of the file that will provide record layouts (in the format produced by -fdump-record-layou...
unsigned FixToTemporaries
Apply fixes to temporary files.
building frameworks.
static bool parseTestModuleFileExtensionArg(StringRef Arg, std::string &BlockName, unsigned &MajorVersion, unsigned &MinorVersion, bool &Hashed, std::string &UserInfo)
Parse the argument to the -ftest-module-file-extension command-line argument.
unsigned maxBlockVisitOnPath
The maximum number of times the analyzer visits a block.
unsigned DisableAllChecks
Disable all analyzer checks.
std::string OutputFile
The file to write dependency output to.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
DependencyOutputFormat OutputFormat
The format for the dependency file.
unsigned UseDebugInfo
Whether the module includes debug information (-gmodules).
uint64_t SanitizerMask
Definition: Sanitizers.h:24
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
Definition: LangOptions.h:93
Enable migration to modern ObjC readonly property.
bool tryParse(StringRef string)
Try to parse the given string as a version number.
static ParsedSourceLocation FromString(StringRef Str)
Construct a parsed source location from a string; the Filename is empty on error. ...
PreprocessorOptions & getPreprocessorOpts()
frontend::ActionKind ProgramAction
The frontend action to perform.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:117
std::string ARCMTMigrateReportOut
Like System, but only used for C.
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
AnalysisConstraints AnalysisConstraintsOpt
Helper class for holding the data necessary to invoke the compiler.
DiagnosticOptions & getDiagnosticOpts() const
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
unsigned UsePhonyTargets
Include phony targets for each dependency, which can avoid some 'make' problems.
std::string AnalyzeSpecificFunction
FrontendOptions - Options for controlling the behavior of the frontend.
static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args)
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
Definition: Sanitizers.cpp:20
std::string ImplementationOfModule
The name of the module that the translation unit is an implementation of.
Definition: LangOptions.h:101
Run a plugin action,.
static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args)
void BuryPointer(const void *Ptr)
Parse ASTs and dump them.
use NS_NONATOMIC_IOSONLY for property 'atomic' attribute
Enable migration to modern ObjC subscripting.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CodeCompleteOptions CodeCompleteOpts
std::vector< std::string > AddPluginActions
The list of plugin actions to run in addition to the normal action.
Optional< unsigned > getSubminor() const
Retrieve the subminor version number, if provided.
Definition: VersionTuple.h:79
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
AnalysisPurgeMode
AnalysisPurgeModes - Set of available strategies for dead symbol removal.
llvm::opt::OptTable * createDriverOptTable()
Keeps track of options that affect how file operations are performed.
unsigned DisableFree
Disable memory freeing on exit.
Generate pre-compiled header.
int getLastArgIntValue(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, int Default, DiagnosticsEngine *Diags=nullptr)
Return the value of the last argument as an integer, or a default.
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:11761
Kind getKind() const
Definition: ObjCRuntime.h:75
unsigned ShowMacroComments
Show comments, even in macros.
unsigned NoRetryExhausted
Do not re-analyze paths leading to exhausted nodes with a different strategy.
std::string MainFileName
The user provided name for the "main file", if non-empty.
unsigned ModuleCachePruneAfter
The time (in seconds) after which an unused module file will be considered unused and will...
prefer 'atomic' property over 'nonatomic'.
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:113
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
std::string ActionName
The name of the action to run when using a plugin action.
unsigned ShowLineMarkers
Show #line markers.
FileSystemOptions & getFileSystemOpts()
static unsigned getOptimizationLevelSize(ArgList &Args)
Run one or more source code analyses.
#define LANGSTANDARD(id, name, desc, features)
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Enable migration of ObjC methods to 'instancetype'.
std::vector< IntrusiveRefCntPtr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::vector< std::string > LLVMArgs
A list of arguments to forward to LLVM's option processing; this should only be used for debugging an...
std::vector< std::string > Targets
A list of names to use as the targets in the dependency file; this list must contain at least one ent...
std::vector< std::pair< unsigned, std::string > > LinkBitcodeFiles
The name of the bitcode file to link before optzns.
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate and -fprofile-generate.
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
DiagnosticLevelMask
A bitmask representing the diagnostic levels used by VerifyDiagnosticConsumer.
Limit generated debug info to reduce size (-fno-standalone-debug).
Dump information about a module file.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
#define CLANG_VERSION_STRING
A string that describes the Clang version number, e.g., "1.0".
Definition: Version.h:30
unsigned AddMissingHeaderDeps
Add missing headers to dependency list.
std::vector< std::string > SanitizerBlacklistFiles
Paths to blacklist files specifying which objects (files, functions, variables) should not be instrum...
Definition: LangOptions.h:83
unsigned ShowCPP
Print normal preprocessed output.
std::vector< std::string > BackendOptions
A list of command-line options to forward to the LLVM backend.
Like Angled, but marks header maps used when.
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Generate pre-tokenized header.
static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
std::string ObjCConstantStringClass
Definition: LangOptions.h:87
#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)
unsigned IncludeMacros
Show macros in code completion results.
AnalysisPurgeMode AnalysisPurgeOpt
unsigned PrintShowIncludes
Print cl.exe style /showIncludes info.
bool DumpDeserializedPCHDecls
Dump declarations that are deserialized from PCH, for testing.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
std::string Triple
If given, the name of the target triple to compile for.
Definition: TargetOptions.h:28
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)
Defines enum values for all the target-independent builtin functions.
std::string ModuleFormat
The module/pch container format.
static void parseSanitizerKinds(StringRef FlagName, const std::vector< std::string > &Sanitizers, DiagnosticsEngine &Diags, SanitizerSet &S)
std::string DiagnosticLogFile
The file to log diagnostic output to.
std::string TokenCache
If given, a PTH cache file to use for speeding up header parsing.
bool ParseAllComments
Treat ordinary comments as documentation comments.
Enable migration to modern ObjC property.
bool hasHexFloats() const
hasHexFloats - Language supports hexadecimal float constants.
Definition: LangStandard.h:89
std::vector< std::string > ModuleMapFiles
The list of module map files to load before processing the input.