clang  7.0.0
CompilerInvocation.cpp
Go to the documentation of this file.
1 //===- CompilerInvocation.cpp ---------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
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 =
1554  llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple));
1555  Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
1556 
1557  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1558  OPT_arcmt_modify,
1559  OPT_arcmt_migrate)) {
1560  switch (A->getOption().getID()) {
1561  default:
1562  llvm_unreachable("missed a case");
1563  case OPT_arcmt_check:
1565  break;
1566  case OPT_arcmt_modify:
1568  break;
1569  case OPT_arcmt_migrate:
1571  break;
1572  }
1573  }
1574  Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
1576  = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1578  = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1579 
1580  if (Args.hasArg(OPT_objcmt_migrate_literals))
1582  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1584  if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1586  if (Args.hasArg(OPT_objcmt_migrate_property))
1588  if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1590  if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1592  if (Args.hasArg(OPT_objcmt_migrate_annotation))
1594  if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1596  if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1598  if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1600  if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1602  if (Args.hasArg(OPT_objcmt_atomic_property))
1604  if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1606  if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1608  if (Args.hasArg(OPT_objcmt_migrate_all))
1610 
1611  Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
1612 
1615  Diags.Report(diag::err_drv_argument_not_allowed_with)
1616  << "ARC migration" << "ObjC migration";
1617  }
1618 
1620  if (const Arg *A = Args.getLastArg(OPT_x)) {
1621  StringRef XValue = A->getValue();
1622 
1623  // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1624  // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1625  bool Preprocessed = XValue.consume_back("-cpp-output");
1626  bool ModuleMap = XValue.consume_back("-module-map");
1627  IsHeaderFile =
1628  !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1629 
1630  // Principal languages.
1631  DashX = llvm::StringSwitch<InputKind>(XValue)
1632  .Case("c", InputKind::C)
1633  .Case("cl", InputKind::OpenCL)
1634  .Case("cuda", InputKind::CUDA)
1635  .Case("hip", InputKind::HIP)
1636  .Case("c++", InputKind::CXX)
1637  .Case("objective-c", InputKind::ObjC)
1638  .Case("objective-c++", InputKind::ObjCXX)
1639  .Case("renderscript", InputKind::RenderScript)
1640  .Default(InputKind::Unknown);
1641 
1642  // "objc[++]-cpp-output" is an acceptable synonym for
1643  // "objective-c[++]-cpp-output".
1644  if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1645  DashX = llvm::StringSwitch<InputKind>(XValue)
1646  .Case("objc", InputKind::ObjC)
1647  .Case("objc++", InputKind::ObjCXX)
1648  .Default(InputKind::Unknown);
1649 
1650  // Some special cases cannot be combined with suffixes.
1651  if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1652  DashX = llvm::StringSwitch<InputKind>(XValue)
1653  .Case("cpp-output", InputKind(InputKind::C).getPreprocessed())
1654  .Case("assembler-with-cpp", InputKind::Asm)
1655  .Cases("ast", "pcm",
1657  .Case("ir", InputKind::LLVM_IR)
1658  .Default(InputKind::Unknown);
1659 
1660  if (DashX.isUnknown())
1661  Diags.Report(diag::err_drv_invalid_value)
1662  << A->getAsString(Args) << A->getValue();
1663 
1664  if (Preprocessed)
1665  DashX = DashX.getPreprocessed();
1666  if (ModuleMap)
1667  DashX = DashX.withFormat(InputKind::ModuleMap);
1668  }
1669 
1670  // '-' is the default input if none is given.
1671  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1672  Opts.Inputs.clear();
1673  if (Inputs.empty())
1674  Inputs.push_back("-");
1675  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1676  InputKind IK = DashX;
1677  if (IK.isUnknown()) {
1679  StringRef(Inputs[i]).rsplit('.').second);
1680  // FIXME: Warn on this?
1681  if (IK.isUnknown())
1682  IK = InputKind::C;
1683  // FIXME: Remove this hack.
1684  if (i == 0)
1685  DashX = IK;
1686  }
1687 
1688  // The -emit-module action implicitly takes a module map.
1690  IK.getFormat() == InputKind::Source)
1692 
1693  Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
1694  }
1695 
1696  return DashX;
1697 }
1698 
1699 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1700  void *MainAddr) {
1701  std::string ClangExecutable =
1702  llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1703  StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
1704 
1705  // Compute the path to the resource directory.
1706  StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1707  SmallString<128> P(Dir);
1708  if (ClangResourceDir != "")
1709  llvm::sys::path::append(P, ClangResourceDir);
1710  else
1711  llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX,
1712  "clang", CLANG_VERSION_STRING);
1713 
1714  return P.str();
1715 }
1716 
1717 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1718  const std::string &WorkingDir) {
1719  Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
1720  Opts.Verbose = Args.hasArg(OPT_v);
1721  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
1722  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
1723  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
1724  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1725  Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1726  Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
1727 
1728  // Canonicalize -fmodules-cache-path before storing it.
1729  SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1730  if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1731  if (WorkingDir.empty())
1732  llvm::sys::fs::make_absolute(P);
1733  else
1734  llvm::sys::fs::make_absolute(WorkingDir, P);
1735  }
1736  llvm::sys::path::remove_dots(P);
1737  Opts.ModuleCachePath = P.str();
1738 
1739  Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
1740  // Only the -fmodule-file=<name>=<file> form.
1741  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1742  StringRef Val = A->getValue();
1743  if (Val.find('=') != StringRef::npos)
1744  Opts.PrebuiltModuleFiles.insert(Val.split('='));
1745  }
1746  for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
1747  Opts.AddPrebuiltModulePath(A->getValue());
1748  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
1749  Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
1751  !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
1752  Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
1753  Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
1755  getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1756  Opts.ModuleCachePruneAfter =
1757  getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
1759  Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1760  Opts.BuildSessionTimestamp =
1761  getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
1763  Args.hasArg(OPT_fmodules_validate_system_headers);
1764  if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1765  Opts.ModuleFormat = A->getValue();
1766 
1767  for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
1768  StringRef MacroDef = A->getValue();
1769  Opts.ModulesIgnoreMacros.insert(
1770  llvm::CachedHashString(MacroDef.split('=').first));
1771  }
1772 
1773  // Add -I..., -F..., and -index-header-map options in order.
1774  bool IsIndexHeaderMap = false;
1775  bool IsSysrootSpecified =
1776  Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
1777  for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
1778  if (A->getOption().matches(OPT_index_header_map)) {
1779  // -index-header-map applies to the next -I or -F.
1780  IsIndexHeaderMap = true;
1781  continue;
1782  }
1783 
1785  IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1786 
1787  bool IsFramework = A->getOption().matches(OPT_F);
1788  std::string Path = A->getValue();
1789 
1790  if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1791  SmallString<32> Buffer;
1792  llvm::sys::path::append(Buffer, Opts.Sysroot,
1793  llvm::StringRef(A->getValue()).substr(1));
1794  Path = Buffer.str();
1795  }
1796 
1797  Opts.AddPath(Path, Group, IsFramework,
1798  /*IgnoreSysroot*/ true);
1799  IsIndexHeaderMap = false;
1800  }
1801 
1802  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
1803  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1804  for (const auto *A :
1805  Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
1806  if (A->getOption().matches(OPT_iprefix))
1807  Prefix = A->getValue();
1808  else if (A->getOption().matches(OPT_iwithprefix))
1809  Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
1810  else
1811  Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
1812  }
1813 
1814  for (const auto *A : Args.filtered(OPT_idirafter))
1815  Opts.AddPath(A->getValue(), frontend::After, false, true);
1816  for (const auto *A : Args.filtered(OPT_iquote))
1817  Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
1818  for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
1819  Opts.AddPath(A->getValue(), frontend::System, false,
1820  !A->getOption().matches(OPT_iwithsysroot));
1821  for (const auto *A : Args.filtered(OPT_iframework))
1822  Opts.AddPath(A->getValue(), frontend::System, true, true);
1823  for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
1824  Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
1825  /*IgnoreSysRoot=*/false);
1826 
1827  // Add the paths for the various language specific isystem flags.
1828  for (const auto *A : Args.filtered(OPT_c_isystem))
1829  Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
1830  for (const auto *A : Args.filtered(OPT_cxx_isystem))
1831  Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
1832  for (const auto *A : Args.filtered(OPT_objc_isystem))
1833  Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
1834  for (const auto *A : Args.filtered(OPT_objcxx_isystem))
1835  Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1836 
1837  // Add the internal paths from a driver that detects standard include paths.
1838  for (const auto *A :
1839  Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1841  if (A->getOption().matches(OPT_internal_externc_isystem))
1842  Group = frontend::ExternCSystem;
1843  Opts.AddPath(A->getValue(), Group, false, true);
1844  }
1845 
1846  // Add the path prefixes which are implicitly treated as being system headers.
1847  for (const auto *A :
1848  Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1849  Opts.AddSystemHeaderPrefix(
1850  A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1851 
1852  for (const auto *A : Args.filtered(OPT_ivfsoverlay))
1853  Opts.AddVFSOverlayFile(A->getValue());
1854 }
1855 
1857  const llvm::Triple &T,
1858  PreprocessorOptions &PPOpts,
1859  LangStandard::Kind LangStd) {
1860  // Set some properties which depend solely on the input kind; it would be nice
1861  // to move these to the language standard, and have the driver resolve the
1862  // input kind + language standard.
1863  //
1864  // FIXME: Perhaps a better model would be for a single source file to have
1865  // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
1866  // simultaneously active?
1867  if (IK.getLanguage() == InputKind::Asm) {
1868  Opts.AsmPreprocessor = 1;
1869  } else if (IK.isObjectiveC()) {
1870  Opts.ObjC1 = Opts.ObjC2 = 1;
1871  }
1872 
1873  if (LangStd == LangStandard::lang_unspecified) {
1874  // Based on the base language, pick one.
1875  switch (IK.getLanguage()) {
1876  case InputKind::Unknown:
1877  case InputKind::LLVM_IR:
1878  llvm_unreachable("Invalid input kind!");
1879  case InputKind::OpenCL:
1880  LangStd = LangStandard::lang_opencl10;
1881  break;
1882  case InputKind::CUDA:
1883  LangStd = LangStandard::lang_cuda;
1884  break;
1885  case InputKind::Asm:
1886  case InputKind::C:
1887 #if defined(CLANG_DEFAULT_STD_C)
1888  LangStd = CLANG_DEFAULT_STD_C;
1889 #else
1890  // The PS4 uses C99 as the default C standard.
1891  if (T.isPS4())
1892  LangStd = LangStandard::lang_gnu99;
1893  else
1894  LangStd = LangStandard::lang_gnu11;
1895 #endif
1896  break;
1897  case InputKind::ObjC:
1898 #if defined(CLANG_DEFAULT_STD_C)
1899  LangStd = CLANG_DEFAULT_STD_C;
1900 #else
1901  LangStd = LangStandard::lang_gnu11;
1902 #endif
1903  break;
1904  case InputKind::CXX:
1905  case InputKind::ObjCXX:
1906 #if defined(CLANG_DEFAULT_STD_CXX)
1907  LangStd = CLANG_DEFAULT_STD_CXX;
1908 #else
1909  LangStd = LangStandard::lang_gnucxx14;
1910 #endif
1911  break;
1913  LangStd = LangStandard::lang_c99;
1914  break;
1915  case InputKind::HIP:
1916  LangStd = LangStandard::lang_hip;
1917  break;
1918  }
1919  }
1920 
1922  Opts.LineComment = Std.hasLineComments();
1923  Opts.C99 = Std.isC99();
1924  Opts.C11 = Std.isC11();
1925  Opts.C17 = Std.isC17();
1926  Opts.CPlusPlus = Std.isCPlusPlus();
1927  Opts.CPlusPlus11 = Std.isCPlusPlus11();
1928  Opts.CPlusPlus14 = Std.isCPlusPlus14();
1929  Opts.CPlusPlus17 = Std.isCPlusPlus17();
1930  Opts.CPlusPlus2a = Std.isCPlusPlus2a();
1931  Opts.Digraphs = Std.hasDigraphs();
1932  Opts.GNUMode = Std.isGNUMode();
1933  Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
1934  Opts.HexFloats = Std.hasHexFloats();
1935  Opts.ImplicitInt = Std.hasImplicitInt();
1936 
1937  // Set OpenCL Version.
1938  Opts.OpenCL = Std.isOpenCL();
1939  if (LangStd == LangStandard::lang_opencl10)
1940  Opts.OpenCLVersion = 100;
1941  else if (LangStd == LangStandard::lang_opencl11)
1942  Opts.OpenCLVersion = 110;
1943  else if (LangStd == LangStandard::lang_opencl12)
1944  Opts.OpenCLVersion = 120;
1945  else if (LangStd == LangStandard::lang_opencl20)
1946  Opts.OpenCLVersion = 200;
1947  else if (LangStd == LangStandard::lang_openclcpp)
1948  Opts.OpenCLCPlusPlusVersion = 100;
1949 
1950  // OpenCL has some additional defaults.
1951  if (Opts.OpenCL) {
1952  Opts.AltiVec = 0;
1953  Opts.ZVector = 0;
1954  Opts.LaxVectorConversions = 0;
1955  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
1956  Opts.NativeHalfType = 1;
1957  Opts.NativeHalfArgsAndReturns = 1;
1958  Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
1959  // Include default header file for OpenCL.
1960  if (Opts.IncludeDefaultHeader) {
1961  PPOpts.Includes.push_back("opencl-c.h");
1962  }
1963  }
1964 
1965  Opts.HIP = IK.getLanguage() == InputKind::HIP;
1966  Opts.CUDA = IK.getLanguage() == InputKind::CUDA || Opts.HIP;
1967  if (Opts.CUDA)
1968  // Set default FP_CONTRACT to FAST.
1969  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
1970 
1971  Opts.RenderScript = IK.getLanguage() == InputKind::RenderScript;
1972  if (Opts.RenderScript) {
1973  Opts.NativeHalfType = 1;
1974  Opts.NativeHalfArgsAndReturns = 1;
1975  }
1976 
1977  // OpenCL and C++ both have bool, true, false keywords.
1978  Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1979 
1980  // OpenCL has half keyword
1981  Opts.Half = Opts.OpenCL;
1982 
1983  // C++ has wchar_t keyword.
1984  Opts.WChar = Opts.CPlusPlus;
1985 
1986  Opts.GNUKeywords = Opts.GNUMode;
1987  Opts.CXXOperatorNames = Opts.CPlusPlus;
1988 
1989  Opts.AlignedAllocation = Opts.CPlusPlus17;
1990 
1991  Opts.DollarIdents = !Opts.AsmPreprocessor;
1992 }
1993 
1994 /// Attempt to parse a visibility value out of the given argument.
1995 static Visibility parseVisibility(Arg *arg, ArgList &args,
1996  DiagnosticsEngine &diags) {
1997  StringRef value = arg->getValue();
1998  if (value == "default") {
1999  return DefaultVisibility;
2000  } else if (value == "hidden" || value == "internal") {
2001  return HiddenVisibility;
2002  } else if (value == "protected") {
2003  // FIXME: diagnose if target does not support protected visibility
2004  return ProtectedVisibility;
2005  }
2006 
2007  diags.Report(diag::err_drv_invalid_value)
2008  << arg->getAsString(args) << value;
2009  return DefaultVisibility;
2010 }
2011 
2012 /// Check if input file kind and language standard are compatible.
2014  const LangStandard &S) {
2015  switch (IK.getLanguage()) {
2016  case InputKind::Unknown:
2017  case InputKind::LLVM_IR:
2018  llvm_unreachable("should not parse language flags for this input");
2019 
2020  case InputKind::C:
2021  case InputKind::ObjC:
2023  return S.getLanguage() == InputKind::C;
2024 
2025  case InputKind::OpenCL:
2026  return S.getLanguage() == InputKind::OpenCL;
2027 
2028  case InputKind::CXX:
2029  case InputKind::ObjCXX:
2030  return S.getLanguage() == InputKind::CXX;
2031 
2032  case InputKind::CUDA:
2033  // FIXME: What -std= values should be permitted for CUDA compilations?
2034  return S.getLanguage() == InputKind::CUDA ||
2035  S.getLanguage() == InputKind::CXX;
2036 
2037  case InputKind::HIP:
2038  return S.getLanguage() == InputKind::CXX ||
2039  S.getLanguage() == InputKind::HIP;
2040 
2041  case InputKind::Asm:
2042  // Accept (and ignore) all -std= values.
2043  // FIXME: The -std= value is not ignored; it affects the tokenization
2044  // and preprocessing rules if we're preprocessing this asm input.
2045  return true;
2046  }
2047 
2048  llvm_unreachable("unexpected input language");
2049 }
2050 
2051 /// Get language name for given input kind.
2052 static const StringRef GetInputKindName(InputKind IK) {
2053  switch (IK.getLanguage()) {
2054  case InputKind::C:
2055  return "C";
2056  case InputKind::ObjC:
2057  return "Objective-C";
2058  case InputKind::CXX:
2059  return "C++";
2060  case InputKind::ObjCXX:
2061  return "Objective-C++";
2062  case InputKind::OpenCL:
2063  return "OpenCL";
2064  case InputKind::CUDA:
2065  return "CUDA";
2067  return "RenderScript";
2068  case InputKind::HIP:
2069  return "HIP";
2070 
2071  case InputKind::Asm:
2072  return "Asm";
2073  case InputKind::LLVM_IR:
2074  return "LLVM IR";
2075 
2076  case InputKind::Unknown:
2077  break;
2078  }
2079  llvm_unreachable("unknown input language");
2080 }
2081 
2082 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
2083  const TargetOptions &TargetOpts,
2084  PreprocessorOptions &PPOpts,
2085  DiagnosticsEngine &Diags) {
2086  // FIXME: Cleanup per-file based stuff.
2088  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
2089  LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2090 #define LANGSTANDARD(id, name, lang, desc, features) \
2091  .Case(name, LangStandard::lang_##id)
2092 #define LANGSTANDARD_ALIAS(id, alias) \
2093  .Case(alias, LangStandard::lang_##id)
2094 #include "clang/Frontend/LangStandards.def"
2096  if (LangStd == LangStandard::lang_unspecified) {
2097  Diags.Report(diag::err_drv_invalid_value)
2098  << A->getAsString(Args) << A->getValue();
2099  // Report supported standards with short description.
2100  for (unsigned KindValue = 0;
2101  KindValue != LangStandard::lang_unspecified;
2102  ++KindValue) {
2104  static_cast<LangStandard::Kind>(KindValue));
2105  if (IsInputCompatibleWithStandard(IK, Std)) {
2106  auto Diag = Diags.Report(diag::note_drv_use_standard);
2107  Diag << Std.getName() << Std.getDescription();
2108  unsigned NumAliases = 0;
2109 #define LANGSTANDARD(id, name, lang, desc, features)
2110 #define LANGSTANDARD_ALIAS(id, alias) \
2111  if (KindValue == LangStandard::lang_##id) ++NumAliases;
2112 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2113 #include "clang/Frontend/LangStandards.def"
2114  Diag << NumAliases;
2115 #define LANGSTANDARD(id, name, lang, desc, features)
2116 #define LANGSTANDARD_ALIAS(id, alias) \
2117  if (KindValue == LangStandard::lang_##id) Diag << alias;
2118 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2119 #include "clang/Frontend/LangStandards.def"
2120  }
2121  }
2122  } else {
2123  // Valid standard, check to make sure language and standard are
2124  // compatible.
2126  if (!IsInputCompatibleWithStandard(IK, Std)) {
2127  Diags.Report(diag::err_drv_argument_not_allowed_with)
2128  << A->getAsString(Args) << GetInputKindName(IK);
2129  }
2130  }
2131  }
2132 
2133  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2134  StringRef Name = A->getValue();
2135  if (Name == "full" || Name == "branch") {
2136  Opts.CFProtectionBranch = 1;
2137  }
2138  }
2139  // -cl-std only applies for OpenCL language standards.
2140  // Override the -std option in this case.
2141  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
2142  LangStandard::Kind OpenCLLangStd
2143  = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2144  .Cases("cl", "CL", LangStandard::lang_opencl10)
2145  .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2146  .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2147  .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
2148  .Case("c++", LangStandard::lang_openclcpp)
2150 
2151  if (OpenCLLangStd == LangStandard::lang_unspecified) {
2152  Diags.Report(diag::err_drv_invalid_value)
2153  << A->getAsString(Args) << A->getValue();
2154  }
2155  else
2156  LangStd = OpenCLLangStd;
2157  }
2158 
2159  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2160 
2161  llvm::Triple T(TargetOpts.Triple);
2162  CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
2163 
2164  // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2165  // This option should be deprecated for CL > 1.0 because
2166  // this option was added for compatibility with OpenCL 1.0.
2167  if (Args.getLastArg(OPT_cl_strict_aliasing)
2168  && Opts.OpenCLVersion > 100) {
2169  Diags.Report(diag::warn_option_invalid_ocl_version)
2170  << Opts.getOpenCLVersionTuple().getAsString()
2171  << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
2172  }
2173 
2174  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2175  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2176  // while a subset (the non-C++ GNU keywords) is provided by GCC's
2177  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2178  // name, as it doesn't seem a useful distinction.
2179  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
2180  Opts.GNUKeywords);
2181 
2182  Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2183 
2184  if (Args.hasArg(OPT_fno_operator_names))
2185  Opts.CXXOperatorNames = 0;
2186 
2187  if (Args.hasArg(OPT_fcuda_is_device))
2188  Opts.CUDAIsDevice = 1;
2189 
2190  if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2191  Opts.CUDAAllowVariadicFunctions = 1;
2192 
2193  if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2194  Opts.CUDAHostDeviceConstexpr = 0;
2195 
2196  if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2197  Opts.CUDADeviceApproxTranscendentals = 1;
2198 
2199  Opts.CUDARelocatableDeviceCode = Args.hasArg(OPT_fcuda_rdc);
2200 
2201  if (Opts.ObjC1) {
2202  if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2203  StringRef value = arg->getValue();
2204  if (Opts.ObjCRuntime.tryParse(value))
2205  Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2206  }
2207 
2208  if (Args.hasArg(OPT_fobjc_gc_only))
2209  Opts.setGC(LangOptions::GCOnly);
2210  else if (Args.hasArg(OPT_fobjc_gc))
2211  Opts.setGC(LangOptions::HybridGC);
2212  else if (Args.hasArg(OPT_fobjc_arc)) {
2213  Opts.ObjCAutoRefCount = 1;
2214  if (!Opts.ObjCRuntime.allowsARC())
2215  Diags.Report(diag::err_arc_unsupported_on_runtime);
2216  }
2217 
2218  // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2219  // whether the feature is actually enabled. This is predominantly
2220  // determined by -fobjc-runtime, but we allow it to be overridden
2221  // from the command line for testing purposes.
2222  if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2223  Opts.ObjCWeakRuntime = 1;
2224  else
2225  Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2226 
2227  // ObjCWeak determines whether __weak is actually enabled.
2228  // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2229  if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2230  if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2231  assert(!Opts.ObjCWeak);
2232  } else if (Opts.getGC() != LangOptions::NonGC) {
2233  Diags.Report(diag::err_objc_weak_with_gc);
2234  } else if (!Opts.ObjCWeakRuntime) {
2235  Diags.Report(diag::err_objc_weak_unsupported);
2236  } else {
2237  Opts.ObjCWeak = 1;
2238  }
2239  } else if (Opts.ObjCAutoRefCount) {
2240  Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2241  }
2242 
2243  if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2244  Opts.ObjCInferRelatedResultType = 0;
2245 
2246  if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2247  Opts.ObjCSubscriptingLegacyRuntime =
2249  }
2250 
2251  if (Args.hasArg(OPT_fgnu89_inline)) {
2252  if (Opts.CPlusPlus)
2253  Diags.Report(diag::err_drv_argument_not_allowed_with)
2254  << "-fgnu89-inline" << GetInputKindName(IK);
2255  else
2256  Opts.GNUInline = 1;
2257  }
2258 
2259  if (Args.hasArg(OPT_fapple_kext)) {
2260  if (!Opts.CPlusPlus)
2261  Diags.Report(diag::warn_c_kext);
2262  else
2263  Opts.AppleKext = 1;
2264  }
2265 
2266  if (Args.hasArg(OPT_print_ivar_layout))
2267  Opts.ObjCGCBitmapPrint = 1;
2268  if (Args.hasArg(OPT_fno_constant_cfstrings))
2269  Opts.NoConstantCFStrings = 1;
2270 
2271  if (Args.hasArg(OPT_fzvector))
2272  Opts.ZVector = 1;
2273 
2274  if (Args.hasArg(OPT_pthread))
2275  Opts.POSIXThreads = 1;
2276 
2277  // The value-visibility mode defaults to "default".
2278  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2279  Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2280  } else {
2281  Opts.setValueVisibilityMode(DefaultVisibility);
2282  }
2283 
2284  // The type-visibility mode defaults to the value-visibility mode.
2285  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2286  Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2287  } else {
2288  Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2289  }
2290 
2291  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2292  Opts.InlineVisibilityHidden = 1;
2293 
2294  if (Args.hasArg(OPT_ftrapv)) {
2295  Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2296  // Set the handler, if one is specified.
2297  Opts.OverflowHandler =
2298  Args.getLastArgValue(OPT_ftrapv_handler);
2299  }
2300  else if (Args.hasArg(OPT_fwrapv))
2301  Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2302 
2303  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2304  Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2305  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
2306  Opts.MSCompatibilityVersion = 0;
2307  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2308  VersionTuple VT;
2309  if (VT.tryParse(A->getValue()))
2310  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2311  << A->getValue();
2312  Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2313  VT.getMinor().getValueOr(0) * 100000 +
2314  VT.getSubminor().getValueOr(0);
2315  }
2316 
2317  // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
2318  // is specified, or -std is set to a conforming mode.
2319  // Trigraphs are disabled by default in c++1z onwards.
2320  Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
2321  Opts.Trigraphs =
2322  Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2323 
2324  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2325  OPT_fno_dollars_in_identifiers,
2326  Opts.DollarIdents);
2327  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
2328  Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
2329  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
2330  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
2331  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2332  Opts.ConstStrings);
2333  if (Args.hasArg(OPT_fno_lax_vector_conversions))
2334  Opts.LaxVectorConversions = 0;
2335  if (Args.hasArg(OPT_fno_threadsafe_statics))
2336  Opts.ThreadsafeStatics = 0;
2337  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
2338  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
2339  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
2340 
2341  // -ffixed-point
2342  Opts.FixedPoint =
2343  Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2344  !Opts.CPlusPlus;
2345  Opts.PaddingOnUnsignedFixedPoint =
2346  Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2347  OPT_fno_padding_on_unsigned_fixed_point,
2348  /*Default=*/false) &&
2349  Opts.FixedPoint;
2350 
2351  // Handle exception personalities
2352  Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
2353  options::OPT_fseh_exceptions,
2354  options::OPT_fdwarf_exceptions);
2355  if (A) {
2356  const Option &Opt = A->getOption();
2357  llvm::Triple T(TargetOpts.Triple);
2358  if (T.isWindowsMSVCEnvironment())
2359  Diags.Report(diag::err_fe_invalid_exception_model)
2360  << Opt.getName() << T.str();
2361 
2362  Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2363  Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2364  Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2365  }
2366 
2367  Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
2368  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
2369 
2370  Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
2371  Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
2372  Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
2373  && Opts.OpenCLVersion == 200);
2374  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
2375  Opts.CoroutinesTS = Args.hasArg(OPT_fcoroutines_ts);
2376 
2377  // Enable [[]] attributes in C++11 by default.
2378  Opts.DoubleSquareBracketAttributes =
2379  Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2380  OPT_fno_double_square_bracket_attributes, Opts.CPlusPlus11);
2381 
2382  Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2383  Opts.Modules = Args.hasArg(OPT_fmodules) || Opts.ModulesTS;
2384  Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2385  Opts.ModulesDeclUse =
2386  Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
2387  Opts.ModulesLocalVisibility =
2388  Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS;
2389  Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2390  Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
2391  Opts.ModulesSearchAll = Opts.Modules &&
2392  !Args.hasArg(OPT_fno_modules_search_all) &&
2393  Args.hasArg(OPT_fmodules_search_all);
2394  Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
2395  Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
2396  Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
2397  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
2398  Opts.Char8 = Args.hasArg(OPT_fchar8__t);
2399  if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2400  Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2401  .Case("char", 1)
2402  .Case("short", 2)
2403  .Case("int", 4)
2404  .Default(0);
2405  if (Opts.WCharSize == 0)
2406  Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2407  }
2408  Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
2409  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
2410  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2411  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2412  if (!Opts.NoBuiltin)
2414  Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
2415  Opts.RelaxedTemplateTemplateArgs =
2416  Args.hasArg(OPT_frelaxed_template_template_args);
2417  Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
2418  Opts.AlignedAllocation =
2419  Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2420  Opts.AlignedAllocation);
2421  Opts.AlignedAllocationUnavailable =
2422  Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
2423  Opts.NewAlignOverride =
2424  getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2425  if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2426  Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2427  Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2428  << A->getValue();
2429  Opts.NewAlignOverride = 0;
2430  }
2431  Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
2432  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
2433  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
2434  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
2435  Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
2436  Opts.InstantiationDepth =
2437  getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
2438  Opts.ArrowDepth =
2439  getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
2440  Opts.ConstexprCallDepth =
2441  getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2442  Opts.ConstexprStepLimit =
2443  getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2444  Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
2445  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
2446  Opts.NumLargeByValueCopy =
2447  getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
2448  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
2450  Args.getLastArgValue(OPT_fconstant_string_class);
2451  Opts.ObjCDefaultSynthProperties =
2452  !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
2453  Opts.EncodeExtendedBlockSig =
2454  Args.hasArg(OPT_fencode_extended_block_signature);
2455  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
2456  Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
2457  Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
2458  Opts.AlignDouble = Args.hasArg(OPT_malign_double);
2459  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2460  Opts.PIE = Args.hasArg(OPT_pic_is_pie);
2461  Opts.Static = Args.hasArg(OPT_static_define);
2462  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
2463  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2464  || Args.hasArg(OPT_fdump_record_layouts);
2465  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
2466  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
2467  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
2468  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
2469  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
2470  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
2471  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
2472  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
2473  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
2474  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
2475  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
2476  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
2477  Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ);
2478  Opts.CurrentModule = Opts.ModuleName;
2479  Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
2480  Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
2481  llvm::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end());
2482  Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
2483  Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2484  // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2485  // is enabled.
2486  Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2487  | Opts.NativeHalfArgsAndReturns;
2488  Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
2489 
2490  // __declspec is enabled by default for the PS4 by the driver, and also
2491  // enabled for Microsoft Extensions or Borland Extensions, here.
2492  //
2493  // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
2494  // CUDA extension. However, it is required for supporting
2495  // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2496  // been rewritten in terms of something more generic, remove the Opts.CUDA
2497  // term here.
2498  Opts.DeclSpecKeyword =
2499  Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2500  (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2501 
2502  if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2503  switch (llvm::StringSwitch<unsigned>(A->getValue())
2504  .Case("target", LangOptions::ASMM_Target)
2505  .Case("no", LangOptions::ASMM_Off)
2506  .Case("yes", LangOptions::ASMM_On)
2507  .Default(255)) {
2508  default:
2509  Diags.Report(diag::err_drv_invalid_value)
2510  << "-faddress-space-map-mangling=" << A->getValue();
2511  break;
2513  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2514  break;
2515  case LangOptions::ASMM_On:
2516  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2517  break;
2518  case LangOptions::ASMM_Off:
2519  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2520  break;
2521  }
2522  }
2523 
2524  if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2526  llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2527  A->getValue())
2528  .Case("single",
2530  .Case("multiple",
2532  .Case("virtual",
2534  .Default(LangOptions::PPTMK_BestCase);
2535  if (InheritanceModel == LangOptions::PPTMK_BestCase)
2536  Diags.Report(diag::err_drv_invalid_value)
2537  << "-fms-memptr-rep=" << A->getValue();
2538 
2539  Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2540  }
2541 
2542  // Check for MS default calling conventions being specified.
2543  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2545  llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
2546  .Case("cdecl", LangOptions::DCC_CDecl)
2547  .Case("fastcall", LangOptions::DCC_FastCall)
2548  .Case("stdcall", LangOptions::DCC_StdCall)
2549  .Case("vectorcall", LangOptions::DCC_VectorCall)
2550  .Case("regcall", LangOptions::DCC_RegCall)
2551  .Default(LangOptions::DCC_None);
2552  if (DefaultCC == LangOptions::DCC_None)
2553  Diags.Report(diag::err_drv_invalid_value)
2554  << "-fdefault-calling-conv=" << A->getValue();
2555 
2556  llvm::Triple T(TargetOpts.Triple);
2557  llvm::Triple::ArchType Arch = T.getArch();
2558  bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
2559  DefaultCC == LangOptions::DCC_StdCall) &&
2560  Arch != llvm::Triple::x86;
2561  emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
2562  DefaultCC == LangOptions::DCC_RegCall) &&
2563  !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2564  if (emitError)
2565  Diags.Report(diag::err_drv_argument_not_allowed_with)
2566  << A->getSpelling() << T.getTriple();
2567  else
2568  Opts.setDefaultCallingConv(DefaultCC);
2569  }
2570 
2571  // -mrtd option
2572  if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2573  if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2574  Diags.Report(diag::err_drv_argument_not_allowed_with)
2575  << A->getSpelling() << "-fdefault-calling-conv";
2576  else {
2577  llvm::Triple T(TargetOpts.Triple);
2578  if (T.getArch() != llvm::Triple::x86)
2579  Diags.Report(diag::err_drv_argument_not_allowed_with)
2580  << A->getSpelling() << T.getTriple();
2581  else
2582  Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2583  }
2584  }
2585 
2586  // Check if -fopenmp is specified.
2587  Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 1 : 0;
2588  // Check if -fopenmp-simd is specified.
2589  bool IsSimdSpecified =
2590  Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2591  /*Default=*/false);
2592  Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
2593  Opts.OpenMPUseTLS =
2594  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
2595  Opts.OpenMPIsDevice =
2596  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2597  bool IsTargetSpecified =
2598  Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
2599 
2600  if (Opts.OpenMP || Opts.OpenMPSimd) {
2601  if (int Version = getLastArgIntValue(
2602  Args, OPT_fopenmp_version_EQ,
2603  (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags))
2604  Opts.OpenMP = Version;
2605  else if (IsSimdSpecified || IsTargetSpecified)
2606  Opts.OpenMP = 45;
2607  // Provide diagnostic when a given target is not expected to be an OpenMP
2608  // device or host.
2609  if (!Opts.OpenMPIsDevice) {
2610  switch (T.getArch()) {
2611  default:
2612  break;
2613  // Add unsupported host targets here:
2614  case llvm::Triple::nvptx:
2615  case llvm::Triple::nvptx64:
2616  Diags.Report(diag::err_drv_omp_host_target_not_supported)
2617  << TargetOpts.Triple;
2618  break;
2619  }
2620  }
2621  }
2622 
2623  // Set the flag to prevent the implementation from emitting device exception
2624  // handling code for those requiring so.
2625  Opts.OpenMPHostCXXExceptions = Opts.Exceptions && Opts.CXXExceptions;
2626  if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) {
2627  Opts.Exceptions = 0;
2628  Opts.CXXExceptions = 0;
2629  }
2630 
2631  // Get the OpenMP target triples if any.
2632  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
2633 
2634  for (unsigned i = 0; i < A->getNumValues(); ++i) {
2635  llvm::Triple TT(A->getValue(i));
2636 
2637  if (TT.getArch() == llvm::Triple::UnknownArch ||
2638  !(TT.getArch() == llvm::Triple::ppc ||
2639  TT.getArch() == llvm::Triple::ppc64 ||
2640  TT.getArch() == llvm::Triple::ppc64le ||
2641  TT.getArch() == llvm::Triple::nvptx ||
2642  TT.getArch() == llvm::Triple::nvptx64 ||
2643  TT.getArch() == llvm::Triple::x86 ||
2644  TT.getArch() == llvm::Triple::x86_64))
2645  Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
2646  else
2647  Opts.OMPTargetTriples.push_back(TT);
2648  }
2649  }
2650 
2651  // Get OpenMP host file path if any and report if a non existent file is
2652  // found
2653  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
2654  Opts.OMPHostIRFile = A->getValue();
2655  if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
2656  Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
2657  << Opts.OMPHostIRFile;
2658  }
2659 
2660  // set CUDA mode for OpenMP target NVPTX if specified in options
2661  Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() &&
2662  Args.hasArg(options::OPT_fopenmp_cuda_mode);
2663 
2664  // Record whether the __DEPRECATED define was requested.
2665  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2666  OPT_fno_deprecated_macro,
2667  Opts.Deprecated);
2668 
2669  // FIXME: Eliminate this dependency.
2670  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
2671  OptSize = getOptimizationLevelSize(Args);
2672  Opts.Optimize = Opt != 0;
2673  Opts.OptimizeSize = OptSize != 0;
2674 
2675  // This is the __NO_INLINE__ define, which just depends on things like the
2676  // optimization level and -fno-inline, not actually whether the backend has
2677  // inlining enabled.
2678  Opts.NoInlineDefine = !Opts.Optimize;
2679  if (Arg *InlineArg = Args.getLastArg(
2680  options::OPT_finline_functions, options::OPT_finline_hint_functions,
2681  options::OPT_fno_inline_functions, options::OPT_fno_inline))
2682  if (InlineArg->getOption().matches(options::OPT_fno_inline))
2683  Opts.NoInlineDefine = true;
2684 
2685  Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
2686  Args.hasArg(OPT_cl_fast_relaxed_math);
2687  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
2688  Args.hasArg(OPT_cl_finite_math_only) ||
2689  Args.hasArg(OPT_cl_fast_relaxed_math);
2690  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
2691  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
2692  Args.hasArg(OPT_cl_fast_relaxed_math);
2693 
2694  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2695  StringRef Val = A->getValue();
2696  if (Val == "fast")
2697  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2698  else if (Val == "on")
2699  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2700  else if (Val == "off")
2701  Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
2702  else
2703  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2704  }
2705 
2706  Opts.RetainCommentsFromSystemHeaders =
2707  Args.hasArg(OPT_fretain_comments_from_system_headers);
2708 
2709  unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
2710  switch (SSP) {
2711  default:
2712  Diags.Report(diag::err_drv_invalid_value)
2713  << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2714  break;
2715  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2716  case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
2717  case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
2718  case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
2719  }
2720 
2721  // Parse -fsanitize= arguments.
2722  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2723  Diags, Opts.Sanitize);
2724  // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
2725  Opts.SanitizeAddressFieldPadding =
2726  getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
2727  Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
2728 
2729  // -fxray-instrument
2730  Opts.XRayInstrument =
2731  Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
2732 
2733  // -fxray-always-emit-customevents
2734  Opts.XRayAlwaysEmitCustomEvents =
2735  Args.hasFlag(OPT_fxray_always_emit_customevents,
2736  OPT_fnoxray_always_emit_customevents, false);
2737 
2738  // -fxray-always-emit-typedevents
2739  Opts.XRayAlwaysEmitTypedEvents =
2740  Args.hasFlag(OPT_fxray_always_emit_typedevents,
2741  OPT_fnoxray_always_emit_customevents, false);
2742 
2743  // -fxray-{always,never}-instrument= filenames.
2745  Args.getAllArgValues(OPT_fxray_always_instrument);
2747  Args.getAllArgValues(OPT_fxray_never_instrument);
2748  Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
2749 
2750  // -fforce-emit-vtables
2751  Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
2752 
2753  // -fallow-editor-placeholders
2754  Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
2755 
2756  if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
2757  Opts.setClangABICompat(LangOptions::ClangABI::Latest);
2758 
2759  StringRef Ver = A->getValue();
2760  std::pair<StringRef, StringRef> VerParts = Ver.split('.');
2761  unsigned Major, Minor = 0;
2762 
2763  // Check the version number is valid: either 3.x (0 <= x <= 9) or
2764  // y or y.0 (4 <= y <= current version).
2765  if (!VerParts.first.startswith("0") &&
2766  !VerParts.first.getAsInteger(10, Major) &&
2767  3 <= Major && Major <= CLANG_VERSION_MAJOR &&
2768  (Major == 3 ? VerParts.second.size() == 1 &&
2769  !VerParts.second.getAsInteger(10, Minor)
2770  : VerParts.first.size() == Ver.size() ||
2771  VerParts.second == "0")) {
2772  // Got a valid version number.
2773  if (Major == 3 && Minor <= 8)
2774  Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
2775  else if (Major <= 4)
2776  Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
2777  else if (Major <= 6)
2778  Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
2779  } else if (Ver != "latest") {
2780  Diags.Report(diag::err_drv_invalid_value)
2781  << A->getAsString(Args) << A->getValue();
2782  }
2783  }
2784 
2785  Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
2786  Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
2787 }
2788 
2790  switch (Action) {
2791  case frontend::ASTDeclList:
2792  case frontend::ASTDump:
2793  case frontend::ASTPrint:
2794  case frontend::ASTView:
2796  case frontend::EmitBC:
2797  case frontend::EmitHTML:
2798  case frontend::EmitLLVM:
2801  case frontend::EmitObj:
2802  case frontend::FixIt:
2805  case frontend::GeneratePCH:
2806  case frontend::GeneratePTH:
2809  case frontend::VerifyPCH:
2812  case frontend::RewriteObjC:
2813  case frontend::RewriteTest:
2814  case frontend::RunAnalysis:
2817  return false;
2818 
2821  case frontend::DumpTokens:
2822  case frontend::InitOnly:
2827  return true;
2828  }
2829  llvm_unreachable("invalid frontend action");
2830 }
2831 
2832 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
2833  DiagnosticsEngine &Diags,
2835  Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
2836  Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
2837  Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ);
2838  if (const Arg *A = Args.getLastArg(OPT_token_cache))
2839  Opts.TokenCache = A->getValue();
2840  else
2841  Opts.TokenCache = Opts.ImplicitPTHInclude;
2842  Opts.UsePredefines = !Args.hasArg(OPT_undef);
2843  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
2844  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
2845  Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
2846 
2847  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
2848  for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
2849  Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
2850 
2851  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
2852  StringRef Value(A->getValue());
2853  size_t Comma = Value.find(',');
2854  unsigned Bytes = 0;
2855  unsigned EndOfLine = 0;
2856 
2857  if (Comma == StringRef::npos ||
2858  Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2859  Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2860  Diags.Report(diag::err_drv_preamble_format);
2861  else {
2862  Opts.PrecompiledPreambleBytes.first = Bytes;
2863  Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2864  }
2865  }
2866 
2867  // Add the __CET__ macro if a CFProtection option is set.
2868  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2869  StringRef Name = A->getValue();
2870  if (Name == "branch")
2871  Opts.addMacroDef("__CET__=1");
2872  else if (Name == "return")
2873  Opts.addMacroDef("__CET__=2");
2874  else if (Name == "full")
2875  Opts.addMacroDef("__CET__=3");
2876  }
2877 
2878  // Add macros from the command line.
2879  for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
2880  if (A->getOption().matches(OPT_D))
2881  Opts.addMacroDef(A->getValue());
2882  else
2883  Opts.addMacroUndef(A->getValue());
2884  }
2885 
2886  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
2887 
2888  // Add the ordered list of -includes.
2889  for (const auto *A : Args.filtered(OPT_include))
2890  Opts.Includes.emplace_back(A->getValue());
2891 
2892  for (const auto *A : Args.filtered(OPT_chain_include))
2893  Opts.ChainedIncludes.emplace_back(A->getValue());
2894 
2895  for (const auto *A : Args.filtered(OPT_remap_file)) {
2896  std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
2897 
2898  if (Split.second.empty()) {
2899  Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
2900  continue;
2901  }
2902 
2903  Opts.addRemappedFile(Split.first, Split.second);
2904  }
2905 
2906  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
2907  StringRef Name = A->getValue();
2908  unsigned Library = llvm::StringSwitch<unsigned>(Name)
2909  .Case("libc++", ARCXX_libcxx)
2910  .Case("libstdc++", ARCXX_libstdcxx)
2911  .Case("none", ARCXX_nolib)
2912  .Default(~0U);
2913  if (Library == ~0U)
2914  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2915  else
2917  }
2918 
2919  // Always avoid lexing editor placeholders when we're just running the
2920  // preprocessor as we never want to emit the
2921  // "editor placeholder in source file" error in PP only mode.
2922  if (isStrictlyPreprocessorAction(Action))
2923  Opts.LexEditorPlaceholders = false;
2924 }
2925 
2927  ArgList &Args,
2929  if (isStrictlyPreprocessorAction(Action))
2930  Opts.ShowCPP = !Args.hasArg(OPT_dM);
2931  else
2932  Opts.ShowCPP = 0;
2933 
2934  Opts.ShowComments = Args.hasArg(OPT_C);
2935  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
2936  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
2937  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
2938  Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
2939  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
2940  Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
2941  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
2942 }
2943 
2944 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2945  DiagnosticsEngine &Diags) {
2946  Opts.ABI = Args.getLastArgValue(OPT_target_abi);
2947  if (Arg *A = Args.getLastArg(OPT_meabi)) {
2948  StringRef Value = A->getValue();
2949  llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
2950  .Case("default", llvm::EABI::Default)
2951  .Case("4", llvm::EABI::EABI4)
2952  .Case("5", llvm::EABI::EABI5)
2953  .Case("gnu", llvm::EABI::GNU)
2954  .Default(llvm::EABI::Unknown);
2955  if (EABIVersion == llvm::EABI::Unknown)
2956  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2957  << Value;
2958  else
2959  Opts.EABIVersion = EABIVersion;
2960  }
2961  Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
2962  Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
2963  Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
2964  Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
2965  Opts.Triple = Args.getLastArgValue(OPT_triple);
2966  // Use the default target triple if unspecified.
2967  if (Opts.Triple.empty())
2968  Opts.Triple = llvm::sys::getDefaultTargetTriple();
2969  Opts.Triple = llvm::Triple::normalize(Opts.Triple);
2970  Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
2971  Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
2972  Opts.NVPTXUseShortPointers = Args.hasFlag(
2973  options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
2974 }
2975 
2977  const char *const *ArgBegin,
2978  const char *const *ArgEnd,
2979  DiagnosticsEngine &Diags) {
2980  bool Success = true;
2981 
2982  // Parse the arguments.
2983  std::unique_ptr<OptTable> Opts = createDriverOptTable();
2984  const unsigned IncludedFlagsBitmask = options::CC1Option;
2985  unsigned MissingArgIndex, MissingArgCount;
2986  InputArgList Args =
2987  Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
2988  MissingArgCount, IncludedFlagsBitmask);
2989  LangOptions &LangOpts = *Res.getLangOpts();
2990 
2991  // Check for missing argument error.
2992  if (MissingArgCount) {
2993  Diags.Report(diag::err_drv_missing_argument)
2994  << Args.getArgString(MissingArgIndex) << MissingArgCount;
2995  Success = false;
2996  }
2997 
2998  // Issue errors on unknown arguments.
2999  for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
3000  auto ArgString = A->getAsString(Args);
3001  std::string Nearest;
3002  if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3003  Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3004  else
3005  Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3006  << ArgString << Nearest;
3007  Success = false;
3008  }
3009 
3010  Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3011  Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3013  Success &=
3014  ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3015  false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
3016  ParseCommentArgs(LangOpts.CommentOpts, Args);
3018  // FIXME: We shouldn't have to pass the DashX option around here
3019  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3020  LangOpts.IsHeaderFile);
3021  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
3022  Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
3023  Res.getTargetOpts(), Res.getFrontendOpts());
3026  if (DashX.getFormat() == InputKind::Precompiled ||
3027  DashX.getLanguage() == InputKind::LLVM_IR) {
3028  // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3029  // PassManager in BackendUtil.cpp. They need to be initializd no matter
3030  // what the input type is.
3031  if (Args.hasArg(OPT_fobjc_arc))
3032  LangOpts.ObjCAutoRefCount = 1;
3033  // PIClevel and PIELevel are needed during code generation and this should be
3034  // set regardless of the input type.
3035  LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3036  LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
3037  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3038  Diags, LangOpts.Sanitize);
3039  } else {
3040  // Other LangOpts are only initialzed when the input is not AST or LLVM IR.
3041  // FIXME: Should we really be calling this for an InputKind::Asm input?
3042  ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
3043  Res.getPreprocessorOpts(), Diags);
3045  LangOpts.ObjCExceptions = 1;
3046  }
3047 
3048  LangOpts.FunctionAlignment =
3049  getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3050 
3051  if (LangOpts.CUDA) {
3052  // During CUDA device-side compilation, the aux triple is the
3053  // triple used for host compilation.
3054  if (LangOpts.CUDAIsDevice)
3056  }
3057 
3058  // Set the triple of the host for OpenMP device compile.
3059  if (LangOpts.OpenMPIsDevice)
3061 
3062  // FIXME: Override value name discarding when asan or msan is used because the
3063  // backend passes depend on the name of the alloca in order to print out
3064  // names.
3065  Res.getCodeGenOpts().DiscardValueNames &=
3066  !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3067  !LangOpts.Sanitize.has(SanitizerKind::Memory);
3068 
3069  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
3073 
3074  // Turn on -Wspir-compat for SPIR target.
3075  llvm::Triple T(Res.getTargetOpts().Triple);
3076  auto Arch = T.getArch();
3077  if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64) {
3078  Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3079  }
3080 
3081  // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3082  if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3083  !Res.getLangOpts()->Sanitize.empty()) {
3084  Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3085  Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3086  }
3087  return Success;
3088 }
3089 
3091  // Note: For QoI reasons, the things we use as a hash here should all be
3092  // dumped via the -module-info flag.
3093  using llvm::hash_code;
3094  using llvm::hash_value;
3095  using llvm::hash_combine;
3096 
3097  // Start the signature with the compiler version.
3098  // FIXME: We'd rather use something more cryptographically sound than
3099  // CityHash, but this will do for now.
3100  hash_code code = hash_value(getClangFullRepositoryVersion());
3101 
3102  // Extend the signature with the language options
3103 #define LANGOPT(Name, Bits, Default, Description) \
3104  code = hash_combine(code, LangOpts->Name);
3105 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3106  code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
3107 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
3108 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3109 #include "clang/Basic/LangOptions.def"
3110 
3111  for (StringRef Feature : LangOpts->ModuleFeatures)
3112  code = hash_combine(code, Feature);
3113 
3114  // Extend the signature with the target options.
3115  code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
3116  TargetOpts->ABI);
3117  for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3118  code = hash_combine(code, FeatureAsWritten);
3119 
3120  // Extend the signature with preprocessor options.
3121  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
3122  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
3123  code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3124 
3125  for (const auto &I : getPreprocessorOpts().Macros) {
3126  // If we're supposed to ignore this macro for the purposes of modules,
3127  // don't put it into the hash.
3128  if (!hsOpts.ModulesIgnoreMacros.empty()) {
3129  // Check whether we're ignoring this macro.
3130  StringRef MacroDef = I.first;
3131  if (hsOpts.ModulesIgnoreMacros.count(
3132  llvm::CachedHashString(MacroDef.split('=').first)))
3133  continue;
3134  }
3135 
3136  code = hash_combine(code, I.first, I.second);
3137  }
3138 
3139  // Extend the signature with the sysroot and other header search options.
3140  code = hash_combine(code, hsOpts.Sysroot,
3141  hsOpts.ModuleFormat,
3142  hsOpts.UseDebugInfo,
3143  hsOpts.UseBuiltinIncludes,
3145  hsOpts.UseStandardCXXIncludes,
3146  hsOpts.UseLibcxx,
3148  code = hash_combine(code, hsOpts.ResourceDir);
3149 
3150  // Extend the signature with the user build path.
3151  code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3152 
3153  // Extend the signature with the module file extensions.
3154  const FrontendOptions &frontendOpts = getFrontendOpts();
3155  for (const auto &ext : frontendOpts.ModuleFileExtensions) {
3156  code = ext->hashExtension(code);
3157  }
3158 
3159  // Extend the signature with the enabled sanitizers, if at least one is
3160  // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3161  SanitizerSet SanHash = LangOpts->Sanitize;
3162  SanHash.clear(getPPTransparentSanitizers());
3163  if (!SanHash.empty())
3164  code = hash_combine(code, SanHash.Mask);
3165 
3166  return llvm::APInt(64, code).toString(36, /*Signed=*/false);
3167 }
3168 
3169 template<typename IntTy>
3170 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
3171  IntTy Default,
3172  DiagnosticsEngine *Diags) {
3173  IntTy Res = Default;
3174  if (Arg *A = Args.getLastArg(Id)) {
3175  if (StringRef(A->getValue()).getAsInteger(10, Res)) {
3176  if (Diags)
3177  Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
3178  << A->getValue();
3179  }
3180  }
3181  return Res;
3182 }
3183 
3184 namespace clang {
3185 
3186 // Declared in clang/Frontend/Utils.h.
3187 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
3188  DiagnosticsEngine *Diags) {
3189  return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
3190 }
3191 
3192 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
3193  uint64_t Default,
3194  DiagnosticsEngine *Diags) {
3195  return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
3196 }
3197 
3198 void BuryPointer(const void *Ptr) {
3199  // This function may be called only a small fixed amount of times per each
3200  // invocation, otherwise we do actually have a leak which we want to report.
3201  // If this function is called more than kGraveYardMaxSize times, the pointers
3202  // will not be properly buried and a leak detector will report a leak, which
3203  // is what we want in such case.
3204  static const size_t kGraveYardMaxSize = 16;
3205  LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
3206  static std::atomic<unsigned> GraveYardSize;
3207  unsigned Idx = GraveYardSize++;
3208  if (Idx >= kGraveYardMaxSize)
3209  return;
3210  GraveYard[Idx] = Ptr;
3211 }
3212 
3215  DiagnosticsEngine &Diags) {
3217 }
3218 
3221  DiagnosticsEngine &Diags,
3223  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3224  return BaseFS;
3225 
3227  new vfs::OverlayFileSystem(BaseFS));
3228  // earlier vfs files are on the bottom
3229  for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
3230  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
3231  BaseFS->getBufferForFile(File);
3232  if (!Buffer) {
3233  Diags.Report(diag::err_missing_vfs_overlay_file) << File;
3234  continue;
3235  }
3236 
3238  std::move(Buffer.get()), /*DiagHandler*/ nullptr, File);
3239  if (FS)
3240  Overlay->pushOverlay(FS);
3241  else
3242  Diags.Report(diag::err_invalid_vfs_overlay) << File;
3243  }
3244  return Overlay;
3245 }
3246 
3247 } // namespace clang
HeaderSearchOptions & getHeaderSearchOpts()
static Visibility parseVisibility(Arg *arg, ArgList &args, DiagnosticsEngine &diags)
Attempt to parse a visibility value out of the given argument.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
Expand macros but not #includes.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string OutputFile
The output file, if any.
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true, bool DefaultShowOpt=true)
Fill out Opts based on the options given in Args.
static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args)
Conform to the underlying platform&#39;s C and C++ ABIs as closely as we can.
unsigned InlineMaxStackDepth
The inlining stack depth limit.
Paths for &#39;#include <>&#39; added by &#39;-I&#39;.
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
std::string ObjCMTWhiteListPath
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
void addMacroUndef(StringRef Name)
Enable migration to modern ObjC readonly property.
static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile)
Generate pre-compiled module from a module map.
Attempt to be ABI-compatible with code generated by Clang 6.0.x (SVN r321711).
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
unsigned ImplicitModuleMaps
Implicit module maps.
static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, const TargetOptions &TargetOpts, PreprocessorOptions &PPOpts, DiagnosticsEngine &Diags)
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
Parse and perform semantic analysis.
Enable migration to add conforming protocols.
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
XRayInstrMask Mask
Definition: XRayInstr.h:63
std::string ModuleUserBuildPath
The directory used for a user build.
static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags)
unsigned IncludeGlobals
Show top-level decls in code completion results.
Emit a .bc file.
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:142
Format getFormat() const
Like System, but headers are implicitly wrapped in extern "C".
DependencyOutputOptions & getDependencyOutputOpts()
std::shared_ptr< HeaderSearchOptions > HeaderSearchOpts
Options controlling the #include directive.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the &#39;real&#39; file system, as seen by the operating system.
std::shared_ptr< llvm::Regex > OptimizationRemarkMissedPattern
Regular expression to select optimizations for which we should enable missed optimization remarks...
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
LangStandard - Information about the properties of a particular language standard.
Definition: LangStandard.h:42
static bool isBuiltinFunc(const char *Name)
Returns true if this is a libc/libm function without the &#39;__builtin_&#39; prefix.
Definition: Builtins.cpp:51
unsigned IncludeModuleFiles
Include module file dependencies.
void set(XRayInstrMask K, bool Value)
Definition: XRayInstr.h:54
Parse ASTs and print them.
bool hasDigraphs() const
hasDigraphs - Language supports digraphs.
Definition: LangStandard.h:94
Like System, but only used for C++.
std::string HeaderIncludeOutputFile
The file to write header include output to.
StringRef P
std::vector< std::string > Includes
static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector< std::string > &Levels, DiagnosticsEngine *Diags, DiagnosticLevelMask &M)
std::string FPDenormalMode
The floating-point denormal mode to use.
Defines types useful for describing an Objective-C runtime.
bool isObjectiveC() const
Is the language of the input some dialect of Objective-C?
unsigned visualizeExplodedGraphWithGraphViz
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Show all overloads.
Like System, but only used for ObjC++.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1294
static bool CreateFromArgs(CompilerInvocation &Res, const char *const *ArgBegin, const char *const *ArgEnd, DiagnosticsEngine &Diags)
Create a compiler invocation from a list of input options.
#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > Reciprocals
std::vector< std::string > RewriteMapFiles
Set of files defining the rules for the symbol rewriting.
Options for controlling comment parsing.
static const LangStandard & getLangStandardForKind(Kind K)
InputKind::Language getLanguage() const
Get the language that this standard describes.
Definition: LangStandard.h:63
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:37
static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, const std::string &WorkingDir)
std::string ImplicitPTHInclude
The implicit PTH input included at the start of the translation unit, or empty.
Options for controlling the target.
Definition: TargetOptions.h:26
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreMacros
The set of macro names that should be ignored for the purposes of computing the module hash...
void AddPath(StringRef Path, frontend::IncludeDirGroup Group, bool IsFramework, bool IgnoreSysRoot)
AddPath - Add the Path path to the specified Group list.
void addRemappedFile(StringRef From, StringRef To)
std::string FixItSuffix
If given, the new suffix for fix-it rewritten files.
std::string HostTriple
When compiling for the device side, contains the triple used to compile for the host.
Definition: TargetOptions.h:33
std::string SplitDwarfFile
The name for the split debug info file that we&#39;ll break out.
Like System, but searched after the system directories.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
std::string ModuleCachePath
The directory used for the module cache.
std::string DebugPass
Enable additional debugging information.
float __ovld __cnfn normalize(float p)
Returns a vector in the same direction as p but with a length of 1.
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Parse and apply any fixits to the source.
Defines the clang::SanitizerKind enum.
void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader)
AddSystemHeaderPrefix - Override whether #include directives naming a path starting with Prefix shoul...
static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
&#39;macosx-fragile&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:40
std::map< std::string, std::string > DebugPrefixMap
std::vector< std::string > XRayAlwaysInstrumentFiles
Paths to the XRay "always instrument" files specifying which objects (files, functions, variables) should be imbued with the XRay "always instrument" attribute.
Definition: LangOptions.h:152
bool isCPlusPlus14() const
isCPlusPlus14 - Language is a C++14 variant (or later).
Definition: LangStandard.h:84
std::string FPMath
If given, the unit to use for floating point math.
Definition: TargetOptions.h:39
static std::shared_ptr< llvm::Regex > GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args, Arg *RpassArg)
Create a new Regex instance out of the string value in RpassArg.
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:112
unsigned IncludeSystemHeaders
Include system header dependencies.
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
IntrusiveRefCntPtr< FileSystem > getVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Gets a FileSystem for a virtual file system described in YAML format.
Translate input source into HTML.
static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, DiagnosticsEngine &Diags, const TargetOptions &TargetOpts, const FrontendOptions &FrontendOpts)
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:73
Enable migration to modern ObjC literals.
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
unsigned eagerlyAssumeBinOpBifurcation
The flag regulates if we should eagerly assume evaluations of conditionals, thus, bifurcating the pat...
InputKind withFormat(Format F) const
std::vector< std::string > ASTMergeFiles
The list of AST files to merge.
std::string CodeModel
The code model to use (-mcmodel).
Print DeclContext and their Decls.
std::vector< std::string > ModulesEmbedFiles
The list of files to embed into the compiled module file.
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
Languages that the frontend can parse and compile.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
Definition: Visibility.h:46
std::shared_ptr< PreprocessorOptions > PreprocessorOpts
Options controlling the preprocessor (aside from #include handling).
unsigned IncludeCodePatterns
Show code patterns in code completion results.
Action - Represent an abstract compilation step to perform.
Definition: Action.h:48
A file system that allows overlaying one AbstractFileSystem on top of another.
Generate LLVM IR, but do not emit anything.
static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
Enable annotation of ObjCMethods of all kinds.
std::vector< std::string > XRayAttrListFiles
Paths to the XRay attribute list files, specifying which objects (files, functions, variables) should be imbued with the appropriate XRay attribute(s).
Definition: LangOptions.h:163
CodeGenOptions & getCodeGenOpts()
bool hasLineComments() const
Language supports &#39;//&#39; comments.
Definition: LangStandard.h:66
unsigned ShowStats
Show frontend performance metrics and statistics.
static void hash_combine(std::size_t &seed, const T &v)
Enable migration to modern ObjC readwrite property.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args)
static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
bool isOpenCL() const
isOpenCL - Language is a OpenCL variant.
Definition: LangStandard.h:106
bool isCPlusPlus2a() const
isCPlusPlus2a - Language is a post-C++17 variant (or later).
Definition: LangStandard.h:90
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned FixWhatYouCan
Apply fixes even if there are unfixable errors.
annotate property with NS_RETURNS_INNER_POINTER
Enable migration to NS_ENUM/NS_OPTIONS macros.
Defines the Diagnostic-related interfaces.
std::unique_ptr< llvm::opt::OptTable > createDriverOptTable()
std::string FullCompilerInvocation
Store full compiler invocation for reproducible instructions in the generated report.
std::vector< std::string > Warnings
The list of -W...
std::vector< std::pair< std::string, bool > > CheckersControlList
Pair of checker name and enable/disable.
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
AnalysisStores
AnalysisStores - Set of available analysis store models.
constexpr XRayInstrMask All
Definition: XRayInstr.h:42
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
Definition: LangStandard.h:78
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
VersionTuple getOpenCLVersionTuple() const
Return the OpenCL C or C++ version as a VersionTuple.
Definition: LangOptions.cpp:47
static void setPGOUseInstrumentor(CodeGenOptions &Opts, const Twine &ProfileName)
unsigned FixAndRecompile
Apply fixes and recompile.
Defines the clang::Visibility enumeration and various utility functions.
std::string FloatABI
The ABI to use for passing floating point arguments.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module &#39;requires&#39; decls in addition to the hard-coded list in ...
Definition: LangOptions.h:189
PreprocessorOutputOptions & getPreprocessorOutputOpts()
std::string ThreadModel
The thread model to use.
FrontendOptions & getFrontendOpts()
std::vector< std::string > DependentLibraries
A list of dependent libraries.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Dump the compiler configuration.
MigratorOptions & getMigratorOpts()
Dump template instantiations.
char CoverageVersion[4]
The version string to put into coverage files.
Dump out preprocessed tokens.
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:183
const char * getName() const
getName - Get the name of this standard.
Definition: LangStandard.h:57
AnalysisDiagClients AnalysisDiagOpt
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
void AddVFSOverlayFile(StringRef Name)
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g., -E).
static bool IsHeaderFile(const std::string &Filename)
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
Generate pre-compiled module from a C++ module interface file.
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:192
static std::string GetResourcesPath(const char *Argv0, void *MainAddr)
Get the directory where the compiler headers reside, relative to the compiler binary (found by the pa...
unsigned ModuleCachePruneInterval
The interval (in seconds) between pruning operations.
bool isCPlusPlus11() const
isCPlusPlus11 - Language is a C++11 variant (or later).
Definition: LangStandard.h:81
Defines the clang::LangOptions interface.
Enable migration to modern ObjC subscripting.
std::vector< std::string > Plugins
The list of plugins to load.
Show just the "best" overload candidates.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
Emit only debug info necessary for generating line number tables (-gline-tables-only).
static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id, IntTy Default, DiagnosticsEngine *Diags)
int Id
Definition: ASTDiff.cpp:191
void AddPrebuiltModulePath(StringRef Name)
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:203
Defines the clang::CommentOptions interface.
std::set< std::string > DeserializedPCHDeclsToErrorOn
This is a set of names for decls that we do not want to be deserialized, and we emit an error if they...
unsigned RewriteIncludes
Preprocess include directives only.
unsigned ShowTimers
Show timers for individual actions.
std::string LinkerVersion
If given, the version string of the linker in use.
Definition: TargetOptions.h:48
Only execute frontend initialization.
Defines version macros and version-related utility functions for Clang.
unsigned IncludeNamespaceLevelDecls
Show decls in namespace (including the global namespace) in code completion results.
Print the "preamble" of the input file.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
static llvm::Reloc::Model getRelocModel(ArgList &Args, DiagnosticsEngine &Diags)
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
Definition: ObjCRuntime.cpp:49
unsigned ShowHeaderIncludes
Show header inclusions (-H).
std::shared_ptr< llvm::Regex > OptimizationRemarkPattern
Regular expression to select optimizations for which we should enable optimization remarks...
Rewriter playground.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
bool hasImplicitInt() const
hasImplicitInt - Language allows variables to be typed as int implicitly.
Definition: LangStandard.h:103
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:118
static bool IsInputCompatibleWithStandard(InputKind IK, const LangStandard &S)
Check if input file kind and language standard are compatible.
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition: Sanitizers.h:67
unsigned ModulesEmbedAllFiles
Whether we should embed all used files into the PCM file.
AnalysisInliningMode
AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
Objects with "protected" visibility are seen by the dynamic linker but always dynamically resolve to ...
Definition: Visibility.h:42
unsigned ShowMacros
Print macro definitions.
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:165
static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, ArgList &Args, frontend::ActionKind Action)
static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action)
unsigned FixOnlyWarnings
Apply fixes only for warnings.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
bool ForceEnableInt128
If given, enables support for __int128_t and __uint128_t types.
Definition: TargetOptions.h:65
Attempt to be ABI-compatible with code generated by Clang 3.8.x (SVN r257626).
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector< std::string > &Diagnostics)
std::string AuxTriple
Auxiliary triple for CUDA compilation.
bool isC11() const
isC11 - Language is a superset of C11.
Definition: LangStandard.h:72
Defines the clang::XRayInstrKind enum.
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
bool hasHexFloats() const
hasHexFloats - Language supports hexadecimal float constants.
Definition: LangStandard.h:100
unsigned ShowIncludeDirectives
Print includes, imports etc. within preprocessed output.
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:85
unsigned ARCMTMigrateEmitARCErrors
Emit ARC errors even if the migrator can fix them.
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:61
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:42
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
AnalyzerOptionsRef getAnalyzerOpts() const
AnalysisStores AnalysisStoreOpt
InputKind getPreprocessed() const
Encodes a location in the source.
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
Generate machine code, but don&#39;t emit anything.
Assembly: we accept this only so that we can preprocess it.
std::vector< std::string > ModuleFiles
The list of additional prebuilt module files to load before processing the input. ...
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
Limit generated debug info to reduce size (-fno-standalone-debug).
Options for controlling the compiler diagnostics engine.
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
std::vector< FrontendInputFile > Inputs
The input files and their types.
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
Kind getKind() const
Definition: ObjCRuntime.h:77
unsigned ModulesValidateSystemHeaders
Whether to validate system input files when a module is loaded.
ConfigTable Config
A key-value table of use-specified configuration values.
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
The kind of a file that we&#39;ve been handed as an input.
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)
unsigned IncludeTimestamps
Whether timestamps should be written to the produced PCH file.
Parse ASTs and view them in Graphviz.
std::vector< std::string > Remarks
The list of -R...
std::vector< std::string > OpenCLExtensionsAsWritten
The list of OpenCL extensions to enable or disable, as written on the command line.
Definition: TargetOptions.h:62
unsigned visualizeExplodedGraphWithUbiGraph
Parse ASTs and list Decl nodes.
unsigned Verbose
Whether header search information should be output as for -v.
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:90
static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector< std::string > &Funcs)
Defines the clang::TargetOptions class.
std::unordered_map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
DiagnosticOptions & getDiagnosticOpts() const
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
unsigned ASTDumpLookups
Whether we include lookup table dumps in AST dumps.
std::vector< std::string > ExtraDeps
A list of filenames to be used as extra dependencies for every target.
Load and verify that a PCH file is usable.
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
std::string ModuleName
The module currently being compiled as speficied by -fmodule-name.
Definition: LangOptions.h:176
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
unsigned UseLineDirectives
Use #line instead of GCC-style # N.
Like System, but only used for ObjC.
unsigned ShowVersion
Show the -version text.
unsigned RewriteImports
Include contents of transitively-imported modules.
std::shared_ptr< llvm::Regex > OptimizationRemarkAnalysisPattern
Regular expression to select optimizations for which we should enable optimization analyses...
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
Definition: TargetOptions.h:51
XRayInstrSet XRayInstrumentationBundle
Set of XRay instrumentation kinds to emit.
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
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:173
static ParsedSourceLocation FromString(StringRef Str)
Construct a parsed source location from a string; the Filename is empty on error. ...
PreprocessorOptions & getPreprocessorOpts()
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Language getLanguage() const
frontend::ActionKind ProgramAction
The frontend action to perform.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:199
std::vector< std::string > VerifyPrefixes
The prefixes for comment directives sought by -verify ("expected" by default).
std::string ARCMTMigrateReportOut
std::string PreferVectorWidth
The preferred width for auto-vectorization transforms.
Emit location information but do not generate debug info in the output.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Like System, but only used for C.
bool empty() const
Returns true if at least one sanitizer is enabled.
Definition: Sanitizers.h:70
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
AnalysisConstraints AnalysisConstraintsOpt
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
static bool isStrictlyPreprocessorAction(frontend::ActionKind Action)
Helper class for holding the data necessary to invoke the compiler.
Defines the virtual file system interface vfs::FileSystem.
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
unsigned UsePhonyTargets
Include phony targets for each dependency, which can avoid some &#39;make&#39; problems.
std::string AnalyzeSpecificFunction
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i...
Definition: LangOptions.h:207
FrontendOptions - Options for controlling the behavior of the frontend.
bool isC17() const
isC17 - Language is a superset of C17.
Definition: LangStandard.h:75
static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args)
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
Definition: Sanitizers.cpp:19
Run a plugin action,.
bool isGNUMode() const
isGNUMode - Language includes GNU extensions.
Definition: LangStandard.h:97
uint64_t SanitizerMask
Definition: Sanitizers.h:26
std::string StatsFile
Filename to write statistics to.
void BuryPointer(const void *Ptr)
Parse ASTs and dump them.
Don&#39;t generate debug info.
Enable migration of ObjC methods to &#39;instancetype&#39;.
std::string CoverageDataFile
The filename with path we use for coverage data files.
Defines the clang::FileSystemOptions interface.
std::vector< std::string > LinkerOptions
A list of linker options to embed in the object file.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
CodeCompleteOptions CodeCompleteOpts
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor)
IntrusiveRefCntPtr< DiagnosticOptions > DiagnosticOpts
Options controlling the diagnostic engine.
std::vector< std::string > AddPluginActions
The list of plugin actions to run in addition to the normal action.
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
AnalysisPurgeMode
AnalysisPurgeModes - Set of available strategies for dead symbol removal.
Keeps track of options that affect how file operations are performed.
prefer &#39;atomic&#39; property over &#39;nonatomic&#39;.
unsigned DisableFree
Disable memory freeing on exit.
Generate pre-compiled header.
int getLastArgIntValue(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, int Default, DiagnosticsEngine *Diags=nullptr)
Return the value of the last argument as an integer, or a default.
enum clang::FrontendOptions::@169 ARCMTAction
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13820
unsigned ShowMacroComments
Show comments, even in macros.
bool isUnknown() const
Is the input kind fully-unknown?
Defines the clang::SourceLocation class and associated facilities.
unsigned NoRetryExhausted
Do not re-analyze paths leading to exhausted nodes with a different strategy.
std::vector< std::string > XRayNeverInstrumentFiles
Paths to the XRay "never instrument" files specifying which objects (files, functions, variables) should be imbued with the XRay "never instrument" attribute.
Definition: LangOptions.h:158
bool NVPTXUseShortPointers
If enabled, use 32-bit pointers for accessing const/local/shared address space.
Definition: TargetOptions.h:69
std::string MainFileName
The user provided name for the "main file", if non-empty.
unsigned ModuleCachePruneAfter
The time (in seconds) after which an unused module file will be considered unused and will...
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:195
static bool checkVerifyPrefixes(const std::vector< std::string > &VerifyPrefixes, DiagnosticsEngine *Diags)
XRayInstrMask parseXRayInstrValue(StringRef Value)
Definition: XRayInstr.cpp:19
bool isC99() const
isC99 - Language is a superset of C99.
Definition: LangStandard.h:69
unsigned IncludeFixIts
Include results after corrections (small fix-its), e.g.
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
Enable converting setter/getter expressions to property-dot syntx.
Enable migration to modern ObjC property.
std::string ActionName
The name of the action to run when using a plugin action.
unsigned ShowLineMarkers
Show #line markers.
bool isCPlusPlus17() const
isCPlusPlus17 - Language is a C++17 variant (or later).
Definition: LangStandard.h:87
FileSystemOptions & getFileSystemOpts()
static unsigned getOptimizationLevelSize(ArgList &Args)
Run one or more source code analyses.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:52
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::vector< std::string > LLVMArgs
A list of arguments to forward to LLVM&#39;s option processing; this should only be used for debugging an...
std::vector< std::string > Targets
A list of names to use as the targets in the dependency file; this list must contain at least one ent...
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate and -fprofile-generate.
const char * getDescription() const
getDescription - Get the description of this standard.
Definition: LangStandard.h:60
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
DiagnosticLevelMask
A bitmask representing the diagnostic levels used by VerifyDiagnosticConsumer.
Dump information about a module file.
unsigned ModuleMapFileHomeIsCwd
Set the &#39;home directory&#39; of a module map file to the current working directory (or the home directory...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
unsigned AddMissingHeaderDeps
Add missing headers to dependency list.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
std::vector< std::string > SanitizerBlacklistFiles
Paths to blacklist files specifying which objects (files, functions, variables) should not be instrum...
Definition: LangOptions.h:146
unsigned ShowCPP
Print normal preprocessed output.
Like Angled, but marks header maps used when building frameworks.
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Generate pre-tokenized header.
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
std::string ObjCConstantStringClass
Definition: LangOptions.h:167
use NS_NONATOMIC_IOSONLY for property &#39;atomic&#39; attribute
#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)
unsigned IncludeMacros
Show macros in code completion results.
AnalysisPurgeMode AnalysisPurgeOpt
static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, ArgList &Args, DiagnosticsEngine &D, XRayInstrSet &S)
bool DumpDeserializedPCHDecls
Dump declarations that are deserialized from PCH, for testing.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::map< std::string, std::string > PrebuiltModuleFiles
The mapping of module names to prebuilt module files.
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)
Defines enum values for all the target-independent builtin functions.
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
std::string ModuleFormat
The module/pch container format.
static void parseSanitizerKinds(StringRef FlagName, const std::vector< std::string > &Sanitizers, DiagnosticsEngine &Diags, SanitizerSet &S)
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:193
LangStandard::Kind Std
std::string DiagnosticLogFile
The file to log diagnostic output to.
std::string TokenCache
If given, a PTH cache file to use for speeding up header parsing.
bool ParseAllComments
Treat ordinary comments as documentation comments.
bool LexEditorPlaceholders
When enabled, the preprocessor will construct editor placeholder tokens.
std::vector< std::string > ModuleMapFiles
The list of module map files to load before processing the input.