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