clang  6.0.0svn
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 
12 #include "clang/Basic/Builtins.h"
14 #include "clang/Basic/Version.h"
15 #include "clang/Config/config.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Driver/Util.h"
21 #include "clang/Frontend/Utils.h"
26 #include "llvm/ADT/Hashing.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/Option/Arg.h"
34 #include "llvm/Option/ArgList.h"
35 #include "llvm/Option/OptTable.h"
36 #include "llvm/Option/Option.h"
37 #include "llvm/ProfileData/InstrProfReader.h"
38 #include "llvm/Support/CodeGen.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Process.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/ScopedPrinter.h"
46 #include <atomic>
47 #include <memory>
48 #include <sys/stat.h>
49 #include <system_error>
50 using namespace clang;
51 
52 //===----------------------------------------------------------------------===//
53 // Initialization.
54 //===----------------------------------------------------------------------===//
55 
57  : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
58  DiagnosticOpts(new DiagnosticOptions()),
59  HeaderSearchOpts(new HeaderSearchOptions()),
60  PreprocessorOpts(new PreprocessorOptions()) {}
61 
63  : LangOpts(new LangOptions(*X.getLangOpts())),
68 
70 
71 //===----------------------------------------------------------------------===//
72 // Deserialization (from args)
73 //===----------------------------------------------------------------------===//
74 
75 using namespace clang::driver;
76 using namespace clang::driver::options;
77 using namespace llvm::opt;
78 
79 //
80 
81 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
82  DiagnosticsEngine &Diags) {
83  unsigned DefaultOpt = 0;
84  if (IK.getLanguage() == InputKind::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
85  DefaultOpt = 2;
86 
87  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
88  if (A->getOption().matches(options::OPT_O0))
89  return 0;
90 
91  if (A->getOption().matches(options::OPT_Ofast))
92  return 3;
93 
94  assert (A->getOption().matches(options::OPT_O));
95 
96  StringRef S(A->getValue());
97  if (S == "s" || S == "z" || S.empty())
98  return 2;
99 
100  if (S == "g")
101  return 1;
102 
103  return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
104  }
105 
106  return DefaultOpt;
107 }
108 
109 static unsigned getOptimizationLevelSize(ArgList &Args) {
110  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
111  if (A->getOption().matches(options::OPT_O)) {
112  switch (A->getValue()[0]) {
113  default:
114  return 0;
115  case 's':
116  return 1;
117  case 'z':
118  return 2;
119  }
120  }
121  }
122  return 0;
123 }
124 
125 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
126  OptSpecifier GroupWithValue,
127  std::vector<std::string> &Diagnostics) {
128  for (Arg *A : Args.filtered(Group)) {
129  if (A->getOption().getKind() == Option::FlagClass) {
130  // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
131  // its name (minus the "W" or "R" at the beginning) to the warning list.
132  Diagnostics.push_back(A->getOption().getName().drop_front(1));
133  } else if (A->getOption().matches(GroupWithValue)) {
134  // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
135  Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
136  } else {
137  // Otherwise, add its value (for OPT_W_Joined and similar).
138  for (const char *Arg : A->getValues())
139  Diagnostics.emplace_back(Arg);
140  }
141  }
142 }
143 
144 static void getAllNoBuiltinFuncValues(ArgList &Args,
145  std::vector<std::string> &Funcs) {
147  for (const auto &Arg : Args) {
148  const Option &O = Arg->getOption();
149  if (O.matches(options::OPT_fno_builtin_)) {
150  const char *FuncName = Arg->getValue();
151  if (Builtin::Context::isBuiltinFunc(FuncName))
152  Values.push_back(FuncName);
153  }
154  }
155  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
156 }
157 
158 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
159  DiagnosticsEngine &Diags) {
160  using namespace options;
161  bool Success = true;
162  if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
163  StringRef Name = A->getValue();
164  AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
165 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
166  .Case(CMDFLAG, NAME##Model)
167 #include "clang/StaticAnalyzer/Core/Analyses.def"
168  .Default(NumStores);
169  if (Value == NumStores) {
170  Diags.Report(diag::err_drv_invalid_value)
171  << A->getAsString(Args) << Name;
172  Success = false;
173  } else {
174  Opts.AnalysisStoreOpt = Value;
175  }
176  }
177 
178  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
179  StringRef Name = A->getValue();
180  AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
181 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
182  .Case(CMDFLAG, NAME##Model)
183 #include "clang/StaticAnalyzer/Core/Analyses.def"
184  .Default(NumConstraints);
185  if (Value == NumConstraints) {
186  Diags.Report(diag::err_drv_invalid_value)
187  << A->getAsString(Args) << Name;
188  Success = false;
189  } else {
191  }
192  }
193 
194  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
195  StringRef Name = A->getValue();
196  AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
197 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
198  .Case(CMDFLAG, PD_##NAME)
199 #include "clang/StaticAnalyzer/Core/Analyses.def"
200  .Default(NUM_ANALYSIS_DIAG_CLIENTS);
201  if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
202  Diags.Report(diag::err_drv_invalid_value)
203  << A->getAsString(Args) << Name;
204  Success = false;
205  } else {
206  Opts.AnalysisDiagOpt = Value;
207  }
208  }
209 
210  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
211  StringRef Name = A->getValue();
212  AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
213 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
214  .Case(CMDFLAG, NAME)
215 #include "clang/StaticAnalyzer/Core/Analyses.def"
216  .Default(NumPurgeModes);
217  if (Value == NumPurgeModes) {
218  Diags.Report(diag::err_drv_invalid_value)
219  << A->getAsString(Args) << Name;
220  Success = false;
221  } else {
222  Opts.AnalysisPurgeOpt = Value;
223  }
224  }
225 
226  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
227  StringRef Name = A->getValue();
228  AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
229 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
230  .Case(CMDFLAG, NAME)
231 #include "clang/StaticAnalyzer/Core/Analyses.def"
232  .Default(NumInliningModes);
233  if (Value == NumInliningModes) {
234  Diags.Report(diag::err_drv_invalid_value)
235  << A->getAsString(Args) << Name;
236  Success = false;
237  } else {
238  Opts.InliningMode = Value;
239  }
240  }
241 
242  Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
243  Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
244  Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
245 
247  Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
249  Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
250  Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
251  Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
252  Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
253  Opts.AnalyzeNestedBlocks =
254  Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
255  Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
256  Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
257  Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
258  Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
259  Opts.maxBlockVisitOnPath =
260  getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
261  Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
262  Opts.InlineMaxStackDepth =
263  getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
264  Opts.InlineMaxStackDepth, Diags);
265 
266  Opts.CheckersControlList.clear();
267  for (const Arg *A :
268  Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
269  A->claim();
270  bool enable = (A->getOption().getID() == OPT_analyzer_checker);
271  // We can have a list of comma separated checker names, e.g:
272  // '-analyzer-checker=cocoa,unix'
273  StringRef checkerList = A->getValue();
274  SmallVector<StringRef, 4> checkers;
275  checkerList.split(checkers, ",");
276  for (StringRef checker : checkers)
277  Opts.CheckersControlList.emplace_back(checker, enable);
278  }
279 
280  // Go through the analyzer configuration options.
281  for (const Arg *A : Args.filtered(OPT_analyzer_config)) {
282  A->claim();
283  // We can have a list of comma separated config names, e.g:
284  // '-analyzer-config key1=val1,key2=val2'
285  StringRef configList = A->getValue();
286  SmallVector<StringRef, 4> configVals;
287  configList.split(configVals, ",");
288  for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
289  StringRef key, val;
290  std::tie(key, val) = configVals[i].split("=");
291  if (val.empty()) {
292  Diags.Report(SourceLocation(),
293  diag::err_analyzer_config_no_value) << configVals[i];
294  Success = false;
295  break;
296  }
297  if (val.find('=') != StringRef::npos) {
298  Diags.Report(SourceLocation(),
299  diag::err_analyzer_config_multiple_values)
300  << configVals[i];
301  Success = false;
302  break;
303  }
304  Opts.Config[key] = val;
305  }
306  }
307 
308  return Success;
309 }
310 
311 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
312  Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
313  Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
314  return true;
315 }
316 
317 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
318  Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
319  Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
320 }
321 
322 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
323  if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
324  StringRef Value = A->getValue();
325  if (Value == "small" || Value == "kernel" || Value == "medium" ||
326  Value == "large")
327  return Value;
328  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
329  }
330  return "default";
331 }
332 
333 static StringRef getRelocModel(ArgList &Args, DiagnosticsEngine &Diags) {
334  if (Arg *A = Args.getLastArg(OPT_mrelocation_model)) {
335  StringRef Value = A->getValue();
336  if (Value == "static" || Value == "pic" || Value == "ropi" ||
337  Value == "rwpi" || Value == "ropi-rwpi" || Value == "dynamic-no-pic")
338  return Value;
339  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
340  }
341  return "pic";
342 }
343 
344 /// \brief Create a new Regex instance out of the string value in \p RpassArg.
345 /// It returns a pointer to the newly generated Regex instance.
346 static std::shared_ptr<llvm::Regex>
348  Arg *RpassArg) {
349  StringRef Val = RpassArg->getValue();
350  std::string RegexError;
351  std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
352  if (!Pattern->isValid(RegexError)) {
353  Diags.Report(diag::err_drv_optimization_remark_pattern)
354  << RegexError << RpassArg->getAsString(Args);
355  Pattern.reset();
356  }
357  return Pattern;
358 }
359 
360 static bool parseDiagnosticLevelMask(StringRef FlagName,
361  const std::vector<std::string> &Levels,
362  DiagnosticsEngine *Diags,
363  DiagnosticLevelMask &M) {
364  bool Success = true;
365  for (const auto &Level : Levels) {
366  DiagnosticLevelMask const PM =
367  llvm::StringSwitch<DiagnosticLevelMask>(Level)
368  .Case("note", DiagnosticLevelMask::Note)
369  .Case("remark", DiagnosticLevelMask::Remark)
370  .Case("warning", DiagnosticLevelMask::Warning)
371  .Case("error", DiagnosticLevelMask::Error)
372  .Default(DiagnosticLevelMask::None);
373  if (PM == DiagnosticLevelMask::None) {
374  Success = false;
375  if (Diags)
376  Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
377  }
378  M = M | PM;
379  }
380  return Success;
381 }
382 
383 static void parseSanitizerKinds(StringRef FlagName,
384  const std::vector<std::string> &Sanitizers,
385  DiagnosticsEngine &Diags, SanitizerSet &S) {
386  for (const auto &Sanitizer : Sanitizers) {
387  SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
388  if (K == 0)
389  Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
390  else
391  S.set(K, true);
392  }
393 }
394 
395 // Set the profile kind for fprofile-instrument.
396 static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
397  DiagnosticsEngine &Diags) {
398  Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
399  if (A == nullptr)
400  return;
401  StringRef S = A->getValue();
402  unsigned I = llvm::StringSwitch<unsigned>(S)
403  .Case("none", CodeGenOptions::ProfileNone)
404  .Case("clang", CodeGenOptions::ProfileClangInstr)
405  .Case("llvm", CodeGenOptions::ProfileIRInstr)
406  .Default(~0U);
407  if (I == ~0U) {
408  Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
409  << S;
410  return;
411  }
412  CodeGenOptions::ProfileInstrKind Instrumentor =
413  static_cast<CodeGenOptions::ProfileInstrKind>(I);
414  Opts.setProfileInstr(Instrumentor);
415 }
416 
417 // Set the profile kind using fprofile-instrument-use-path.
419  const Twine &ProfileName) {
420  auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
421  // In error, return silently and let Clang PGOUse report the error message.
422  if (auto E = ReaderOrErr.takeError()) {
423  llvm::consumeError(std::move(E));
424  Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
425  return;
426  }
427  std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
428  std::move(ReaderOrErr.get());
429  if (PGOReader->isIRLevelProfile())
430  Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
431  else
432  Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
433 }
434 
435 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
436  DiagnosticsEngine &Diags,
437  const TargetOptions &TargetOpts) {
438  using namespace options;
439  bool Success = true;
440  llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
441 
442  unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
443  // TODO: This could be done in Driver
444  unsigned MaxOptLevel = 3;
445  if (OptimizationLevel > MaxOptLevel) {
446  // If the optimization level is not supported, fall back on the default
447  // optimization
448  Diags.Report(diag::warn_drv_optimization_value)
449  << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
450  OptimizationLevel = MaxOptLevel;
451  }
452  Opts.OptimizationLevel = OptimizationLevel;
453 
454  // At O0 we want to fully disable inlining outside of cases marked with
455  // 'alwaysinline' that are required for correctness.
456  Opts.setInlining((Opts.OptimizationLevel == 0)
459  // Explicit inlining flags can disable some or all inlining even at
460  // optimization levels above zero.
461  if (Arg *InlineArg = Args.getLastArg(
462  options::OPT_finline_functions, options::OPT_finline_hint_functions,
463  options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
464  if (Opts.OptimizationLevel > 0) {
465  const Option &InlineOpt = InlineArg->getOption();
466  if (InlineOpt.matches(options::OPT_finline_functions))
467  Opts.setInlining(CodeGenOptions::NormalInlining);
468  else if (InlineOpt.matches(options::OPT_finline_hint_functions))
469  Opts.setInlining(CodeGenOptions::OnlyHintInlining);
470  else
471  Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
472  }
473  }
474 
475  Opts.ExperimentalNewPassManager = Args.hasFlag(
476  OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager,
477  /* Default */ false);
478 
479  Opts.DebugPassManager =
480  Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager,
481  /* Default */ false);
482 
483  if (Arg *A = Args.getLastArg(OPT_fveclib)) {
484  StringRef Name = A->getValue();
485  if (Name == "Accelerate")
486  Opts.setVecLib(CodeGenOptions::Accelerate);
487  else if (Name == "SVML")
488  Opts.setVecLib(CodeGenOptions::SVML);
489  else if (Name == "none")
490  Opts.setVecLib(CodeGenOptions::NoLibrary);
491  else
492  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
493  }
494 
495  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
496  unsigned Val =
497  llvm::StringSwitch<unsigned>(A->getValue())
498  .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
499  .Case("limited", codegenoptions::LimitedDebugInfo)
500  .Case("standalone", codegenoptions::FullDebugInfo)
501  .Default(~0U);
502  if (Val == ~0U)
503  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
504  << A->getValue();
505  else
506  Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
507  }
508  if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
509  unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
510  .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
511  .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
512  .Case("sce", unsigned(llvm::DebuggerKind::SCE))
513  .Default(~0U);
514  if (Val == ~0U)
515  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
516  << A->getValue();
517  else
518  Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
519  }
520  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
521  Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
522  Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
523  Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
524  Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
525  Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
526  Opts.EnableSplitDwarf = Args.hasArg(OPT_enable_split_dwarf);
527  Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
528  Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
529  Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
530  Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
531  Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
532 
533  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
534  Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
535 
536  if (const Arg *A =
537  Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
538  Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
539 
540  Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
541  Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
542  Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
543  Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
544  Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
545  Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
546  OPT_fuse_register_sized_bitfield_access);
547  Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
548  Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
549  Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
550  Args.hasArg(OPT_new_struct_path_tbaa);
551  Opts.FineGrainedBitfieldAccesses =
552  Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
553  OPT_fno_fine_grained_bitfield_accesses, false);
554  Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
555  Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants);
556  Opts.NoCommon = Args.hasArg(OPT_fno_common);
557  Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
558  Opts.OptimizeSize = getOptimizationLevelSize(Args);
559  Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
560  Args.hasArg(OPT_ffreestanding));
561  if (Opts.SimplifyLibCalls)
563  Opts.UnrollLoops =
564  Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
565  (Opts.OptimizationLevel > 1));
566  Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
567 
568  Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
569  Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
570  Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
571  Opts.DebugInfoForProfiling = Args.hasFlag(
572  OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
573  Opts.GnuPubnames = Args.hasArg(OPT_ggnu_pubnames);
574 
575  setPGOInstrumentor(Opts, Args, Diags);
576  Opts.InstrProfileOutput =
577  Args.getLastArgValue(OPT_fprofile_instrument_path_EQ);
579  Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ);
580  if (!Opts.ProfileInstrumentUsePath.empty())
582 
583  if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
584  Opts.setClangABICompat(CodeGenOptions::ClangABI::Latest);
585 
586  StringRef Ver = A->getValue();
587  std::pair<StringRef, StringRef> VerParts = Ver.split('.');
588  unsigned Major, Minor = 0;
589 
590  // Check the version number is valid: either 3.x (0 <= x <= 9) or
591  // y or y.0 (4 <= y <= current version).
592  if (!VerParts.first.startswith("0") &&
593  !VerParts.first.getAsInteger(10, Major) &&
594  3 <= Major && Major <= CLANG_VERSION_MAJOR &&
595  (Major == 3 ? VerParts.second.size() == 1 &&
596  !VerParts.second.getAsInteger(10, Minor)
597  : VerParts.first.size() == Ver.size() ||
598  VerParts.second == "0")) {
599  // Got a valid version number.
600  if (Major == 3 && Minor <= 8)
601  Opts.setClangABICompat(CodeGenOptions::ClangABI::Ver3_8);
602  else if (Major <= 4)
603  Opts.setClangABICompat(CodeGenOptions::ClangABI::Ver4);
604  } else if (Ver != "latest") {
605  Diags.Report(diag::err_drv_invalid_value)
606  << A->getAsString(Args) << A->getValue();
607  }
608  }
609 
610  Opts.CoverageMapping =
611  Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
612  Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
613  Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
614  Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
615  Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
616  Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
617  Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
618  Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
619  Opts.CodeModel = getCodeModel(Args, Diags);
620  Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
621  Opts.DisableFPElim =
622  (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg));
623  Opts.DisableFree = Args.hasArg(OPT_disable_free);
624  Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
625  Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
626  Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
627  Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
628  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
629  Args.hasArg(OPT_cl_fast_relaxed_math);
630  Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
631  Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
632  Args.hasArg(OPT_cl_finite_math_only) ||
633  Args.hasArg(OPT_cl_fast_relaxed_math));
634  Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
635  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
636  Args.hasArg(OPT_cl_finite_math_only) ||
637  Args.hasArg(OPT_cl_fast_relaxed_math));
638  Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
639  Args.hasArg(OPT_cl_no_signed_zeros) ||
640  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
641  Args.hasArg(OPT_cl_fast_relaxed_math));
642  Opts.Reassociate = Args.hasArg(OPT_mreassociate);
643  Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero);
644  Opts.CorrectlyRoundedDivSqrt =
645  Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
646  Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
647  Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
648  Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
649  Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
650  Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
651  Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
652  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
653  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
654  Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
655  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
656  Opts.IncrementalLinkerCompatible =
657  Args.hasArg(OPT_mincremental_linker_compatible);
658  Opts.PIECopyRelocations =
659  Args.hasArg(OPT_mpie_copy_relocations);
660  Opts.NoPLT = Args.hasArg(OPT_fno_plt);
661  Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
662  Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
663  Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
664  Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
665  Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
666  Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
667  Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
668  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
669  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
670  Args.hasArg(OPT_cl_fast_relaxed_math);
671  Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
672  Opts.RelocationModel = getRelocModel(Args, Diags);
673  Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
674  if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
675  Diags.Report(diag::err_drv_invalid_value)
676  << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
677  << Opts.ThreadModel;
678  Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
679  Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
680 
681  Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
682  OPT_fno_function_sections, false);
683  Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
684  OPT_fno_data_sections, false);
685  Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
686  OPT_fno_unique_section_names, true);
687 
688  Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
689 
690  Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
691 
692  Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
693 
694  Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
695  Opts.EmitSummaryIndex = false;
696  if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
697  StringRef S = A->getValue();
698  if (S == "thin")
699  Opts.EmitSummaryIndex = true;
700  else if (S != "full")
701  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
702  }
703  Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
704  if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
705  if (IK.getLanguage() != InputKind::LLVM_IR)
706  Diags.Report(diag::err_drv_argument_only_allowed_with)
707  << A->getAsString(Args) << "-x ir";
708  Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
709  }
710  Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ);
711 
712  Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
713 
714  Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
715  Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
716 
717  Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
718 
719  Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
720  Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
721 
722  Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
723  Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
724  Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
725  if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
726  Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file);
727  Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file);
728  Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
729  Opts.CoverageNoFunctionNamesInData =
730  Args.hasArg(OPT_coverage_no_function_names_in_data);
731  Opts.CoverageExitBlockBeforeBody =
732  Args.hasArg(OPT_coverage_exit_block_before_body);
733  if (Args.hasArg(OPT_coverage_version_EQ)) {
734  StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
735  if (CoverageVersion.size() != 4) {
736  Diags.Report(diag::err_drv_invalid_value)
737  << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
738  << CoverageVersion;
739  } else {
740  memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
741  }
742  }
743  }
744  // Handle -fembed-bitcode option.
745  if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
746  StringRef Name = A->getValue();
747  unsigned Model = llvm::StringSwitch<unsigned>(Name)
748  .Case("off", CodeGenOptions::Embed_Off)
749  .Case("all", CodeGenOptions::Embed_All)
750  .Case("bitcode", CodeGenOptions::Embed_Bitcode)
751  .Case("marker", CodeGenOptions::Embed_Marker)
752  .Default(~0U);
753  if (Model == ~0U) {
754  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
755  Success = false;
756  } else
757  Opts.setEmbedBitcode(
758  static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
759  }
760  // FIXME: For backend options that are not yet recorded as function
761  // attributes in the IR, keep track of them so we can embed them in a
762  // separate data section and use them when building the bitcode.
763  if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
764  for (const auto &A : Args) {
765  // Do not encode output and input.
766  if (A->getOption().getID() == options::OPT_o ||
767  A->getOption().getID() == options::OPT_INPUT ||
768  A->getOption().getID() == options::OPT_x ||
769  A->getOption().getID() == options::OPT_fembed_bitcode ||
770  (A->getOption().getGroup().isValid() &&
771  A->getOption().getGroup().getID() == options::OPT_W_Group))
772  continue;
773  ArgStringList ASL;
774  A->render(Args, ASL);
775  for (const auto &arg : ASL) {
776  StringRef ArgStr(arg);
777  Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
778  // using \00 to seperate each commandline options.
779  Opts.CmdArgs.push_back('\0');
780  }
781  }
782  }
783 
784  Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
785  Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
786  Opts.InstrumentFunctionsAfterInlining =
787  Args.hasArg(OPT_finstrument_functions_after_inlining);
788  Opts.InstrumentFunctionEntryBare =
789  Args.hasArg(OPT_finstrument_function_entry_bare);
790  Opts.XRayInstrumentFunctions = Args.hasArg(OPT_fxray_instrument);
791  Opts.XRayAlwaysEmitCustomEvents =
792  Args.hasArg(OPT_fxray_always_emit_customevents);
793  Opts.XRayInstructionThreshold =
794  getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
795  Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
796  Opts.CallFEntry = Args.hasArg(OPT_mfentry);
797  Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
798 
799  if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
800  OPT_compress_debug_sections_EQ)) {
801  if (A->getOption().getID() == OPT_compress_debug_sections) {
802  // TODO: be more clever about the compression type auto-detection
803  Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
804  } else {
805  auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
806  .Case("none", llvm::DebugCompressionType::None)
807  .Case("zlib", llvm::DebugCompressionType::Z)
808  .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
810  Opts.setCompressDebugSections(DCT);
811  }
812  }
813 
814  Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
815  Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
816  for (auto A : Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
818  F.Filename = A->getValue();
819  if (A->getOption().matches(OPT_mlink_cuda_bitcode)) {
820  F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
821  // When linking CUDA bitcode, propagate function attributes so that
822  // e.g. libdevice gets fast-math attrs if we're building with fast-math.
823  F.PropagateAttrs = true;
824  F.Internalize = true;
825  }
826  Opts.LinkBitcodeFiles.push_back(F);
827  }
828  Opts.SanitizeCoverageType =
829  getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
830  Opts.SanitizeCoverageIndirectCalls =
831  Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
832  Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
833  Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
834  Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
835  Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
836  Opts.SanitizeCoverage8bitCounters =
837  Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
838  Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
839  Opts.SanitizeCoverageTracePCGuard =
840  Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
841  Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
842  Opts.SanitizeCoverageInline8bitCounters =
843  Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
844  Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
845  Opts.SanitizeCoverageStackDepth =
846  Args.hasArg(OPT_fsanitize_coverage_stack_depth);
847  Opts.SanitizeMemoryTrackOrigins =
848  getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
849  Opts.SanitizeMemoryUseAfterDtor =
850  Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
851  OPT_fno_sanitize_memory_use_after_dtor,
852  false);
853  Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
854  Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
855  Opts.SanitizeCfiICallGeneralizePointers =
856  Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
857  Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
858  if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
859  OPT_fno_sanitize_address_use_after_scope)) {
860  Opts.SanitizeAddressUseAfterScope =
861  A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
862  }
863  Opts.SanitizeAddressGlobalsDeadStripping =
864  Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
865  Opts.SSPBufferSize =
866  getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
867  Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
868  if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
869  StringRef Val = A->getValue();
870  unsigned StackAlignment = Opts.StackAlignment;
871  Val.getAsInteger(10, StackAlignment);
872  Opts.StackAlignment = StackAlignment;
873  }
874 
875  if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
876  StringRef Val = A->getValue();
877  unsigned StackProbeSize = Opts.StackProbeSize;
878  Val.getAsInteger(0, StackProbeSize);
879  Opts.StackProbeSize = StackProbeSize;
880  }
881 
882  if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
883  StringRef Name = A->getValue();
884  unsigned Method = llvm::StringSwitch<unsigned>(Name)
885  .Case("legacy", CodeGenOptions::Legacy)
886  .Case("non-legacy", CodeGenOptions::NonLegacy)
887  .Case("mixed", CodeGenOptions::Mixed)
888  .Default(~0U);
889  if (Method == ~0U) {
890  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
891  Success = false;
892  } else {
893  Opts.setObjCDispatchMethod(
894  static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
895  }
896  }
897 
898  Opts.EmulatedTLS =
899  Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
900 
901  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
902  StringRef Name = A->getValue();
903  unsigned Model = llvm::StringSwitch<unsigned>(Name)
904  .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
905  .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
906  .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
907  .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
908  .Default(~0U);
909  if (Model == ~0U) {
910  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
911  Success = false;
912  } else {
913  Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
914  }
915  }
916 
917  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
918  StringRef Val = A->getValue();
919  if (Val == "ieee")
920  Opts.FPDenormalMode = "ieee";
921  else if (Val == "preserve-sign")
922  Opts.FPDenormalMode = "preserve-sign";
923  else if (Val == "positive-zero")
924  Opts.FPDenormalMode = "positive-zero";
925  else
926  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
927  }
928 
929  if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
930  if (A->getOption().matches(OPT_fpcc_struct_return)) {
931  Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
932  } else {
933  assert(A->getOption().matches(OPT_freg_struct_return));
934  Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
935  }
936  }
937 
938  Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
939  Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
940  bool NeedLocTracking = false;
941 
942  Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file);
943  if (!Opts.OptRecordFile.empty())
944  NeedLocTracking = true;
945 
946  if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
948  GenerateOptimizationRemarkRegex(Diags, Args, A);
949  NeedLocTracking = true;
950  }
951 
952  if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
954  GenerateOptimizationRemarkRegex(Diags, Args, A);
955  NeedLocTracking = true;
956  }
957 
958  if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
960  GenerateOptimizationRemarkRegex(Diags, Args, A);
961  NeedLocTracking = true;
962  }
963 
964  Opts.DiagnosticsWithHotness =
965  Args.hasArg(options::OPT_fdiagnostics_show_hotness);
966  bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
967  bool UsingProfile = UsingSampleProfile ||
968  (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
969 
970  if (Opts.DiagnosticsWithHotness && !UsingProfile)
971  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
972  << "-fdiagnostics-show-hotness";
973 
974  Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
975  Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
976  if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
977  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
978  << "-fdiagnostics-hotness-threshold=";
979 
980  // If the user requested to use a sample profile for PGO, then the
981  // backend will need to track source location information so the profile
982  // can be incorporated into the IR.
983  if (UsingSampleProfile)
984  NeedLocTracking = true;
985 
986  // If the user requested a flag that requires source locations available in
987  // the backend, make sure that the backend tracks source location information.
988  if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
989  Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
990 
991  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
992 
993  // Parse -fsanitize-recover= arguments.
994  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
995  parseSanitizerKinds("-fsanitize-recover=",
996  Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
997  Opts.SanitizeRecover);
998  parseSanitizerKinds("-fsanitize-trap=",
999  Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1000  Opts.SanitizeTrap);
1001 
1002  Opts.CudaGpuBinaryFileNames =
1003  Args.getAllArgValues(OPT_fcuda_include_gpubinary);
1004 
1005  Opts.Backchain = Args.hasArg(OPT_mbackchain);
1006 
1007  Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1008  Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1009 
1010  return Success;
1011 }
1012 
1014  ArgList &Args) {
1015  using namespace options;
1016  Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1017  Opts.Targets = Args.getAllArgValues(OPT_MT);
1018  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
1019  Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
1020  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
1021  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
1022  Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
1023  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
1024  Opts.PrintShowIncludes = Args.hasArg(OPT_show_includes);
1025  Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
1027  Args.getLastArgValue(OPT_module_dependency_dir);
1028  if (Args.hasArg(OPT_MV))
1030  // Add sanitizer blacklists as extra dependencies.
1031  // They won't be discovered by the regular preprocessor, so
1032  // we let make / ninja to know about this implicit dependency.
1033  Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
1034  // Only the -fmodule-file=<file> form.
1035  for (const Arg *A : Args.filtered(OPT_fmodule_file)) {
1036  StringRef Val = A->getValue();
1037  if (Val.find('=') == StringRef::npos)
1038  Opts.ExtraDeps.push_back(Val);
1039  }
1040 }
1041 
1042 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1043  // Color diagnostics default to auto ("on" if terminal supports) in the driver
1044  // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1045  // Support both clang's -f[no-]color-diagnostics and gcc's
1046  // -f[no-]diagnostics-colors[=never|always|auto].
1047  enum {
1048  Colors_On,
1049  Colors_Off,
1050  Colors_Auto
1051  } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
1052  for (Arg *A : Args) {
1053  const Option &O = A->getOption();
1054  if (O.matches(options::OPT_fcolor_diagnostics) ||
1055  O.matches(options::OPT_fdiagnostics_color)) {
1056  ShowColors = Colors_On;
1057  } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1058  O.matches(options::OPT_fno_diagnostics_color)) {
1059  ShowColors = Colors_Off;
1060  } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
1061  StringRef Value(A->getValue());
1062  if (Value == "always")
1063  ShowColors = Colors_On;
1064  else if (Value == "never")
1065  ShowColors = Colors_Off;
1066  else if (Value == "auto")
1067  ShowColors = Colors_Auto;
1068  }
1069  }
1070  return ShowColors == Colors_On ||
1071  (ShowColors == Colors_Auto &&
1072  llvm::sys::Process::StandardErrHasColors());
1073 }
1074 
1075 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1076  DiagnosticsEngine *Diags) {
1077  bool Success = true;
1078  for (const auto &Prefix : VerifyPrefixes) {
1079  // Every prefix must start with a letter and contain only alphanumeric
1080  // characters, hyphens, and underscores.
1081  auto BadChar = std::find_if(Prefix.begin(), Prefix.end(),
1082  [](char C){return !isAlphanumeric(C)
1083  && C != '-' && C != '_';});
1084  if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1085  Success = false;
1086  if (Diags) {
1087  Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1088  Diags->Report(diag::note_drv_verify_prefix_spelling);
1089  }
1090  }
1091  }
1092  return Success;
1093 }
1094 
1095 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1096  DiagnosticsEngine *Diags,
1097  bool DefaultDiagColor, bool DefaultShowOpt) {
1098  using namespace options;
1099  bool Success = true;
1100 
1101  Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
1102  if (Arg *A =
1103  Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1104  Opts.DiagnosticSerializationFile = A->getValue();
1105  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1106  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1107  Opts.Pedantic = Args.hasArg(OPT_pedantic);
1108  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1109  Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
1110  Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
1111  Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1112  OPT_fno_show_column,
1113  /*Default=*/true);
1114  Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1115  Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
1116  Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
1117  Opts.ShowOptionNames =
1118  Args.hasFlag(OPT_fdiagnostics_show_option,
1119  OPT_fno_diagnostics_show_option, DefaultShowOpt);
1120 
1121  llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1122 
1123  // Default behavior is to not to show note include stacks.
1124  Opts.ShowNoteIncludeStack = false;
1125  if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1126  OPT_fno_diagnostics_show_note_include_stack))
1127  if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1128  Opts.ShowNoteIncludeStack = true;
1129 
1130  StringRef ShowOverloads =
1131  Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1132  if (ShowOverloads == "best")
1133  Opts.setShowOverloads(Ovl_Best);
1134  else if (ShowOverloads == "all")
1135  Opts.setShowOverloads(Ovl_All);
1136  else {
1137  Success = false;
1138  if (Diags)
1139  Diags->Report(diag::err_drv_invalid_value)
1140  << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1141  << ShowOverloads;
1142  }
1143 
1144  StringRef ShowCategory =
1145  Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
1146  if (ShowCategory == "none")
1147  Opts.ShowCategories = 0;
1148  else if (ShowCategory == "id")
1149  Opts.ShowCategories = 1;
1150  else if (ShowCategory == "name")
1151  Opts.ShowCategories = 2;
1152  else {
1153  Success = false;
1154  if (Diags)
1155  Diags->Report(diag::err_drv_invalid_value)
1156  << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1157  << ShowCategory;
1158  }
1159 
1160  StringRef Format =
1161  Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1162  if (Format == "clang")
1163  Opts.setFormat(DiagnosticOptions::Clang);
1164  else if (Format == "msvc")
1165  Opts.setFormat(DiagnosticOptions::MSVC);
1166  else if (Format == "msvc-fallback") {
1167  Opts.setFormat(DiagnosticOptions::MSVC);
1168  Opts.CLFallbackMode = true;
1169  } else if (Format == "vi")
1170  Opts.setFormat(DiagnosticOptions::Vi);
1171  else {
1172  Success = false;
1173  if (Diags)
1174  Diags->Report(diag::err_drv_invalid_value)
1175  << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1176  << Format;
1177  }
1178 
1179  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1180  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1181  Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
1182  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1183  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1184  if (Args.hasArg(OPT_verify))
1185  Opts.VerifyPrefixes.push_back("expected");
1186  // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1187  // then sort it to prepare for fast lookup using std::binary_search.
1188  if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1189  Opts.VerifyDiagnostics = false;
1190  Success = false;
1191  }
1192  else
1193  std::sort(Opts.VerifyPrefixes.begin(), Opts.VerifyPrefixes.end());
1195  Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1196  Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1197  Diags, DiagMask);
1198  if (Args.hasArg(OPT_verify_ignore_unexpected))
1199  DiagMask = DiagnosticLevelMask::All;
1200  Opts.setVerifyIgnoreUnexpected(DiagMask);
1201  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1202  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1203  Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1204  Opts.MacroBacktraceLimit =
1205  getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
1207  Opts.TemplateBacktraceLimit = getLastArgIntValue(
1208  Args, OPT_ftemplate_backtrace_limit,
1210  Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1211  Args, OPT_fconstexpr_backtrace_limit,
1213  Opts.SpellCheckingLimit = getLastArgIntValue(
1214  Args, OPT_fspell_checking_limit,
1216  Opts.SnippetLineLimit = getLastArgIntValue(
1217  Args, OPT_fcaret_diagnostics_max_lines,
1219  Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
1221  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1222  Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1223  if (Diags)
1224  Diags->Report(diag::warn_ignoring_ftabstop_value)
1225  << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1226  }
1227  Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
1228  addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1229  addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1230 
1231  return Success;
1232 }
1233 
1234 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1235  Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1236 }
1237 
1238 /// Parse the argument to the -ftest-module-file-extension
1239 /// command-line argument.
1240 ///
1241 /// \returns true on error, false on success.
1242 static bool parseTestModuleFileExtensionArg(StringRef Arg,
1243  std::string &BlockName,
1244  unsigned &MajorVersion,
1245  unsigned &MinorVersion,
1246  bool &Hashed,
1247  std::string &UserInfo) {
1249  Arg.split(Args, ':', 5);
1250  if (Args.size() < 5)
1251  return true;
1252 
1253  BlockName = Args[0];
1254  if (Args[1].getAsInteger(10, MajorVersion)) return true;
1255  if (Args[2].getAsInteger(10, MinorVersion)) return true;
1256  if (Args[3].getAsInteger(2, Hashed)) return true;
1257  if (Args.size() > 4)
1258  UserInfo = Args[4];
1259  return false;
1260 }
1261 
1262 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1263  DiagnosticsEngine &Diags,
1264  bool &IsHeaderFile) {
1265  using namespace options;
1267  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1268  switch (A->getOption().getID()) {
1269  default:
1270  llvm_unreachable("Invalid option in group!");
1271  case OPT_ast_list:
1272  Opts.ProgramAction = frontend::ASTDeclList; break;
1273  case OPT_ast_dump:
1274  case OPT_ast_dump_all:
1275  case OPT_ast_dump_lookups:
1276  Opts.ProgramAction = frontend::ASTDump; break;
1277  case OPT_ast_print:
1278  Opts.ProgramAction = frontend::ASTPrint; break;
1279  case OPT_ast_view:
1280  Opts.ProgramAction = frontend::ASTView; break;
1281  case OPT_dump_raw_tokens:
1282  Opts.ProgramAction = frontend::DumpRawTokens; break;
1283  case OPT_dump_tokens:
1284  Opts.ProgramAction = frontend::DumpTokens; break;
1285  case OPT_S:
1286  Opts.ProgramAction = frontend::EmitAssembly; break;
1287  case OPT_emit_llvm_bc:
1288  Opts.ProgramAction = frontend::EmitBC; break;
1289  case OPT_emit_html:
1290  Opts.ProgramAction = frontend::EmitHTML; break;
1291  case OPT_emit_llvm:
1292  Opts.ProgramAction = frontend::EmitLLVM; break;
1293  case OPT_emit_llvm_only:
1294  Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1295  case OPT_emit_codegen_only:
1297  case OPT_emit_obj:
1298  Opts.ProgramAction = frontend::EmitObj; break;
1299  case OPT_fixit_EQ:
1300  Opts.FixItSuffix = A->getValue();
1301  // fall-through!
1302  case OPT_fixit:
1303  Opts.ProgramAction = frontend::FixIt; break;
1304  case OPT_emit_module:
1306  case OPT_emit_module_interface:
1308  case OPT_emit_pch:
1309  Opts.ProgramAction = frontend::GeneratePCH; break;
1310  case OPT_emit_pth:
1311  Opts.ProgramAction = frontend::GeneratePTH; break;
1312  case OPT_init_only:
1313  Opts.ProgramAction = frontend::InitOnly; break;
1314  case OPT_fsyntax_only:
1316  case OPT_module_file_info:
1318  case OPT_verify_pch:
1319  Opts.ProgramAction = frontend::VerifyPCH; break;
1320  case OPT_print_decl_contexts:
1322  case OPT_print_preamble:
1323  Opts.ProgramAction = frontend::PrintPreamble; break;
1324  case OPT_E:
1326  case OPT_rewrite_macros:
1327  Opts.ProgramAction = frontend::RewriteMacros; break;
1328  case OPT_rewrite_objc:
1329  Opts.ProgramAction = frontend::RewriteObjC; break;
1330  case OPT_rewrite_test:
1331  Opts.ProgramAction = frontend::RewriteTest; break;
1332  case OPT_analyze:
1333  Opts.ProgramAction = frontend::RunAnalysis; break;
1334  case OPT_migrate:
1335  Opts.ProgramAction = frontend::MigrateSource; break;
1336  case OPT_Eonly:
1338  }
1339  }
1340 
1341  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1342  Opts.Plugins.emplace_back(A->getValue(0));
1344  Opts.ActionName = A->getValue();
1345  }
1346  Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1347  for (const Arg *AA : Args.filtered(OPT_plugin_arg))
1348  Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1349 
1350  for (const std::string &Arg :
1351  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1352  std::string BlockName;
1353  unsigned MajorVersion;
1354  unsigned MinorVersion;
1355  bool Hashed;
1356  std::string UserInfo;
1357  if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1358  MinorVersion, Hashed, UserInfo)) {
1359  Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1360 
1361  continue;
1362  }
1363 
1364  // Add the testing module file extension.
1365  Opts.ModuleFileExtensions.push_back(
1366  std::make_shared<TestModuleFileExtension>(
1367  BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
1368  }
1369 
1370  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1371  Opts.CodeCompletionAt =
1372  ParsedSourceLocation::FromString(A->getValue());
1373  if (Opts.CodeCompletionAt.FileName.empty())
1374  Diags.Report(diag::err_drv_invalid_value)
1375  << A->getAsString(Args) << A->getValue();
1376  }
1377  Opts.DisableFree = Args.hasArg(OPT_disable_free);
1378 
1379  Opts.OutputFile = Args.getLastArgValue(OPT_o);
1380  Opts.Plugins = Args.getAllArgValues(OPT_load);
1381  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1382  Opts.ShowHelp = Args.hasArg(OPT_help);
1383  Opts.ShowStats = Args.hasArg(OPT_print_stats);
1384  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1385  Opts.ShowVersion = Args.hasArg(OPT_version);
1386  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1387  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1388  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1389  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1390  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1391  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1392  Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
1393  Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all);
1394  Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
1395  Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
1396  Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
1398  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1399  // Only the -fmodule-file=<file> form.
1400  for (const Arg *A : Args.filtered(OPT_fmodule_file)) {
1401  StringRef Val = A->getValue();
1402  if (Val.find('=') == StringRef::npos)
1403  Opts.ModuleFiles.push_back(Val);
1404  }
1405  Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1406  Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
1407  Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
1408 
1410  = Args.hasArg(OPT_code_completion_macros);
1412  = Args.hasArg(OPT_code_completion_patterns);
1414  = !Args.hasArg(OPT_no_code_completion_globals);
1416  = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
1418  = Args.hasArg(OPT_code_completion_brief_comments);
1419 
1421  = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
1422  Opts.AuxTriple =
1423  llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple));
1424  Opts.FindPchSource = Args.getLastArgValue(OPT_find_pch_source_EQ);
1425  Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
1426 
1427  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1428  OPT_arcmt_modify,
1429  OPT_arcmt_migrate)) {
1430  switch (A->getOption().getID()) {
1431  default:
1432  llvm_unreachable("missed a case");
1433  case OPT_arcmt_check:
1435  break;
1436  case OPT_arcmt_modify:
1438  break;
1439  case OPT_arcmt_migrate:
1441  break;
1442  }
1443  }
1444  Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
1446  = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1448  = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1449 
1450  if (Args.hasArg(OPT_objcmt_migrate_literals))
1452  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1454  if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1456  if (Args.hasArg(OPT_objcmt_migrate_property))
1458  if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1460  if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1462  if (Args.hasArg(OPT_objcmt_migrate_annotation))
1464  if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1466  if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1468  if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1470  if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1472  if (Args.hasArg(OPT_objcmt_atomic_property))
1474  if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1476  if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1478  if (Args.hasArg(OPT_objcmt_migrate_all))
1480 
1481  Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
1482 
1485  Diags.Report(diag::err_drv_argument_not_allowed_with)
1486  << "ARC migration" << "ObjC migration";
1487  }
1488 
1490  if (const Arg *A = Args.getLastArg(OPT_x)) {
1491  StringRef XValue = A->getValue();
1492 
1493  // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1494  // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1495  bool Preprocessed = XValue.consume_back("-cpp-output");
1496  bool ModuleMap = XValue.consume_back("-module-map");
1497  IsHeaderFile =
1498  !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1499 
1500  // Principal languages.
1501  DashX = llvm::StringSwitch<InputKind>(XValue)
1502  .Case("c", InputKind::C)
1503  .Case("cl", InputKind::OpenCL)
1504  .Case("cuda", InputKind::CUDA)
1505  .Case("c++", InputKind::CXX)
1506  .Case("objective-c", InputKind::ObjC)
1507  .Case("objective-c++", InputKind::ObjCXX)
1508  .Case("renderscript", InputKind::RenderScript)
1509  .Default(InputKind::Unknown);
1510 
1511  // "objc[++]-cpp-output" is an acceptable synonym for
1512  // "objective-c[++]-cpp-output".
1513  if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1514  DashX = llvm::StringSwitch<InputKind>(XValue)
1515  .Case("objc", InputKind::ObjC)
1516  .Case("objc++", InputKind::ObjCXX)
1517  .Default(InputKind::Unknown);
1518 
1519  // Some special cases cannot be combined with suffixes.
1520  if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1521  DashX = llvm::StringSwitch<InputKind>(XValue)
1522  .Case("cpp-output", InputKind(InputKind::C).getPreprocessed())
1523  .Case("assembler-with-cpp", InputKind::Asm)
1524  .Cases("ast", "pcm",
1526  .Case("ir", InputKind::LLVM_IR)
1527  .Default(InputKind::Unknown);
1528 
1529  if (DashX.isUnknown())
1530  Diags.Report(diag::err_drv_invalid_value)
1531  << A->getAsString(Args) << A->getValue();
1532 
1533  if (Preprocessed)
1534  DashX = DashX.getPreprocessed();
1535  if (ModuleMap)
1536  DashX = DashX.withFormat(InputKind::ModuleMap);
1537  }
1538 
1539  // '-' is the default input if none is given.
1540  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1541  Opts.Inputs.clear();
1542  if (Inputs.empty())
1543  Inputs.push_back("-");
1544  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1545  InputKind IK = DashX;
1546  if (IK.isUnknown()) {
1548  StringRef(Inputs[i]).rsplit('.').second);
1549  // FIXME: Warn on this?
1550  if (IK.isUnknown())
1551  IK = InputKind::C;
1552  // FIXME: Remove this hack.
1553  if (i == 0)
1554  DashX = IK;
1555  }
1556 
1557  // The -emit-module action implicitly takes a module map.
1559  IK.getFormat() == InputKind::Source)
1561 
1562  Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
1563  }
1564 
1565  return DashX;
1566 }
1567 
1568 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1569  void *MainAddr) {
1570  std::string ClangExecutable =
1571  llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1572  StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
1573 
1574  // Compute the path to the resource directory.
1575  StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1576  SmallString<128> P(Dir);
1577  if (ClangResourceDir != "")
1578  llvm::sys::path::append(P, ClangResourceDir);
1579  else
1580  llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX,
1581  "clang", CLANG_VERSION_STRING);
1582 
1583  return P.str();
1584 }
1585 
1586 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1587  const std::string &WorkingDir) {
1588  using namespace options;
1589  Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
1590  Opts.Verbose = Args.hasArg(OPT_v);
1591  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
1592  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
1593  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
1594  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1595  Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1596  Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
1597 
1598  // Canonicalize -fmodules-cache-path before storing it.
1599  SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1600  if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1601  if (WorkingDir.empty())
1602  llvm::sys::fs::make_absolute(P);
1603  else
1604  llvm::sys::fs::make_absolute(WorkingDir, P);
1605  }
1606  llvm::sys::path::remove_dots(P);
1607  Opts.ModuleCachePath = P.str();
1608 
1609  Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
1610  // Only the -fmodule-file=<name>=<file> form.
1611  for (const Arg *A : Args.filtered(OPT_fmodule_file)) {
1612  StringRef Val = A->getValue();
1613  if (Val.find('=') != StringRef::npos)
1614  Opts.PrebuiltModuleFiles.insert(Val.split('='));
1615  }
1616  for (const Arg *A : Args.filtered(OPT_fprebuilt_module_path))
1617  Opts.AddPrebuiltModulePath(A->getValue());
1618  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
1619  Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
1621  !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
1622  Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
1623  Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
1625  getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1626  Opts.ModuleCachePruneAfter =
1627  getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
1629  Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1630  Opts.BuildSessionTimestamp =
1631  getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
1633  Args.hasArg(OPT_fmodules_validate_system_headers);
1634  if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1635  Opts.ModuleFormat = A->getValue();
1636 
1637  for (const Arg *A : Args.filtered(OPT_fmodules_ignore_macro)) {
1638  StringRef MacroDef = A->getValue();
1639  Opts.ModulesIgnoreMacros.insert(
1640  llvm::CachedHashString(MacroDef.split('=').first));
1641  }
1642 
1643  // Add -I..., -F..., and -index-header-map options in order.
1644  bool IsIndexHeaderMap = false;
1645  bool IsSysrootSpecified =
1646  Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
1647  for (const Arg *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
1648  if (A->getOption().matches(OPT_index_header_map)) {
1649  // -index-header-map applies to the next -I or -F.
1650  IsIndexHeaderMap = true;
1651  continue;
1652  }
1653 
1655  IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1656 
1657  bool IsFramework = A->getOption().matches(OPT_F);
1658  std::string Path = A->getValue();
1659 
1660  if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1661  SmallString<32> Buffer;
1662  llvm::sys::path::append(Buffer, Opts.Sysroot,
1663  llvm::StringRef(A->getValue()).substr(1));
1664  Path = Buffer.str();
1665  }
1666 
1667  Opts.AddPath(Path, Group, IsFramework,
1668  /*IgnoreSysroot*/ true);
1669  IsIndexHeaderMap = false;
1670  }
1671 
1672  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
1673  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1674  for (const Arg *A :
1675  Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
1676  if (A->getOption().matches(OPT_iprefix))
1677  Prefix = A->getValue();
1678  else if (A->getOption().matches(OPT_iwithprefix))
1679  Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
1680  else
1681  Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
1682  }
1683 
1684  for (const Arg *A : Args.filtered(OPT_idirafter))
1685  Opts.AddPath(A->getValue(), frontend::After, false, true);
1686  for (const Arg *A : Args.filtered(OPT_iquote))
1687  Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
1688  for (const Arg *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
1689  Opts.AddPath(A->getValue(), frontend::System, false,
1690  !A->getOption().matches(OPT_iwithsysroot));
1691  for (const Arg *A : Args.filtered(OPT_iframework))
1692  Opts.AddPath(A->getValue(), frontend::System, true, true);
1693  for (const Arg *A : Args.filtered(OPT_iframeworkwithsysroot))
1694  Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
1695  /*IgnoreSysRoot=*/false);
1696 
1697  // Add the paths for the various language specific isystem flags.
1698  for (const Arg *A : Args.filtered(OPT_c_isystem))
1699  Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
1700  for (const Arg *A : Args.filtered(OPT_cxx_isystem))
1701  Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
1702  for (const Arg *A : Args.filtered(OPT_objc_isystem))
1703  Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
1704  for (const Arg *A : Args.filtered(OPT_objcxx_isystem))
1705  Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1706 
1707  // Add the internal paths from a driver that detects standard include paths.
1708  for (const Arg *A :
1709  Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1711  if (A->getOption().matches(OPT_internal_externc_isystem))
1712  Group = frontend::ExternCSystem;
1713  Opts.AddPath(A->getValue(), Group, false, true);
1714  }
1715 
1716  // Add the path prefixes which are implicitly treated as being system headers.
1717  for (const Arg *A :
1718  Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1719  Opts.AddSystemHeaderPrefix(
1720  A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1721 
1722  for (const Arg *A : Args.filtered(OPT_ivfsoverlay))
1723  Opts.AddVFSOverlayFile(A->getValue());
1724 }
1725 
1727  const llvm::Triple &T,
1728  PreprocessorOptions &PPOpts,
1729  LangStandard::Kind LangStd) {
1730  // Set some properties which depend solely on the input kind; it would be nice
1731  // to move these to the language standard, and have the driver resolve the
1732  // input kind + language standard.
1733  //
1734  // FIXME: Perhaps a better model would be for a single source file to have
1735  // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
1736  // simultaneously active?
1737  if (IK.getLanguage() == InputKind::Asm) {
1738  Opts.AsmPreprocessor = 1;
1739  } else if (IK.isObjectiveC()) {
1740  Opts.ObjC1 = Opts.ObjC2 = 1;
1741  }
1742 
1743  if (LangStd == LangStandard::lang_unspecified) {
1744  // Based on the base language, pick one.
1745  switch (IK.getLanguage()) {
1746  case InputKind::Unknown:
1747  case InputKind::LLVM_IR:
1748  llvm_unreachable("Invalid input kind!");
1749  case InputKind::OpenCL:
1750  LangStd = LangStandard::lang_opencl10;
1751  break;
1752  case InputKind::CUDA:
1753  LangStd = LangStandard::lang_cuda;
1754  break;
1755  case InputKind::Asm:
1756  case InputKind::C:
1757  // The PS4 uses C99 as the default C standard.
1758  if (T.isPS4())
1759  LangStd = LangStandard::lang_gnu99;
1760  else
1761  LangStd = LangStandard::lang_gnu11;
1762  break;
1763  case InputKind::ObjC:
1764  LangStd = LangStandard::lang_gnu11;
1765  break;
1766  case InputKind::CXX:
1767  case InputKind::ObjCXX:
1768  LangStd = LangStandard::lang_gnucxx14;
1769  break;
1771  LangStd = LangStandard::lang_c99;
1772  break;
1773  }
1774  }
1775 
1776  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1777  Opts.LineComment = Std.hasLineComments();
1778  Opts.C99 = Std.isC99();
1779  Opts.C11 = Std.isC11();
1780  Opts.C17 = Std.isC17();
1781  Opts.CPlusPlus = Std.isCPlusPlus();
1782  Opts.CPlusPlus11 = Std.isCPlusPlus11();
1783  Opts.CPlusPlus14 = Std.isCPlusPlus14();
1784  Opts.CPlusPlus17 = Std.isCPlusPlus17();
1785  Opts.CPlusPlus2a = Std.isCPlusPlus2a();
1786  Opts.Digraphs = Std.hasDigraphs();
1787  Opts.GNUMode = Std.isGNUMode();
1788  Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
1789  Opts.HexFloats = Std.hasHexFloats();
1790  Opts.ImplicitInt = Std.hasImplicitInt();
1791 
1792  // Set OpenCL Version.
1793  Opts.OpenCL = Std.isOpenCL();
1794  if (LangStd == LangStandard::lang_opencl10)
1795  Opts.OpenCLVersion = 100;
1796  else if (LangStd == LangStandard::lang_opencl11)
1797  Opts.OpenCLVersion = 110;
1798  else if (LangStd == LangStandard::lang_opencl12)
1799  Opts.OpenCLVersion = 120;
1800  else if (LangStd == LangStandard::lang_opencl20)
1801  Opts.OpenCLVersion = 200;
1802 
1803  // OpenCL has some additional defaults.
1804  if (Opts.OpenCL) {
1805  Opts.AltiVec = 0;
1806  Opts.ZVector = 0;
1807  Opts.LaxVectorConversions = 0;
1808  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
1809  Opts.NativeHalfType = 1;
1810  Opts.NativeHalfArgsAndReturns = 1;
1811  // Include default header file for OpenCL.
1812  if (Opts.IncludeDefaultHeader) {
1813  PPOpts.Includes.push_back("opencl-c.h");
1814  }
1815  }
1816 
1817  Opts.CUDA = IK.getLanguage() == InputKind::CUDA;
1818  if (Opts.CUDA)
1819  // Set default FP_CONTRACT to FAST.
1820  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
1821 
1822  Opts.RenderScript = IK.getLanguage() == InputKind::RenderScript;
1823  if (Opts.RenderScript) {
1824  Opts.NativeHalfType = 1;
1825  Opts.NativeHalfArgsAndReturns = 1;
1826  }
1827 
1828  // OpenCL and C++ both have bool, true, false keywords.
1829  Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1830 
1831  // OpenCL has half keyword
1832  Opts.Half = Opts.OpenCL;
1833 
1834  // C++ has wchar_t keyword.
1835  Opts.WChar = Opts.CPlusPlus;
1836 
1837  Opts.GNUKeywords = Opts.GNUMode;
1838  Opts.CXXOperatorNames = Opts.CPlusPlus;
1839 
1840  Opts.AlignedAllocation = Opts.CPlusPlus17;
1841 
1842  Opts.DollarIdents = !Opts.AsmPreprocessor;
1843 }
1844 
1845 /// Attempt to parse a visibility value out of the given argument.
1846 static Visibility parseVisibility(Arg *arg, ArgList &args,
1847  DiagnosticsEngine &diags) {
1848  StringRef value = arg->getValue();
1849  if (value == "default") {
1850  return DefaultVisibility;
1851  } else if (value == "hidden" || value == "internal") {
1852  return HiddenVisibility;
1853  } else if (value == "protected") {
1854  // FIXME: diagnose if target does not support protected visibility
1855  return ProtectedVisibility;
1856  }
1857 
1858  diags.Report(diag::err_drv_invalid_value)
1859  << arg->getAsString(args) << value;
1860  return DefaultVisibility;
1861 }
1862 
1863 /// Check if input file kind and language standard are compatible.
1865  const LangStandard &S) {
1866  switch (IK.getLanguage()) {
1867  case InputKind::Unknown:
1868  case InputKind::LLVM_IR:
1869  llvm_unreachable("should not parse language flags for this input");
1870 
1871  case InputKind::C:
1872  case InputKind::ObjC:
1874  return S.getLanguage() == InputKind::C;
1875 
1876  case InputKind::OpenCL:
1877  return S.getLanguage() == InputKind::OpenCL;
1878 
1879  case InputKind::CXX:
1880  case InputKind::ObjCXX:
1881  return S.getLanguage() == InputKind::CXX;
1882 
1883  case InputKind::CUDA:
1884  // FIXME: What -std= values should be permitted for CUDA compilations?
1885  return S.getLanguage() == InputKind::CUDA ||
1886  S.getLanguage() == InputKind::CXX;
1887 
1888  case InputKind::Asm:
1889  // Accept (and ignore) all -std= values.
1890  // FIXME: The -std= value is not ignored; it affects the tokenization
1891  // and preprocessing rules if we're preprocessing this asm input.
1892  return true;
1893  }
1894 
1895  llvm_unreachable("unexpected input language");
1896 }
1897 
1898 /// Get language name for given input kind.
1899 static const StringRef GetInputKindName(InputKind IK) {
1900  switch (IK.getLanguage()) {
1901  case InputKind::C:
1902  return "C";
1903  case InputKind::ObjC:
1904  return "Objective-C";
1905  case InputKind::CXX:
1906  return "C++";
1907  case InputKind::ObjCXX:
1908  return "Objective-C++";
1909  case InputKind::OpenCL:
1910  return "OpenCL";
1911  case InputKind::CUDA:
1912  return "CUDA";
1914  return "RenderScript";
1915 
1916  case InputKind::Asm:
1917  return "Asm";
1918  case InputKind::LLVM_IR:
1919  return "LLVM IR";
1920 
1921  case InputKind::Unknown:
1922  break;
1923  }
1924  llvm_unreachable("unknown input language");
1925 }
1926 
1927 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
1928  const TargetOptions &TargetOpts,
1929  PreprocessorOptions &PPOpts,
1930  DiagnosticsEngine &Diags) {
1931  // FIXME: Cleanup per-file based stuff.
1933  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
1934  LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1935 #define LANGSTANDARD(id, name, lang, desc, features) \
1936  .Case(name, LangStandard::lang_##id)
1937 #define LANGSTANDARD_ALIAS(id, alias) \
1938  .Case(alias, LangStandard::lang_##id)
1939 #include "clang/Frontend/LangStandards.def"
1941  if (LangStd == LangStandard::lang_unspecified) {
1942  Diags.Report(diag::err_drv_invalid_value)
1943  << A->getAsString(Args) << A->getValue();
1944  // Report supported standards with short description.
1945  for (unsigned KindValue = 0;
1946  KindValue != LangStandard::lang_unspecified;
1947  ++KindValue) {
1949  static_cast<LangStandard::Kind>(KindValue));
1950  if (IsInputCompatibleWithStandard(IK, Std)) {
1951  auto Diag = Diags.Report(diag::note_drv_use_standard);
1952  Diag << Std.getName() << Std.getDescription();
1953  unsigned NumAliases = 0;
1954 #define LANGSTANDARD(id, name, lang, desc, features)
1955 #define LANGSTANDARD_ALIAS(id, alias) \
1956  if (KindValue == LangStandard::lang_##id) ++NumAliases;
1957 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
1958 #include "clang/Frontend/LangStandards.def"
1959  Diag << NumAliases;
1960 #define LANGSTANDARD(id, name, lang, desc, features)
1961 #define LANGSTANDARD_ALIAS(id, alias) \
1962  if (KindValue == LangStandard::lang_##id) Diag << alias;
1963 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
1964 #include "clang/Frontend/LangStandards.def"
1965  }
1966  }
1967  } else {
1968  // Valid standard, check to make sure language and standard are
1969  // compatible.
1970  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1971  if (!IsInputCompatibleWithStandard(IK, Std)) {
1972  Diags.Report(diag::err_drv_argument_not_allowed_with)
1973  << A->getAsString(Args) << GetInputKindName(IK);
1974  }
1975  }
1976  }
1977 
1978  // -cl-std only applies for OpenCL language standards.
1979  // Override the -std option in this case.
1980  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
1981  LangStandard::Kind OpenCLLangStd
1982  = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1983  .Cases("cl", "CL", LangStandard::lang_opencl10)
1984  .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
1985  .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
1986  .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
1988 
1989  if (OpenCLLangStd == LangStandard::lang_unspecified) {
1990  Diags.Report(diag::err_drv_invalid_value)
1991  << A->getAsString(Args) << A->getValue();
1992  }
1993  else
1994  LangStd = OpenCLLangStd;
1995  }
1996 
1997  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
1998 
1999  llvm::Triple T(TargetOpts.Triple);
2000  CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
2001 
2002  // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2003  // This option should be deprecated for CL > 1.0 because
2004  // this option was added for compatibility with OpenCL 1.0.
2005  if (Args.getLastArg(OPT_cl_strict_aliasing)
2006  && Opts.OpenCLVersion > 100) {
2007  std::string VerSpec = llvm::to_string(Opts.OpenCLVersion / 100) +
2008  std::string(".") +
2009  llvm::to_string((Opts.OpenCLVersion % 100) / 10);
2010  Diags.Report(diag::warn_option_invalid_ocl_version)
2011  << VerSpec << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
2012  }
2013 
2014  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2015  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2016  // while a subset (the non-C++ GNU keywords) is provided by GCC's
2017  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2018  // name, as it doesn't seem a useful distinction.
2019  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
2020  Opts.GNUKeywords);
2021 
2022  if (Args.hasArg(OPT_fno_operator_names))
2023  Opts.CXXOperatorNames = 0;
2024 
2025  if (Args.hasArg(OPT_fcuda_is_device))
2026  Opts.CUDAIsDevice = 1;
2027 
2028  if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2029  Opts.CUDAAllowVariadicFunctions = 1;
2030 
2031  if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2032  Opts.CUDAHostDeviceConstexpr = 0;
2033 
2034  if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_flush_denormals_to_zero))
2035  Opts.CUDADeviceFlushDenormalsToZero = 1;
2036 
2037  if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2038  Opts.CUDADeviceApproxTranscendentals = 1;
2039 
2040  if (Opts.ObjC1) {
2041  if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2042  StringRef value = arg->getValue();
2043  if (Opts.ObjCRuntime.tryParse(value))
2044  Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2045  }
2046 
2047  if (Args.hasArg(OPT_fobjc_gc_only))
2048  Opts.setGC(LangOptions::GCOnly);
2049  else if (Args.hasArg(OPT_fobjc_gc))
2050  Opts.setGC(LangOptions::HybridGC);
2051  else if (Args.hasArg(OPT_fobjc_arc)) {
2052  Opts.ObjCAutoRefCount = 1;
2053  if (!Opts.ObjCRuntime.allowsARC())
2054  Diags.Report(diag::err_arc_unsupported_on_runtime);
2055  }
2056 
2057  // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2058  // whether the feature is actually enabled. This is predominantly
2059  // determined by -fobjc-runtime, but we allow it to be overridden
2060  // from the command line for testing purposes.
2061  if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2062  Opts.ObjCWeakRuntime = 1;
2063  else
2064  Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2065 
2066  // ObjCWeak determines whether __weak is actually enabled.
2067  // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2068  if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2069  if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2070  assert(!Opts.ObjCWeak);
2071  } else if (Opts.getGC() != LangOptions::NonGC) {
2072  Diags.Report(diag::err_objc_weak_with_gc);
2073  } else if (!Opts.ObjCWeakRuntime) {
2074  Diags.Report(diag::err_objc_weak_unsupported);
2075  } else {
2076  Opts.ObjCWeak = 1;
2077  }
2078  } else if (Opts.ObjCAutoRefCount) {
2079  Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2080  }
2081 
2082  if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2083  Opts.ObjCInferRelatedResultType = 0;
2084 
2085  if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2086  Opts.ObjCSubscriptingLegacyRuntime =
2088  }
2089 
2090  if (Args.hasArg(OPT_fgnu89_inline)) {
2091  if (Opts.CPlusPlus)
2092  Diags.Report(diag::err_drv_argument_not_allowed_with)
2093  << "-fgnu89-inline" << GetInputKindName(IK);
2094  else
2095  Opts.GNUInline = 1;
2096  }
2097 
2098  if (Args.hasArg(OPT_fapple_kext)) {
2099  if (!Opts.CPlusPlus)
2100  Diags.Report(diag::warn_c_kext);
2101  else
2102  Opts.AppleKext = 1;
2103  }
2104 
2105  if (Args.hasArg(OPT_print_ivar_layout))
2106  Opts.ObjCGCBitmapPrint = 1;
2107  if (Args.hasArg(OPT_fno_constant_cfstrings))
2108  Opts.NoConstantCFStrings = 1;
2109 
2110  if (Args.hasArg(OPT_fzvector))
2111  Opts.ZVector = 1;
2112 
2113  if (Args.hasArg(OPT_pthread))
2114  Opts.POSIXThreads = 1;
2115 
2116  // The value-visibility mode defaults to "default".
2117  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2118  Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2119  } else {
2120  Opts.setValueVisibilityMode(DefaultVisibility);
2121  }
2122 
2123  // The type-visibility mode defaults to the value-visibility mode.
2124  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2125  Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2126  } else {
2127  Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2128  }
2129 
2130  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2131  Opts.InlineVisibilityHidden = 1;
2132 
2133  if (Args.hasArg(OPT_ftrapv)) {
2134  Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2135  // Set the handler, if one is specified.
2136  Opts.OverflowHandler =
2137  Args.getLastArgValue(OPT_ftrapv_handler);
2138  }
2139  else if (Args.hasArg(OPT_fwrapv))
2140  Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2141 
2142  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2143  Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2144  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
2145  Opts.MSCompatibilityVersion = 0;
2146  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2147  VersionTuple VT;
2148  if (VT.tryParse(A->getValue()))
2149  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2150  << A->getValue();
2151  Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2152  VT.getMinor().getValueOr(0) * 100000 +
2153  VT.getSubminor().getValueOr(0);
2154  }
2155 
2156  // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
2157  // is specified, or -std is set to a conforming mode.
2158  // Trigraphs are disabled by default in c++1z onwards.
2159  Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
2160  Opts.Trigraphs =
2161  Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2162 
2163  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2164  OPT_fno_dollars_in_identifiers,
2165  Opts.DollarIdents);
2166  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
2167  Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
2168  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
2169  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
2170  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2171  Opts.ConstStrings);
2172  if (Args.hasArg(OPT_fno_lax_vector_conversions))
2173  Opts.LaxVectorConversions = 0;
2174  if (Args.hasArg(OPT_fno_threadsafe_statics))
2175  Opts.ThreadsafeStatics = 0;
2176  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
2177  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
2178  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
2179 
2180  // Handle exception personalities
2181  Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
2182  options::OPT_fseh_exceptions,
2183  options::OPT_fdwarf_exceptions);
2184  if (A) {
2185  const Option &Opt = A->getOption();
2186  Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2187  Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2188  Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2189  }
2190 
2191  Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
2192  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
2193 
2194  Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
2195  Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
2196  Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
2197  && Opts.OpenCLVersion >= 200);
2198  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
2199  Opts.CoroutinesTS = Args.hasArg(OPT_fcoroutines_ts);
2200 
2201  // Enable [[]] attributes in C++11 by default.
2202  Opts.DoubleSquareBracketAttributes =
2203  Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2204  OPT_fno_double_square_bracket_attributes, Opts.CPlusPlus11);
2205 
2206  Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2207  Opts.Modules = Args.hasArg(OPT_fmodules) || Opts.ModulesTS;
2208  Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2209  Opts.ModulesDeclUse =
2210  Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
2211  Opts.ModulesLocalVisibility =
2212  Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS;
2213  Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2214  Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
2215  Opts.ModulesSearchAll = Opts.Modules &&
2216  !Args.hasArg(OPT_fno_modules_search_all) &&
2217  Args.hasArg(OPT_fmodules_search_all);
2218  Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
2219  Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
2220  Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
2221  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
2222  if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2223  Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2224  .Case("char", 1)
2225  .Case("short", 2)
2226  .Case("int", 4)
2227  .Default(0);
2228  if (Opts.WCharSize == 0)
2229  Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2230  }
2231  Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
2232  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
2233  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2234  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2235  if (!Opts.NoBuiltin)
2237  Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
2238  Opts.RelaxedTemplateTemplateArgs =
2239  Args.hasArg(OPT_frelaxed_template_template_args);
2240  Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
2241  Opts.AlignedAllocation =
2242  Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2243  Opts.AlignedAllocation);
2244  Opts.AlignedAllocationUnavailable =
2245  Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
2246  Opts.NewAlignOverride =
2247  getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2248  if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2249  Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2250  Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2251  << A->getValue();
2252  Opts.NewAlignOverride = 0;
2253  }
2254  Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
2255  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
2256  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
2257  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
2258  Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
2259  Opts.InstantiationDepth =
2260  getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
2261  Opts.ArrowDepth =
2262  getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
2263  Opts.ConstexprCallDepth =
2264  getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2265  Opts.ConstexprStepLimit =
2266  getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2267  Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
2268  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
2269  Opts.NumLargeByValueCopy =
2270  getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
2271  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
2273  Args.getLastArgValue(OPT_fconstant_string_class);
2274  Opts.ObjCDefaultSynthProperties =
2275  !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
2276  Opts.EncodeExtendedBlockSig =
2277  Args.hasArg(OPT_fencode_extended_block_signature);
2278  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
2279  Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
2280  Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
2281  Opts.AlignDouble = Args.hasArg(OPT_malign_double);
2282  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2283  Opts.PIE = Args.hasArg(OPT_pic_is_pie);
2284  Opts.Static = Args.hasArg(OPT_static_define);
2285  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
2286  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2287  || Args.hasArg(OPT_fdump_record_layouts);
2288  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
2289  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
2290  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
2291  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
2292  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
2293  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
2294  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
2295  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
2296  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
2297  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
2298  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
2299  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
2300  Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name_EQ);
2301  Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
2302  Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
2303  std::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end());
2304  Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
2305  Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2306  // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2307  // is enabled.
2308  Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2309  | Opts.NativeHalfArgsAndReturns;
2310  Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
2311 
2312  // __declspec is enabled by default for the PS4 by the driver, and also
2313  // enabled for Microsoft Extensions or Borland Extensions, here.
2314  //
2315  // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
2316  // CUDA extension. However, it is required for supporting
2317  // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2318  // been rewritten in terms of something more generic, remove the Opts.CUDA
2319  // term here.
2320  Opts.DeclSpecKeyword =
2321  Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2322  (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2323 
2324  if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2325  switch (llvm::StringSwitch<unsigned>(A->getValue())
2326  .Case("target", LangOptions::ASMM_Target)
2327  .Case("no", LangOptions::ASMM_Off)
2328  .Case("yes", LangOptions::ASMM_On)
2329  .Default(255)) {
2330  default:
2331  Diags.Report(diag::err_drv_invalid_value)
2332  << "-faddress-space-map-mangling=" << A->getValue();
2333  break;
2335  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2336  break;
2337  case LangOptions::ASMM_On:
2338  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2339  break;
2340  case LangOptions::ASMM_Off:
2341  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2342  break;
2343  }
2344  }
2345 
2346  if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2348  llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2349  A->getValue())
2350  .Case("single",
2352  .Case("multiple",
2354  .Case("virtual",
2356  .Default(LangOptions::PPTMK_BestCase);
2357  if (InheritanceModel == LangOptions::PPTMK_BestCase)
2358  Diags.Report(diag::err_drv_invalid_value)
2359  << "-fms-memptr-rep=" << A->getValue();
2360 
2361  Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2362  }
2363 
2364  // Check for MS default calling conventions being specified.
2365  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2367  llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
2368  .Case("cdecl", LangOptions::DCC_CDecl)
2369  .Case("fastcall", LangOptions::DCC_FastCall)
2370  .Case("stdcall", LangOptions::DCC_StdCall)
2371  .Case("vectorcall", LangOptions::DCC_VectorCall)
2372  .Case("regcall", LangOptions::DCC_RegCall)
2373  .Default(LangOptions::DCC_None);
2374  if (DefaultCC == LangOptions::DCC_None)
2375  Diags.Report(diag::err_drv_invalid_value)
2376  << "-fdefault-calling-conv=" << A->getValue();
2377 
2378  llvm::Triple T(TargetOpts.Triple);
2379  llvm::Triple::ArchType Arch = T.getArch();
2380  bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
2381  DefaultCC == LangOptions::DCC_StdCall) &&
2382  Arch != llvm::Triple::x86;
2383  emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
2384  DefaultCC == LangOptions::DCC_RegCall) &&
2385  !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2386  if (emitError)
2387  Diags.Report(diag::err_drv_argument_not_allowed_with)
2388  << A->getSpelling() << T.getTriple();
2389  else
2390  Opts.setDefaultCallingConv(DefaultCC);
2391  }
2392 
2393  // -mrtd option
2394  if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2395  if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2396  Diags.Report(diag::err_drv_argument_not_allowed_with)
2397  << A->getSpelling() << "-fdefault-calling-conv";
2398  else {
2399  llvm::Triple T(TargetOpts.Triple);
2400  if (T.getArch() != llvm::Triple::x86)
2401  Diags.Report(diag::err_drv_argument_not_allowed_with)
2402  << A->getSpelling() << T.getTriple();
2403  else
2404  Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2405  }
2406  }
2407 
2408  // Check if -fopenmp is specified.
2409  Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 1 : 0;
2410  Opts.OpenMPUseTLS =
2411  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
2412  Opts.OpenMPIsDevice =
2413  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2414 
2415  if (Opts.OpenMP) {
2416  int Version =
2417  getLastArgIntValue(Args, OPT_fopenmp_version_EQ, Opts.OpenMP, Diags);
2418  if (Version != 0)
2419  Opts.OpenMP = Version;
2420  // Provide diagnostic when a given target is not expected to be an OpenMP
2421  // device or host.
2422  if (!Opts.OpenMPIsDevice) {
2423  switch (T.getArch()) {
2424  default:
2425  break;
2426  // Add unsupported host targets here:
2427  case llvm::Triple::nvptx:
2428  case llvm::Triple::nvptx64:
2429  Diags.Report(clang::diag::err_drv_omp_host_target_not_supported)
2430  << TargetOpts.Triple;
2431  break;
2432  }
2433  }
2434  }
2435 
2436  // Set the flag to prevent the implementation from emitting device exception
2437  // handling code for those requiring so.
2438  if (Opts.OpenMPIsDevice && T.isNVPTX()) {
2439  Opts.Exceptions = 0;
2440  Opts.CXXExceptions = 0;
2441  }
2442 
2443  // Get the OpenMP target triples if any.
2444  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
2445 
2446  for (unsigned i = 0; i < A->getNumValues(); ++i) {
2447  llvm::Triple TT(A->getValue(i));
2448 
2449  if (TT.getArch() == llvm::Triple::UnknownArch ||
2450  !(TT.getArch() == llvm::Triple::ppc ||
2451  TT.getArch() == llvm::Triple::ppc64 ||
2452  TT.getArch() == llvm::Triple::ppc64le ||
2453  TT.getArch() == llvm::Triple::nvptx ||
2454  TT.getArch() == llvm::Triple::nvptx64 ||
2455  TT.getArch() == llvm::Triple::x86 ||
2456  TT.getArch() == llvm::Triple::x86_64))
2457  Diags.Report(clang::diag::err_drv_invalid_omp_target) << A->getValue(i);
2458  else
2459  Opts.OMPTargetTriples.push_back(TT);
2460  }
2461  }
2462 
2463  // Get OpenMP host file path if any and report if a non existent file is
2464  // found
2465  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
2466  Opts.OMPHostIRFile = A->getValue();
2467  if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
2468  Diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
2469  << Opts.OMPHostIRFile;
2470  }
2471 
2472  // Record whether the __DEPRECATED define was requested.
2473  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2474  OPT_fno_deprecated_macro,
2475  Opts.Deprecated);
2476 
2477  // FIXME: Eliminate this dependency.
2478  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
2479  OptSize = getOptimizationLevelSize(Args);
2480  Opts.Optimize = Opt != 0;
2481  Opts.OptimizeSize = OptSize != 0;
2482 
2483  // This is the __NO_INLINE__ define, which just depends on things like the
2484  // optimization level and -fno-inline, not actually whether the backend has
2485  // inlining enabled.
2486  Opts.NoInlineDefine = !Opts.Optimize;
2487  if (Arg *InlineArg = Args.getLastArg(
2488  options::OPT_finline_functions, options::OPT_finline_hint_functions,
2489  options::OPT_fno_inline_functions, options::OPT_fno_inline))
2490  if (InlineArg->getOption().matches(options::OPT_fno_inline))
2491  Opts.NoInlineDefine = true;
2492 
2493  Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
2494  Args.hasArg(OPT_cl_fast_relaxed_math);
2495  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
2496  Args.hasArg(OPT_cl_finite_math_only) ||
2497  Args.hasArg(OPT_cl_fast_relaxed_math);
2498  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
2499  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
2500  Args.hasArg(OPT_cl_fast_relaxed_math);
2501 
2502  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2503  StringRef Val = A->getValue();
2504  if (Val == "fast")
2505  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2506  else if (Val == "on")
2507  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2508  else if (Val == "off")
2509  Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
2510  else
2511  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2512  }
2513 
2514  Opts.RetainCommentsFromSystemHeaders =
2515  Args.hasArg(OPT_fretain_comments_from_system_headers);
2516 
2517  unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
2518  switch (SSP) {
2519  default:
2520  Diags.Report(diag::err_drv_invalid_value)
2521  << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2522  break;
2523  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2524  case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
2525  case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
2526  case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
2527  }
2528 
2529  // Parse -fsanitize= arguments.
2530  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2531  Diags, Opts.Sanitize);
2532  // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
2533  Opts.SanitizeAddressFieldPadding =
2534  getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
2535  Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
2536 
2537  // -fxray-instrument
2538  Opts.XRayInstrument =
2539  Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
2540 
2541  // -fxray-always-emit-customevents
2542  Opts.XRayAlwaysEmitCustomEvents =
2543  Args.hasFlag(OPT_fxray_always_emit_customevents,
2544  OPT_fnoxray_always_emit_customevents, false);
2545 
2546  // -fxray-{always,never}-instrument= filenames.
2548  Args.getAllArgValues(OPT_fxray_always_instrument);
2550  Args.getAllArgValues(OPT_fxray_never_instrument);
2551 
2552  // -fallow-editor-placeholders
2553  Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
2554 }
2555 
2557  switch (Action) {
2558  case frontend::ASTDeclList:
2559  case frontend::ASTDump:
2560  case frontend::ASTPrint:
2561  case frontend::ASTView:
2563  case frontend::EmitBC:
2564  case frontend::EmitHTML:
2565  case frontend::EmitLLVM:
2568  case frontend::EmitObj:
2569  case frontend::FixIt:
2572  case frontend::GeneratePCH:
2573  case frontend::GeneratePTH:
2576  case frontend::VerifyPCH:
2579  case frontend::RewriteObjC:
2580  case frontend::RewriteTest:
2581  case frontend::RunAnalysis:
2583  return false;
2584 
2586  case frontend::DumpTokens:
2587  case frontend::InitOnly:
2592  return true;
2593  }
2594  llvm_unreachable("invalid frontend action");
2595 }
2596 
2597 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
2598  FileManager &FileMgr,
2599  DiagnosticsEngine &Diags,
2601  using namespace options;
2602  Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
2603  Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
2604  if (const Arg *A = Args.getLastArg(OPT_token_cache))
2605  Opts.TokenCache = A->getValue();
2606  else
2607  Opts.TokenCache = Opts.ImplicitPTHInclude;
2608  Opts.UsePredefines = !Args.hasArg(OPT_undef);
2609  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
2610  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
2611  Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
2612 
2613  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
2614  for (const Arg *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
2615  Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
2616 
2617  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
2618  StringRef Value(A->getValue());
2619  size_t Comma = Value.find(',');
2620  unsigned Bytes = 0;
2621  unsigned EndOfLine = 0;
2622 
2623  if (Comma == StringRef::npos ||
2624  Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2625  Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2626  Diags.Report(diag::err_drv_preamble_format);
2627  else {
2628  Opts.PrecompiledPreambleBytes.first = Bytes;
2629  Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2630  }
2631  }
2632 
2633  // Add macros from the command line.
2634  for (const Arg *A : Args.filtered(OPT_D, OPT_U)) {
2635  if (A->getOption().matches(OPT_D))
2636  Opts.addMacroDef(A->getValue());
2637  else
2638  Opts.addMacroUndef(A->getValue());
2639  }
2640 
2641  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
2642 
2643  // Add the ordered list of -includes.
2644  for (const Arg *A : Args.filtered(OPT_include))
2645  Opts.Includes.emplace_back(A->getValue());
2646 
2647  for (const Arg *A : Args.filtered(OPT_chain_include))
2648  Opts.ChainedIncludes.emplace_back(A->getValue());
2649 
2650  for (const Arg *A : Args.filtered(OPT_remap_file)) {
2651  std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
2652 
2653  if (Split.second.empty()) {
2654  Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
2655  continue;
2656  }
2657 
2658  Opts.addRemappedFile(Split.first, Split.second);
2659  }
2660 
2661  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
2662  StringRef Name = A->getValue();
2663  unsigned Library = llvm::StringSwitch<unsigned>(Name)
2664  .Case("libc++", ARCXX_libcxx)
2665  .Case("libstdc++", ARCXX_libstdcxx)
2666  .Case("none", ARCXX_nolib)
2667  .Default(~0U);
2668  if (Library == ~0U)
2669  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2670  else
2672  }
2673 
2674  // Always avoid lexing editor placeholders when we're just running the
2675  // preprocessor as we never want to emit the
2676  // "editor placeholder in source file" error in PP only mode.
2677  if (isStrictlyPreprocessorAction(Action))
2678  Opts.LexEditorPlaceholders = false;
2679 }
2680 
2682  ArgList &Args,
2684  using namespace options;
2685 
2686  if (isStrictlyPreprocessorAction(Action))
2687  Opts.ShowCPP = !Args.hasArg(OPT_dM);
2688  else
2689  Opts.ShowCPP = 0;
2690 
2691  Opts.ShowComments = Args.hasArg(OPT_C);
2692  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
2693  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
2694  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
2695  Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
2696  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
2697  Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
2698  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
2699 }
2700 
2701 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2702  DiagnosticsEngine &Diags) {
2703  using namespace options;
2704  Opts.ABI = Args.getLastArgValue(OPT_target_abi);
2705  if (Arg *A = Args.getLastArg(OPT_meabi)) {
2706  StringRef Value = A->getValue();
2707  llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
2708  .Case("default", llvm::EABI::Default)
2709  .Case("4", llvm::EABI::EABI4)
2710  .Case("5", llvm::EABI::EABI5)
2711  .Case("gnu", llvm::EABI::GNU)
2712  .Default(llvm::EABI::Unknown);
2713  if (EABIVersion == llvm::EABI::Unknown)
2714  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2715  << Value;
2716  else
2717  Opts.EABIVersion = EABIVersion;
2718  }
2719  Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
2720  Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
2721  Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
2722  Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
2723  Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
2724  // Use the default target triple if unspecified.
2725  if (Opts.Triple.empty())
2726  Opts.Triple = llvm::sys::getDefaultTargetTriple();
2727  Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
2728 }
2729 
2731  const char *const *ArgBegin,
2732  const char *const *ArgEnd,
2733  DiagnosticsEngine &Diags) {
2734  bool Success = true;
2735 
2736  // Parse the arguments.
2737  std::unique_ptr<OptTable> Opts = createDriverOptTable();
2738  const unsigned IncludedFlagsBitmask = options::CC1Option;
2739  unsigned MissingArgIndex, MissingArgCount;
2740  InputArgList Args =
2741  Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
2742  MissingArgCount, IncludedFlagsBitmask);
2743  LangOptions &LangOpts = *Res.getLangOpts();
2744 
2745  // Check for missing argument error.
2746  if (MissingArgCount) {
2747  Diags.Report(diag::err_drv_missing_argument)
2748  << Args.getArgString(MissingArgIndex) << MissingArgCount;
2749  Success = false;
2750  }
2751 
2752  // Issue errors on unknown arguments.
2753  for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
2754  Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
2755  Success = false;
2756  }
2757 
2758  Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
2759  Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
2761  Success &=
2762  ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
2763  false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
2764  ParseCommentArgs(LangOpts.CommentOpts, Args);
2766  // FIXME: We shouldn't have to pass the DashX option around here
2767  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
2768  LangOpts.IsHeaderFile);
2769  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
2770  Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
2771  Res.getTargetOpts());
2774  if (DashX.getFormat() == InputKind::Precompiled ||
2775  DashX.getLanguage() == InputKind::LLVM_IR) {
2776  // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
2777  // PassManager in BackendUtil.cpp. They need to be initializd no matter
2778  // what the input type is.
2779  if (Args.hasArg(OPT_fobjc_arc))
2780  LangOpts.ObjCAutoRefCount = 1;
2781  // PIClevel and PIELevel are needed during code generation and this should be
2782  // set regardless of the input type.
2783  LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2784  LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
2785  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2786  Diags, LangOpts.Sanitize);
2787  } else {
2788  // Other LangOpts are only initialzed when the input is not AST or LLVM IR.
2789  // FIXME: Should we really be calling this for an InputKind::Asm input?
2790  ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
2791  Res.getPreprocessorOpts(), Diags);
2793  LangOpts.ObjCExceptions = 1;
2794  }
2795 
2796  if (LangOpts.CUDA) {
2797  // During CUDA device-side compilation, the aux triple is the
2798  // triple used for host compilation.
2799  if (LangOpts.CUDAIsDevice)
2801  }
2802 
2803  // Set the triple of the host for OpenMP device compile.
2804  if (LangOpts.OpenMPIsDevice)
2806 
2807  // FIXME: Override value name discarding when asan or msan is used because the
2808  // backend passes depend on the name of the alloca in order to print out
2809  // names.
2810  Res.getCodeGenOpts().DiscardValueNames &=
2811  !LangOpts.Sanitize.has(SanitizerKind::Address) &&
2812  !LangOpts.Sanitize.has(SanitizerKind::Memory);
2813 
2814  // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of
2815  // PCH file and find the original header name. Remove the need to do that in
2816  // ParsePreprocessorArgs and remove the FileManager
2817  // parameters from the function and the "FileManager.h" #include.
2818  FileManager FileMgr(Res.getFileSystemOpts());
2819  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, FileMgr, Diags,
2823 
2824  // Turn on -Wspir-compat for SPIR target.
2825  llvm::Triple T(Res.getTargetOpts().Triple);
2826  auto Arch = T.getArch();
2827  if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64) {
2828  Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
2829  }
2830 
2831  // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
2832  if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
2833  !Res.getLangOpts()->Sanitize.empty()) {
2834  Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
2835  Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
2836  }
2837  return Success;
2838 }
2839 
2841  // Note: For QoI reasons, the things we use as a hash here should all be
2842  // dumped via the -module-info flag.
2843  using llvm::hash_code;
2844  using llvm::hash_value;
2845  using llvm::hash_combine;
2846 
2847  // Start the signature with the compiler version.
2848  // FIXME: We'd rather use something more cryptographically sound than
2849  // CityHash, but this will do for now.
2850  hash_code code = hash_value(getClangFullRepositoryVersion());
2851 
2852  // Extend the signature with the language options
2853 #define LANGOPT(Name, Bits, Default, Description) \
2854  code = hash_combine(code, LangOpts->Name);
2855 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
2856  code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
2857 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
2858 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
2859 #include "clang/Basic/LangOptions.def"
2860 
2861  for (StringRef Feature : LangOpts->ModuleFeatures)
2862  code = hash_combine(code, Feature);
2863 
2864  // Extend the signature with the target options.
2865  code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
2866  TargetOpts->ABI);
2867  for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i)
2868  code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]);
2869 
2870  // Extend the signature with preprocessor options.
2871  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
2872  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
2873  code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
2874 
2875  for (std::vector<std::pair<std::string, bool/*isUndef*/>>::const_iterator
2876  I = getPreprocessorOpts().Macros.begin(),
2877  IEnd = getPreprocessorOpts().Macros.end();
2878  I != IEnd; ++I) {
2879  // If we're supposed to ignore this macro for the purposes of modules,
2880  // don't put it into the hash.
2881  if (!hsOpts.ModulesIgnoreMacros.empty()) {
2882  // Check whether we're ignoring this macro.
2883  StringRef MacroDef = I->first;
2884  if (hsOpts.ModulesIgnoreMacros.count(
2885  llvm::CachedHashString(MacroDef.split('=').first)))
2886  continue;
2887  }
2888 
2889  code = hash_combine(code, I->first, I->second);
2890  }
2891 
2892  // Extend the signature with the sysroot and other header search options.
2893  code = hash_combine(code, hsOpts.Sysroot,
2894  hsOpts.ModuleFormat,
2895  hsOpts.UseDebugInfo,
2896  hsOpts.UseBuiltinIncludes,
2898  hsOpts.UseStandardCXXIncludes,
2899  hsOpts.UseLibcxx,
2901  code = hash_combine(code, hsOpts.ResourceDir);
2902 
2903  // Extend the signature with the user build path.
2904  code = hash_combine(code, hsOpts.ModuleUserBuildPath);
2905 
2906  // Extend the signature with the module file extensions.
2907  const FrontendOptions &frontendOpts = getFrontendOpts();
2908  for (const auto &ext : frontendOpts.ModuleFileExtensions) {
2909  code = ext->hashExtension(code);
2910  }
2911 
2912  // Extend the signature with the enabled sanitizers, if at least one is
2913  // enabled. Sanitizers which cannot affect AST generation aren't hashed.
2914  SanitizerSet SanHash = LangOpts->Sanitize;
2915  SanHash.clear(getPPTransparentSanitizers());
2916  if (!SanHash.empty())
2917  code = hash_combine(code, SanHash.Mask);
2918 
2919  return llvm::APInt(64, code).toString(36, /*Signed=*/false);
2920 }
2921 
2922 namespace clang {
2923 
2924 template<typename IntTy>
2925 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
2926  IntTy Default,
2927  DiagnosticsEngine *Diags) {
2928  IntTy Res = Default;
2929  if (Arg *A = Args.getLastArg(Id)) {
2930  if (StringRef(A->getValue()).getAsInteger(10, Res)) {
2931  if (Diags)
2932  Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
2933  << A->getValue();
2934  }
2935  }
2936  return Res;
2937 }
2938 
2939 
2940 // Declared in clang/Frontend/Utils.h.
2941 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
2942  DiagnosticsEngine *Diags) {
2943  return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
2944 }
2945 
2946 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
2947  uint64_t Default,
2948  DiagnosticsEngine *Diags) {
2949  return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
2950 }
2951 
2952 void BuryPointer(const void *Ptr) {
2953  // This function may be called only a small fixed amount of times per each
2954  // invocation, otherwise we do actually have a leak which we want to report.
2955  // If this function is called more than kGraveYardMaxSize times, the pointers
2956  // will not be properly buried and a leak detector will report a leak, which
2957  // is what we want in such case.
2958  static const size_t kGraveYardMaxSize = 16;
2959  LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
2960  static std::atomic<unsigned> GraveYardSize;
2961  unsigned Idx = GraveYardSize++;
2962  if (Idx >= kGraveYardMaxSize)
2963  return;
2964  GraveYard[Idx] = Ptr;
2965 }
2966 
2969  DiagnosticsEngine &Diags) {
2971 }
2972 
2975  DiagnosticsEngine &Diags,
2977  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
2978  return BaseFS;
2979 
2981  new vfs::OverlayFileSystem(BaseFS));
2982  // earlier vfs files are on the bottom
2983  for (const std::string &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
2984  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
2985  BaseFS->getBufferForFile(File);
2986  if (!Buffer) {
2987  Diags.Report(diag::err_missing_vfs_overlay_file) << File;
2989  }
2990 
2992  std::move(Buffer.get()), /*DiagHandler*/ nullptr, File);
2993  if (!FS.get()) {
2994  Diags.Report(diag::err_invalid_vfs_overlay) << File;
2996  }
2997  Overlay->pushOverlay(FS);
2998  }
2999  return Overlay;
3000 }
3001 } // 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.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
Expand macros but not #includes.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string OutputFile
The output file, if any.
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true, bool DefaultShowOpt=true)
Fill out Opts based on the options given in Args.
static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args)
std::vector< std::pair< std::string, bool > > Macros
unsigned InlineMaxStackDepth
The inlining stack depth limit.
Paths for &#39;#include <>&#39; added by &#39;-I&#39;.
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
Conform to the underlying platform&#39;s C and C++ ABIs as closely as we can.
std::string ObjCMTWhiteListPath
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
void addMacroUndef(StringRef Name)
static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile)
Generate pre-compiled module from a module map.
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.
static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, const TargetOptions &TargetOpts, PreprocessorOptions &PPOpts, DiagnosticsEngine &Diags)
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:116
Defines the clang::FileManager interface and associated types.
Parse and perform semantic analysis.
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:101
Format getFormat() const
Like System, but headers are implicitly wrapped in extern "C".
DependencyOutputOptions & getDependencyOutputOpts()
std::shared_ptr< HeaderSearchOptions > HeaderSearchOpts
Options controlling the #include directive.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the &#39;real&#39; 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:42
Enable migration to modern ObjC subscripting.
static bool isBuiltinFunc(const char *Name)
Returns true if this is a libc/libm function without the &#39;__builtin_&#39; prefix.
Definition: Builtins.cpp:51
unsigned IncludeModuleFiles
Include module file dependencies.
Parse ASTs and print them.
bool hasDigraphs() const
hasDigraphs - Language supports digraphs.
Definition: LangStandard.h:94
Like System, but only used for C++.
std::string HeaderIncludeOutputFile
The file to write header include output to.
StringRef P
std::vector< std::string > Includes
static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector< std::string > &Levels, DiagnosticsEngine *Diags, DiagnosticLevelMask &M)
std::string FPDenormalMode
The floating-point denormal mode to use.
bool isObjectiveC() const
Is the language of the input some dialect of Objective-C?
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++.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1207
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.
#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
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 > Reciprocals
std::vector< std::string > RewriteMapFiles
Set of files defining the rules for the symbol rewriting.
Options for controlling comment parsing.
static const LangStandard & getLangStandardForKind(Kind K)
InputKind::Language getLanguage() const
Get the language that this standard describes.
Definition: LangStandard.h:63
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
enum clang::FrontendOptions::@168 ARCMTAction
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:35
static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, const std::string &WorkingDir)
std::string ImplicitPTHInclude
The implicit PTH input included at the start of the translation unit, or empty.
Options for controlling the target.
Definition: TargetOptions.h:26
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreMacros
The set of macro names that should be ignored for the purposes of computing the module hash...
void AddPath(StringRef Path, frontend::IncludeDirGroup Group, bool IsFramework, bool IgnoreSysRoot)
AddPath - Add the Path path to the specified Group list.
void addRemappedFile(StringRef From, StringRef To)
std::string FixItSuffix
If given, the new suffix for fix-it rewritten files.
std::string HostTriple
When compiling for the device side, contains the triple used to compile for the host.
Definition: TargetOptions.h:33
std::string SplitDwarfFile
The name for the split debug info file that we&#39;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.
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
float __ovld __cnfn normalize(float p)
Returns a vector in the same direction as p but with a length of 1.
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Parse and apply any fixits to the source.
std::vector< std::string > CudaGpuBinaryFileNames
A list of file names passed with -fcuda-include-gpubinary options to forward to CUDA runtime back-end...
void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader)
AddSystemHeaderPrefix - Override whether #include directives naming a path starting with Prefix shoul...
std::string FindPchSource
If non-empty, search the pch input file as if it was a header included by this file.
static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
&#39;macosx-fragile&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:37
std::map< std::string, std::string > DebugPrefixMap
std::vector< std::string > XRayAlwaysInstrumentFiles
Paths to the XRay "always instrument" files specifying which objects (files, functions, variables) should be imbued with the XRay "always instrument" attribute.
Definition: LangOptions.h:110
bool isCPlusPlus14() const
isCPlusPlus14 - Language is a C++14 variant (or later).
Definition: LangStandard.h:84
use NS_NONATOMIC_IOSONLY for property &#39;atomic&#39; attribute
std::string FPMath
If given, the unit to use for floating point math.
Definition: TargetOptions.h:39
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.
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:112
unsigned IncludeSystemHeaders
Include system header dependencies.
IntrusiveRefCntPtr< FileSystem > getVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Gets a FileSystem for a virtual file system described in YAML format.
Translate input source into HTML.
Enable migration to modern ObjC readwrite property.
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:71
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
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...
InputKind withFormat(Format F) const
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.
Languages that the frontend can parse and compile.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
Definition: Visibility.h:44
std::shared_ptr< PreprocessorOptions > PreprocessorOpts
Options controlling the preprocessor (aside from #include handling).
unsigned IncludeCodePatterns
Show code patterns in code completion results.
Action - Represent an abstract compilation step to perform.
Definition: Action.h:45
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()
bool hasLineComments() const
Language supports &#39;//&#39; comments.
Definition: LangStandard.h:66
unsigned ShowStats
Show frontend performance metrics and statistics.
static void hash_combine(std::size_t &seed, const T &v)
Enable migration to NS_ENUM/NS_OPTIONS macros.
static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args)
static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
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.
bool isOpenCL() const
isOpenCL - Language is a OpenCL variant.
Definition: LangStandard.h:106
bool isCPlusPlus2a() const
isCPlusPlus2a - Language is a post-C++17 variant (or later).
Definition: LangStandard.h:90
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:147
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
Optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
Definition: VersionTuple.h:77
unsigned FixWhatYouCan
Apply fixes even if there are unfixable errors.
std::unique_ptr< llvm::opt::OptTable > createDriverOptTable()
std::vector< std::string > Warnings
The list of -W...
static StringRef getRelocModel(ArgList &Args, DiagnosticsEngine &Diags)
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.
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
Definition: LangStandard.h:78
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
static void setPGOUseInstrumentor(CodeGenOptions &Opts, const Twine &ProfileName)
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 &#39;requires&#39; decls in addition to the hard-coded list in ...
Definition: LangOptions.h:137
PreprocessorOutputOptions & getPreprocessorOutputOpts()
std::string ThreadModel
The thread model to use.
FrontendOptions & getFrontendOpts()
std::vector< std::string > DependentLibraries
A list of dependent libraries.
Enable annotation of ObjCMethods of all kinds.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id, IntTy Default, DiagnosticsEngine *Diags)
MigratorOptions & getMigratorOpts()
char CoverageVersion[4]
The version string to put into coverage files.
Dump out preprocessed tokens.
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:131
const char * getName() const
getName - Get the name of this standard.
Definition: LangStandard.h:57
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).
static bool IsHeaderFile(const std::string &Filename)
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
Generate pre-compiled module from a C++ module interface file.
uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, uint64_t Default, DiagnosticsEngine *Diags=nullptr)
#define LANGSTANDARD(id, name, lang, desc, features)
static void setLangDefaults(LangOptions &Opts, InputKind IK, const llvm::Triple &T, PreprocessorOptions &PPOpts, LangStandard::Kind LangStd=LangStandard::lang_unspecified)
Set language defaults for the given input language and language standard in the given LangOptions obj...
AnalysisInliningMode InliningMode
The mode of function selection used during inlining.
annotate property with NS_RETURNS_INNER_POINTER
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:140
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 isCPlusPlus11() const
isCPlusPlus11 - Language is a C++11 variant (or later).
Definition: LangStandard.h:81
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...
Emit only debug info necessary for generating line number tables (-gline-tables-only).
int Id
Definition: ASTDiff.cpp:191
const FunctionProtoType * T
void AddPrebuiltModulePath(StringRef Name)
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:151
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:48
Only execute frontend initialization.
Defines version macros and version-related utility functions for Clang.
std::string RelocationModel
The name of the relocation model to use.
unsigned IncludeNamespaceLevelDecls
Show decls in namespace (including the global namespace) in code completion results.
Print the "preamble" of the input file.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
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.
bool hasImplicitInt() const
hasImplicitInt - Language allows variables to be typed as int implicitly.
Definition: LangStandard.h:103
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:118
static bool IsInputCompatibleWithStandard(InputKind IK, const LangStandard &S)
Check if input file kind and language standard are compatible.
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition: Sanitizers.h:65
unsigned ModulesEmbedAllFiles
Whether we should embed all used files into the PCM file.
Enable migration to add conforming protocols.
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:117
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...
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector< std::string > &Diagnostics)
std::string AuxTriple
Auxiliary triple for CUDA compilation.
bool isC11() const
isC11 - Language is a superset of C11.
Definition: LangStandard.h:72
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
bool hasHexFloats() const
hasHexFloats - Language supports hexadecimal float constants.
Definition: LangStandard.h:100
unsigned ShowIncludeDirectives
Print includes, imports etc. within preprocessed output.
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:83
Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:59
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:42
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
AnalyzerOptionsRef getAnalyzerOpts() const
AnalysisStores AnalysisStoreOpt
InputKind getPreprocessed() const
Encodes a location in the source.
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
Generate machine code, but don&#39;t emit anything.
Assembly: we accept this only so that we can preprocess it.
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.
Limit generated debug info to reduce size (-fno-standalone-debug).
Options for controlling the compiler diagnostics engine.
Enable migration to modern ObjC literals.
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
std::vector< FrontendInputFile > Inputs
The input files and their types.
Kind getKind() const
Definition: ObjCRuntime.h:75
unsigned ModulesValidateSystemHeaders
Whether to validate system input files when a module is loaded.
ConfigTable Config
A key-value table of use-specified configuration values.
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
The kind of a file that we&#39;ve been handed as an input.
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)
unsigned IncludeTimestamps
Whether timestamps should be written to the produced PCH file.
Parse ASTs and view them in Graphviz.
std::vector< std::string > Remarks
The list of -R...
std::vector< std::string > OpenCLExtensionsAsWritten
The list of OpenCL extensions to enable or disable, as written on the command line.
Definition: TargetOptions.h:62
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::unordered_map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
DiagnosticOptions & getDiagnosticOpts() const
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
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.
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
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.
unsigned RewriteImports
Include contents of transitively-imported modules.
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:51
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
static const StringRef GetInputKindName(InputKind IK)
Get language name for given input kind.
void addMacroDef(StringRef Name)
llvm::EABI EABIVersion
The EABI version to use.
Definition: TargetOptions.h:45
&#39;#include ""&#39; paths, added by &#39;gcc -iquote&#39;.
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.
Like Angled, but marks system directories.
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.
bool allowsARC() const
Does this runtime allow ARC at all?
Definition: ObjCRuntime.h:140
DependencyOutputFormat OutputFormat
The format for the dependency file.
unsigned UseDebugInfo
Whether the module includes debug information (-gmodules).
Dataflow Directional Tag Classes.
uint64_t SanitizerMask
Definition: Sanitizers.h:24
Optional< unsigned > getSubminor() const
Retrieve the subminor version number, if provided.
Definition: VersionTuple.h:84
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
Definition: LangOptions.h:125
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()
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Language getLanguage() const
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:147
std::vector< std::string > VerifyPrefixes
The prefixes for comment directives sought by -verify ("expected" by default).
std::string ARCMTMigrateReportOut
std::string PreferVectorWidth
The preferred width for auto-vectorization transforms.
Emit location information but do not generate debug info in the output.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Like System, but only used for C.
bool empty() const
Returns true if at least one sanitizer is enabled.
Definition: Sanitizers.h:68
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
unsigned getMajor() const
Retrieve the major version number.
Definition: VersionTuple.h:74
AnalysisConstraints AnalysisConstraintsOpt
static bool isStrictlyPreprocessorAction(frontend::ActionKind Action)
Helper class for holding the data necessary to invoke the compiler.
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 &#39;make&#39; problems.
std::string AnalyzeSpecificFunction
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i...
Definition: LangOptions.h:155
FrontendOptions - Options for controlling the behavior of the frontend.
bool isC17() const
isC17 - Language is a superset of C17.
Definition: LangStandard.h:75
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
Run a plugin action,.
bool isGNUMode() const
isGNUMode - Language includes GNU extensions.
Definition: LangStandard.h:97
std::string StatsFile
Filename to write statistics to.
prefer &#39;atomic&#39; property over &#39;nonatomic&#39;.
Enable migration of ObjC methods to &#39;instancetype&#39;.
void BuryPointer(const void *Ptr)
Parse ASTs and dump them.
Don&#39;t generate debug info.
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::vector< std::string > LinkerOptions
A list of linker options to embed in the object file.
Enable migration to modern ObjC readonly property.
static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, FileManager &FileMgr, DiagnosticsEngine &Diags, frontend::ActionKind Action)
Enable converting setter/getter expressions to property-dot syntx.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
CodeCompleteOptions CodeCompleteOpts
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor)
IntrusiveRefCntPtr< DiagnosticOptions > DiagnosticOpts
Options controlling the diagnostic engine.
std::vector< std::string > AddPluginActions
The list of plugin actions to run in addition to the normal action.
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.
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:13008
unsigned ShowMacroComments
Show comments, even in macros.
bool isUnknown() const
Is the input kind fully-unknown?
unsigned NoRetryExhausted
Do not re-analyze paths leading to exhausted nodes with a different strategy.
std::vector< std::string > XRayNeverInstrumentFiles
Paths to the XRay "never instrument" files specifying which objects (files, functions, variables) should be imbued with the XRay "never instrument" attribute.
Definition: LangOptions.h:115
Enable migration to modern ObjC property.
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...
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:143
static bool checkVerifyPrefixes(const std::vector< std::string > &VerifyPrefixes, DiagnosticsEngine *Diags)
bool isC99() const
isC99 - Language is a superset of C99.
Definition: LangStandard.h:69
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.
bool isCPlusPlus17() const
isCPlusPlus17 - Language is a C++17 variant (or later).
Definition: LangStandard.h:87
FileSystemOptions & getFileSystemOpts()
static unsigned getOptimizationLevelSize(ArgList &Args)
Run one or more source code analyses.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:50
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
#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&#39;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::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate and -fprofile-generate.
const char * getDescription() const
getDescription - Get the description of this standard.
Definition: LangStandard.h:60
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.
Dump information about a module file.
unsigned ModuleMapFileHomeIsCwd
Set the &#39;home directory&#39; of a module map file to the current working directory (or the home directory...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
unsigned AddMissingHeaderDeps
Add missing headers to dependency list.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
std::vector< std::string > SanitizerBlacklistFiles
Paths to blacklist files specifying which objects (files, functions, variables) should not be instrum...
Definition: LangOptions.h:105
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 building frameworks.
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Generate pre-tokenized header.
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
std::string ObjCConstantStringClass
Definition: LangOptions.h:119
#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.
std::map< std::string, std::string > PrebuiltModuleFiles
The mapping of module names to prebuilt module files.
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)
Defines enum values for all the target-independent builtin functions.
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
std::string ModuleFormat
The module/pch container format.
static void parseSanitizerKinds(StringRef FlagName, const std::vector< std::string > &Sanitizers, DiagnosticsEngine &Diags, SanitizerSet &S)
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:192
Attempt to be ABI-compatible with code generated by Clang 3.8.x (SVN r257626).
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.
bool LexEditorPlaceholders
When enabled, the preprocessor will construct editor placeholder tokens.
std::vector< std::string > ModuleMapFiles
The list of module map files to load before processing the input.