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