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