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
10 #include "TestModuleFileExtension.h"
11 #include "clang/Basic/Builtins.h"
12 #include "clang/Basic/FileManager.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/DriverDiagnostic.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/Util.h"
18 #include "clang/Frontend/CompilerInvocation.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "clang/Frontend/LangStandard.h"
21 #include "clang/Frontend/Utils.h"
22 #include "clang/Lex/HeaderSearchOptions.h"
23 #include "clang/Serialization/ASTReader.h"
24 #include "clang/Serialization/ModuleFileExtension.h"
25 #include "llvm/ADT/Hashing.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/Linker/Linker.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Option/Option.h"
36 #include "llvm/ProfileData/InstrProfReader.h"
37 #include "llvm/Support/CodeGen.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Process.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/ScopedPrinter.h"
45 #include <atomic>
46 #include <memory>
47 #include <sys/stat.h>
48 #include <system_error>
49 using namespace clang;
50
51 //===----------------------------------------------------------------------===//
52 // Initialization.
53 //===----------------------------------------------------------------------===//
54
CompilerInvocationBase()55 CompilerInvocationBase::CompilerInvocationBase()
56 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
57 DiagnosticOpts(new DiagnosticOptions()),
58 HeaderSearchOpts(new HeaderSearchOptions()),
59 PreprocessorOpts(new PreprocessorOptions()) {}
60
CompilerInvocationBase(const CompilerInvocationBase & X)61 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
62 : RefCountedBase<CompilerInvocation>(),
63 LangOpts(new LangOptions(*X.getLangOpts())),
64 TargetOpts(new TargetOptions(X.getTargetOpts())),
65 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
66 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
67 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
68
~CompilerInvocationBase()69 CompilerInvocationBase::~CompilerInvocationBase() {}
70
71 //===----------------------------------------------------------------------===//
72 // Deserialization (from args)
73 //===----------------------------------------------------------------------===//
74
75 using namespace clang::driver;
76 using namespace clang::driver::options;
77 using namespace llvm::opt;
78
79 //
80
getOptimizationLevel(ArgList & Args,InputKind IK,DiagnosticsEngine & Diags)81 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
82 DiagnosticsEngine &Diags) {
83 unsigned DefaultOpt = 0;
84 if (IK == IK_OpenCL && !Args.hasArg(OPT_cl_opt_disable))
85 DefaultOpt = 2;
86
87 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
88 if (A->getOption().matches(options::OPT_O0))
89 return 0;
90
91 if (A->getOption().matches(options::OPT_Ofast))
92 return 3;
93
94 assert (A->getOption().matches(options::OPT_O));
95
96 StringRef S(A->getValue());
97 if (S == "s" || S == "z" || S.empty())
98 return 2;
99
100 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
101 }
102
103 return DefaultOpt;
104 }
105
getOptimizationLevelSize(ArgList & Args)106 static unsigned getOptimizationLevelSize(ArgList &Args) {
107 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
108 if (A->getOption().matches(options::OPT_O)) {
109 switch (A->getValue()[0]) {
110 default:
111 return 0;
112 case 's':
113 return 1;
114 case 'z':
115 return 2;
116 }
117 }
118 }
119 return 0;
120 }
121
addDiagnosticArgs(ArgList & Args,OptSpecifier Group,OptSpecifier GroupWithValue,std::vector<std::string> & Diagnostics)122 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
123 OptSpecifier GroupWithValue,
124 std::vector<std::string> &Diagnostics) {
125 for (Arg *A : Args.filtered(Group)) {
126 if (A->getOption().getKind() == Option::FlagClass) {
127 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
128 // its name (minus the "W" or "R" at the beginning) to the warning list.
129 Diagnostics.push_back(A->getOption().getName().drop_front(1));
130 } else if (A->getOption().matches(GroupWithValue)) {
131 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
132 Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
133 } else {
134 // Otherwise, add its value (for OPT_W_Joined and similar).
135 for (const char *Arg : A->getValues())
136 Diagnostics.emplace_back(Arg);
137 }
138 }
139 }
140
getAllNoBuiltinFuncValues(ArgList & Args,std::vector<std::string> & Funcs)141 static void getAllNoBuiltinFuncValues(ArgList &Args,
142 std::vector<std::string> &Funcs) {
143 SmallVector<const char *, 8> Values;
144 for (const auto &Arg : Args) {
145 const Option &O = Arg->getOption();
146 if (O.matches(options::OPT_fno_builtin_)) {
147 const char *FuncName = Arg->getValue();
148 if (Builtin::Context::isBuiltinFunc(FuncName))
149 Values.push_back(FuncName);
150 }
151 }
152 Funcs.insert(Funcs.end(), Values.begin(), Values.end());
153 }
154
ParseAnalyzerArgs(AnalyzerOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)155 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
156 DiagnosticsEngine &Diags) {
157 using namespace options;
158 bool Success = true;
159 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
160 StringRef Name = A->getValue();
161 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
162 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
163 .Case(CMDFLAG, NAME##Model)
164 #include "clang/StaticAnalyzer/Core/Analyses.def"
165 .Default(NumStores);
166 if (Value == NumStores) {
167 Diags.Report(diag::err_drv_invalid_value)
168 << A->getAsString(Args) << Name;
169 Success = false;
170 } else {
171 Opts.AnalysisStoreOpt = Value;
172 }
173 }
174
175 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
176 StringRef Name = A->getValue();
177 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
178 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
179 .Case(CMDFLAG, NAME##Model)
180 #include "clang/StaticAnalyzer/Core/Analyses.def"
181 .Default(NumConstraints);
182 if (Value == NumConstraints) {
183 Diags.Report(diag::err_drv_invalid_value)
184 << A->getAsString(Args) << Name;
185 Success = false;
186 } else {
187 Opts.AnalysisConstraintsOpt = Value;
188 }
189 }
190
191 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
192 StringRef Name = A->getValue();
193 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
194 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
195 .Case(CMDFLAG, PD_##NAME)
196 #include "clang/StaticAnalyzer/Core/Analyses.def"
197 .Default(NUM_ANALYSIS_DIAG_CLIENTS);
198 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
199 Diags.Report(diag::err_drv_invalid_value)
200 << A->getAsString(Args) << Name;
201 Success = false;
202 } else {
203 Opts.AnalysisDiagOpt = Value;
204 }
205 }
206
207 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
208 StringRef Name = A->getValue();
209 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
210 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
211 .Case(CMDFLAG, NAME)
212 #include "clang/StaticAnalyzer/Core/Analyses.def"
213 .Default(NumPurgeModes);
214 if (Value == NumPurgeModes) {
215 Diags.Report(diag::err_drv_invalid_value)
216 << A->getAsString(Args) << Name;
217 Success = false;
218 } else {
219 Opts.AnalysisPurgeOpt = Value;
220 }
221 }
222
223 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
224 StringRef Name = A->getValue();
225 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
226 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
227 .Case(CMDFLAG, NAME)
228 #include "clang/StaticAnalyzer/Core/Analyses.def"
229 .Default(NumInliningModes);
230 if (Value == NumInliningModes) {
231 Diags.Report(diag::err_drv_invalid_value)
232 << A->getAsString(Args) << Name;
233 Success = false;
234 } else {
235 Opts.InliningMode = Value;
236 }
237 }
238
239 Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
240 Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
241
242 Opts.visualizeExplodedGraphWithGraphViz =
243 Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
244 Opts.visualizeExplodedGraphWithUbiGraph =
245 Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
246 Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
247 Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
248 Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
249 Opts.AnalyzeNestedBlocks =
250 Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
251 Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
252 Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
253 Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
254 Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
255 Opts.maxBlockVisitOnPath =
256 getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
257 Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
258 Opts.InlineMaxStackDepth =
259 getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
260 Opts.InlineMaxStackDepth, Diags);
261
262 Opts.CheckersControlList.clear();
263 for (const Arg *A :
264 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
265 A->claim();
266 bool enable = (A->getOption().getID() == OPT_analyzer_checker);
267 // We can have a list of comma separated checker names, e.g:
268 // '-analyzer-checker=cocoa,unix'
269 StringRef checkerList = A->getValue();
270 SmallVector<StringRef, 4> checkers;
271 checkerList.split(checkers, ",");
272 for (StringRef checker : checkers)
273 Opts.CheckersControlList.emplace_back(checker, enable);
274 }
275
276 // Go through the analyzer configuration options.
277 for (const Arg *A : Args.filtered(OPT_analyzer_config)) {
278 A->claim();
279 // We can have a list of comma separated config names, e.g:
280 // '-analyzer-config key1=val1,key2=val2'
281 StringRef configList = A->getValue();
282 SmallVector<StringRef, 4> configVals;
283 configList.split(configVals, ",");
284 for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
285 StringRef key, val;
286 std::tie(key, val) = configVals[i].split("=");
287 if (val.empty()) {
288 Diags.Report(SourceLocation(),
289 diag::err_analyzer_config_no_value) << configVals[i];
290 Success = false;
291 break;
292 }
293 if (val.find('=') != StringRef::npos) {
294 Diags.Report(SourceLocation(),
295 diag::err_analyzer_config_multiple_values)
296 << configVals[i];
297 Success = false;
298 break;
299 }
300 Opts.Config[key] = val;
301 }
302 }
303
304 return Success;
305 }
306
ParseMigratorArgs(MigratorOptions & Opts,ArgList & Args)307 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
308 Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
309 Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
310 return true;
311 }
312
ParseCommentArgs(CommentOptions & Opts,ArgList & Args)313 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
314 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
315 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
316 }
317
getCodeModel(ArgList & Args,DiagnosticsEngine & Diags)318 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
319 if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
320 StringRef Value = A->getValue();
321 if (Value == "small" || Value == "kernel" || Value == "medium" ||
322 Value == "large")
323 return Value;
324 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
325 }
326 return "default";
327 }
328
329 /// \brief Create a new Regex instance out of the string value in \p RpassArg.
330 /// It returns a pointer to the newly generated Regex instance.
331 static std::shared_ptr<llvm::Regex>
GenerateOptimizationRemarkRegex(DiagnosticsEngine & Diags,ArgList & Args,Arg * RpassArg)332 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
333 Arg *RpassArg) {
334 StringRef Val = RpassArg->getValue();
335 std::string RegexError;
336 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
337 if (!Pattern->isValid(RegexError)) {
338 Diags.Report(diag::err_drv_optimization_remark_pattern)
339 << RegexError << RpassArg->getAsString(Args);
340 Pattern.reset();
341 }
342 return Pattern;
343 }
344
parseDiagnosticLevelMask(StringRef FlagName,const std::vector<std::string> & Levels,DiagnosticsEngine * Diags,DiagnosticLevelMask & M)345 static bool parseDiagnosticLevelMask(StringRef FlagName,
346 const std::vector<std::string> &Levels,
347 DiagnosticsEngine *Diags,
348 DiagnosticLevelMask &M) {
349 bool Success = true;
350 for (const auto &Level : Levels) {
351 DiagnosticLevelMask const PM =
352 llvm::StringSwitch<DiagnosticLevelMask>(Level)
353 .Case("note", DiagnosticLevelMask::Note)
354 .Case("remark", DiagnosticLevelMask::Remark)
355 .Case("warning", DiagnosticLevelMask::Warning)
356 .Case("error", DiagnosticLevelMask::Error)
357 .Default(DiagnosticLevelMask::None);
358 if (PM == DiagnosticLevelMask::None) {
359 Success = false;
360 if (Diags)
361 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
362 }
363 M = M | PM;
364 }
365 return Success;
366 }
367
parseSanitizerKinds(StringRef FlagName,const std::vector<std::string> & Sanitizers,DiagnosticsEngine & Diags,SanitizerSet & S)368 static void parseSanitizerKinds(StringRef FlagName,
369 const std::vector<std::string> &Sanitizers,
370 DiagnosticsEngine &Diags, SanitizerSet &S) {
371 for (const auto &Sanitizer : Sanitizers) {
372 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
373 if (K == 0)
374 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
375 else
376 S.set(K, true);
377 }
378 }
379
380 // Set the profile kind for fprofile-instrument.
setPGOInstrumentor(CodeGenOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)381 static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
382 DiagnosticsEngine &Diags) {
383 Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
384 if (A == nullptr)
385 return;
386 StringRef S = A->getValue();
387 unsigned I = llvm::StringSwitch<unsigned>(S)
388 .Case("none", CodeGenOptions::ProfileNone)
389 .Case("clang", CodeGenOptions::ProfileClangInstr)
390 .Case("llvm", CodeGenOptions::ProfileIRInstr)
391 .Default(~0U);
392 if (I == ~0U) {
393 Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
394 << S;
395 return;
396 }
397 CodeGenOptions::ProfileInstrKind Instrumentor =
398 static_cast<CodeGenOptions::ProfileInstrKind>(I);
399 Opts.setProfileInstr(Instrumentor);
400 }
401
402 // Set the profile kind using fprofile-instrument-use-path.
setPGOUseInstrumentor(CodeGenOptions & Opts,const Twine & ProfileName)403 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
404 const Twine &ProfileName) {
405 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
406 // In error, return silently and let Clang PGOUse report the error message.
407 if (auto E = ReaderOrErr.takeError()) {
408 llvm::consumeError(std::move(E));
409 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
410 return;
411 }
412 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
413 std::move(ReaderOrErr.get());
414 if (PGOReader->isIRLevelProfile())
415 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
416 else
417 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
418 }
419
ParseCodeGenArgs(CodeGenOptions & Opts,ArgList & Args,InputKind IK,DiagnosticsEngine & Diags,const TargetOptions & TargetOpts)420 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
421 DiagnosticsEngine &Diags,
422 const TargetOptions &TargetOpts) {
423 using namespace options;
424 bool Success = true;
425 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
426
427 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
428 // TODO: This could be done in Driver
429 unsigned MaxOptLevel = 3;
430 if (OptimizationLevel > MaxOptLevel) {
431 // If the optimization level is not supported, fall back on the default
432 // optimization
433 Diags.Report(diag::warn_drv_optimization_value)
434 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
435 OptimizationLevel = MaxOptLevel;
436 }
437 Opts.OptimizationLevel = OptimizationLevel;
438
439 // We must always run at least the always inlining pass.
440 Opts.setInlining(
441 (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalInlining
442 : CodeGenOptions::OnlyAlwaysInlining);
443 // -fno-inline-functions overrides OptimizationLevel > 1.
444 Opts.NoInline = Args.hasArg(OPT_fno_inline);
445 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
446 options::OPT_finline_hint_functions,
447 options::OPT_fno_inline_functions)) {
448 const Option& InlineOpt = InlineArg->getOption();
449 if (InlineOpt.matches(options::OPT_finline_functions))
450 Opts.setInlining(CodeGenOptions::NormalInlining);
451 else if (InlineOpt.matches(options::OPT_finline_hint_functions))
452 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
453 else
454 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
455 }
456
457 if (Arg *A = Args.getLastArg(OPT_fveclib)) {
458 StringRef Name = A->getValue();
459 if (Name == "Accelerate")
460 Opts.setVecLib(CodeGenOptions::Accelerate);
461 else if (Name == "none")
462 Opts.setVecLib(CodeGenOptions::NoLibrary);
463 else
464 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
465 }
466
467 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
468 unsigned Val =
469 llvm::StringSwitch<unsigned>(A->getValue())
470 .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
471 .Case("limited", codegenoptions::LimitedDebugInfo)
472 .Case("standalone", codegenoptions::FullDebugInfo)
473 .Default(~0U);
474 if (Val == ~0U)
475 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
476 << A->getValue();
477 else
478 Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
479 }
480 if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
481 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
482 .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
483 .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
484 .Case("sce", unsigned(llvm::DebuggerKind::SCE))
485 .Default(~0U);
486 if (Val == ~0U)
487 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
488 << A->getValue();
489 else
490 Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
491 }
492 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
493 Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
494 Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
495 Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
496 Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
497 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
498 Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
499 Opts.DebugExplicitImport = Triple.isPS4CPU();
500
501 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
502 Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
503
504 if (const Arg *A =
505 Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
506 Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
507
508 Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns);
509 Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
510 Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
511 Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
512 Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
513 OPT_fuse_register_sized_bitfield_access);
514 Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
515 Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
516 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
517 Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants);
518 Opts.NoCommon = Args.hasArg(OPT_fno_common);
519 Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
520 Opts.OptimizeSize = getOptimizationLevelSize(Args);
521 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
522 Args.hasArg(OPT_ffreestanding));
523 if (Opts.SimplifyLibCalls)
524 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
525 Opts.UnrollLoops =
526 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
527 (Opts.OptimizationLevel > 1));
528 Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
529
530 Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
531 Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
532 Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
533
534 setPGOInstrumentor(Opts, Args, Diags);
535 Opts.InstrProfileOutput =
536 Args.getLastArgValue(OPT_fprofile_instrument_path_EQ);
537 Opts.ProfileInstrumentUsePath =
538 Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ);
539 if (!Opts.ProfileInstrumentUsePath.empty())
540 setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
541
542 Opts.CoverageMapping =
543 Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
544 Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
545 Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
546 Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
547 Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
548 Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
549 Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
550 Opts.CodeModel = getCodeModel(Args, Diags);
551 Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
552 Opts.DisableFPElim =
553 (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg));
554 Opts.DisableFree = Args.hasArg(OPT_disable_free);
555 Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
556 Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
557 Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
558 Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable);
559 Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
560 Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
561 Args.hasArg(OPT_cl_finite_math_only) ||
562 Args.hasArg(OPT_cl_fast_relaxed_math));
563 Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
564 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
565 Args.hasArg(OPT_cl_finite_math_only) ||
566 Args.hasArg(OPT_cl_fast_relaxed_math));
567 Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
568 Args.hasArg(OPT_cl_no_signed_zeros));
569 Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
570 Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
571 Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
572 Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
573 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
574 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
575 Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
576 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
577 Opts.IncrementalLinkerCompatible =
578 Args.hasArg(OPT_mincremental_linker_compatible);
579 Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
580 Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
581 Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
582 Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
583 Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
584 Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
585 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
586 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
587 Args.hasArg(OPT_cl_fast_relaxed_math);
588 Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
589 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
590 Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
591 if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
592 Diags.Report(diag::err_drv_invalid_value)
593 << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
594 << Opts.ThreadModel;
595 Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
596 Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
597
598 Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
599 OPT_fno_function_sections, false);
600 Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
601 OPT_fno_data_sections, false);
602 Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
603 OPT_fno_unique_section_names, true);
604
605 Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
606
607 Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
608
609 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
610 const Arg *A = Args.getLastArg(OPT_flto, OPT_flto_EQ);
611 Opts.EmitSummaryIndex = A && A->containsValue("thin");
612 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
613 if (IK != IK_LLVM_IR)
614 Diags.Report(diag::err_drv_argument_only_allowed_with)
615 << A->getAsString(Args) << "-x ir";
616 Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
617 }
618
619 Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
620
621 Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive);
622 Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
623 Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
624
625 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
626 Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
627
628 Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
629 Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
630 Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
631 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
632 Opts.CoverageFile = Args.getLastArgValue(OPT_coverage_file);
633 Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
634 Opts.CoverageNoFunctionNamesInData =
635 Args.hasArg(OPT_coverage_no_function_names_in_data);
636 Opts.CoverageExitBlockBeforeBody =
637 Args.hasArg(OPT_coverage_exit_block_before_body);
638 if (Args.hasArg(OPT_coverage_version_EQ)) {
639 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
640 if (CoverageVersion.size() != 4) {
641 Diags.Report(diag::err_drv_invalid_value)
642 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
643 << CoverageVersion;
644 } else {
645 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
646 }
647 }
648 }
649 // Handle -fembed-bitcode option.
650 if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
651 StringRef Name = A->getValue();
652 unsigned Model = llvm::StringSwitch<unsigned>(Name)
653 .Case("off", CodeGenOptions::Embed_Off)
654 .Case("all", CodeGenOptions::Embed_All)
655 .Case("bitcode", CodeGenOptions::Embed_Bitcode)
656 .Case("marker", CodeGenOptions::Embed_Marker)
657 .Default(~0U);
658 if (Model == ~0U) {
659 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
660 Success = false;
661 } else
662 Opts.setEmbedBitcode(
663 static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
664 }
665 // FIXME: For backend options that are not yet recorded as function
666 // attributes in the IR, keep track of them so we can embed them in a
667 // separate data section and use them when building the bitcode.
668 if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
669 for (const auto &A : Args) {
670 // Do not encode output and input.
671 if (A->getOption().getID() == options::OPT_o ||
672 A->getOption().getID() == options::OPT_INPUT ||
673 A->getOption().getID() == options::OPT_x ||
674 A->getOption().getID() == options::OPT_fembed_bitcode ||
675 (A->getOption().getGroup().isValid() &&
676 A->getOption().getGroup().getID() == options::OPT_W_Group))
677 continue;
678 ArgStringList ASL;
679 A->render(Args, ASL);
680 for (const auto &arg : ASL) {
681 StringRef ArgStr(arg);
682 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
683 // using \00 to seperate each commandline options.
684 Opts.CmdArgs.push_back('\0');
685 }
686 }
687 }
688
689 Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
690 Opts.XRayInstrumentFunctions = Args.hasArg(OPT_fxray_instrument);
691 Opts.XRayInstructionThreshold =
692 getLastArgIntValue(Args, OPT_fxray_instruction_threshold_, 200, Diags);
693 Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
694 Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
695 Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections);
696 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
697 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
698 for (auto A : Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
699 unsigned LinkFlags = llvm::Linker::Flags::None;
700 if (A->getOption().matches(OPT_mlink_cuda_bitcode))
701 LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded |
702 llvm::Linker::Flags::InternalizeLinkedSymbols;
703 Opts.LinkBitcodeFiles.push_back(std::make_pair(LinkFlags, A->getValue()));
704 }
705 Opts.SanitizeCoverageType =
706 getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
707 Opts.SanitizeCoverageIndirectCalls =
708 Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
709 Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
710 Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
711 Opts.SanitizeCoverage8bitCounters =
712 Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
713 Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
714 Opts.SanitizeMemoryTrackOrigins =
715 getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
716 Opts.SanitizeMemoryUseAfterDtor =
717 Args.hasArg(OPT_fsanitize_memory_use_after_dtor);
718 Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
719 Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
720 Opts.SanitizeAddressUseAfterScope =
721 Args.hasArg(OPT_fsanitize_address_use_after_scope);
722 Opts.SSPBufferSize =
723 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
724 Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
725 if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
726 StringRef Val = A->getValue();
727 unsigned StackAlignment = Opts.StackAlignment;
728 Val.getAsInteger(10, StackAlignment);
729 Opts.StackAlignment = StackAlignment;
730 }
731
732 if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
733 StringRef Val = A->getValue();
734 unsigned StackProbeSize = Opts.StackProbeSize;
735 Val.getAsInteger(0, StackProbeSize);
736 Opts.StackProbeSize = StackProbeSize;
737 }
738
739 if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
740 StringRef Name = A->getValue();
741 unsigned Method = llvm::StringSwitch<unsigned>(Name)
742 .Case("legacy", CodeGenOptions::Legacy)
743 .Case("non-legacy", CodeGenOptions::NonLegacy)
744 .Case("mixed", CodeGenOptions::Mixed)
745 .Default(~0U);
746 if (Method == ~0U) {
747 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
748 Success = false;
749 } else {
750 Opts.setObjCDispatchMethod(
751 static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
752 }
753 }
754
755 Opts.EmulatedTLS =
756 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
757
758 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
759 StringRef Name = A->getValue();
760 unsigned Model = llvm::StringSwitch<unsigned>(Name)
761 .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
762 .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
763 .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
764 .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
765 .Default(~0U);
766 if (Model == ~0U) {
767 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
768 Success = false;
769 } else {
770 Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
771 }
772 }
773
774 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
775 StringRef Val = A->getValue();
776 if (Val == "fast")
777 Opts.setFPContractMode(CodeGenOptions::FPC_Fast);
778 else if (Val == "on")
779 Opts.setFPContractMode(CodeGenOptions::FPC_On);
780 else if (Val == "off")
781 Opts.setFPContractMode(CodeGenOptions::FPC_Off);
782 else
783 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
784 }
785
786 if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
787 if (A->getOption().matches(OPT_fpcc_struct_return)) {
788 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
789 } else {
790 assert(A->getOption().matches(OPT_freg_struct_return));
791 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
792 }
793 }
794
795 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
796 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
797 bool NeedLocTracking = false;
798
799 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
800 Opts.OptimizationRemarkPattern =
801 GenerateOptimizationRemarkRegex(Diags, Args, A);
802 NeedLocTracking = true;
803 }
804
805 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
806 Opts.OptimizationRemarkMissedPattern =
807 GenerateOptimizationRemarkRegex(Diags, Args, A);
808 NeedLocTracking = true;
809 }
810
811 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
812 Opts.OptimizationRemarkAnalysisPattern =
813 GenerateOptimizationRemarkRegex(Diags, Args, A);
814 NeedLocTracking = true;
815 }
816
817 // If the user requested to use a sample profile for PGO, then the
818 // backend will need to track source location information so the profile
819 // can be incorporated into the IR.
820 if (!Opts.SampleProfileFile.empty())
821 NeedLocTracking = true;
822
823 // If the user requested a flag that requires source locations available in
824 // the backend, make sure that the backend tracks source location information.
825 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
826 Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
827
828 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
829
830 // Parse -fsanitize-recover= arguments.
831 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
832 parseSanitizerKinds("-fsanitize-recover=",
833 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
834 Opts.SanitizeRecover);
835 parseSanitizerKinds("-fsanitize-trap=",
836 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
837 Opts.SanitizeTrap);
838
839 Opts.CudaGpuBinaryFileNames =
840 Args.getAllArgValues(OPT_fcuda_include_gpubinary);
841
842 Opts.Backchain = Args.hasArg(OPT_mbackchain);
843
844 Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
845 Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
846
847 return Success;
848 }
849
ParseDependencyOutputArgs(DependencyOutputOptions & Opts,ArgList & Args)850 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
851 ArgList &Args) {
852 using namespace options;
853 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
854 Opts.Targets = Args.getAllArgValues(OPT_MT);
855 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
856 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
857 Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
858 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
859 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
860 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
861 Opts.PrintShowIncludes = Args.hasArg(OPT_show_includes);
862 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
863 Opts.ModuleDependencyOutputDir =
864 Args.getLastArgValue(OPT_module_dependency_dir);
865 if (Args.hasArg(OPT_MV))
866 Opts.OutputFormat = DependencyOutputFormat::NMake;
867 // Add sanitizer blacklists as extra dependencies.
868 // They won't be discovered by the regular preprocessor, so
869 // we let make / ninja to know about this implicit dependency.
870 Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
871 auto ModuleFiles = Args.getAllArgValues(OPT_fmodule_file);
872 Opts.ExtraDeps.insert(Opts.ExtraDeps.end(), ModuleFiles.begin(),
873 ModuleFiles.end());
874 }
875
parseShowColorsArgs(const ArgList & Args,bool DefaultColor)876 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
877 // Color diagnostics default to auto ("on" if terminal supports) in the driver
878 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
879 // Support both clang's -f[no-]color-diagnostics and gcc's
880 // -f[no-]diagnostics-colors[=never|always|auto].
881 enum {
882 Colors_On,
883 Colors_Off,
884 Colors_Auto
885 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
886 for (Arg *A : Args) {
887 const Option &O = A->getOption();
888 if (!O.matches(options::OPT_fcolor_diagnostics) &&
889 !O.matches(options::OPT_fdiagnostics_color) &&
890 !O.matches(options::OPT_fno_color_diagnostics) &&
891 !O.matches(options::OPT_fno_diagnostics_color) &&
892 !O.matches(options::OPT_fdiagnostics_color_EQ))
893 continue;
894
895 if (O.matches(options::OPT_fcolor_diagnostics) ||
896 O.matches(options::OPT_fdiagnostics_color)) {
897 ShowColors = Colors_On;
898 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
899 O.matches(options::OPT_fno_diagnostics_color)) {
900 ShowColors = Colors_Off;
901 } else {
902 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
903 StringRef Value(A->getValue());
904 if (Value == "always")
905 ShowColors = Colors_On;
906 else if (Value == "never")
907 ShowColors = Colors_Off;
908 else if (Value == "auto")
909 ShowColors = Colors_Auto;
910 }
911 }
912 if (ShowColors == Colors_On ||
913 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
914 return true;
915 return false;
916 }
917
ParseDiagnosticArgs(DiagnosticOptions & Opts,ArgList & Args,DiagnosticsEngine * Diags,bool DefaultDiagColor)918 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
919 DiagnosticsEngine *Diags,
920 bool DefaultDiagColor) {
921 using namespace options;
922 bool Success = true;
923
924 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
925 if (Arg *A =
926 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
927 Opts.DiagnosticSerializationFile = A->getValue();
928 Opts.IgnoreWarnings = Args.hasArg(OPT_w);
929 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
930 Opts.Pedantic = Args.hasArg(OPT_pedantic);
931 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
932 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
933 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
934 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
935 OPT_fno_show_column,
936 /*Default=*/true);
937 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
938 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
939 Opts.ShowOptionNames = Args.hasArg(OPT_fdiagnostics_show_option);
940
941 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
942
943 // Default behavior is to not to show note include stacks.
944 Opts.ShowNoteIncludeStack = false;
945 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
946 OPT_fno_diagnostics_show_note_include_stack))
947 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
948 Opts.ShowNoteIncludeStack = true;
949
950 StringRef ShowOverloads =
951 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
952 if (ShowOverloads == "best")
953 Opts.setShowOverloads(Ovl_Best);
954 else if (ShowOverloads == "all")
955 Opts.setShowOverloads(Ovl_All);
956 else {
957 Success = false;
958 if (Diags)
959 Diags->Report(diag::err_drv_invalid_value)
960 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
961 << ShowOverloads;
962 }
963
964 StringRef ShowCategory =
965 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
966 if (ShowCategory == "none")
967 Opts.ShowCategories = 0;
968 else if (ShowCategory == "id")
969 Opts.ShowCategories = 1;
970 else if (ShowCategory == "name")
971 Opts.ShowCategories = 2;
972 else {
973 Success = false;
974 if (Diags)
975 Diags->Report(diag::err_drv_invalid_value)
976 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
977 << ShowCategory;
978 }
979
980 StringRef Format =
981 Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
982 if (Format == "clang")
983 Opts.setFormat(DiagnosticOptions::Clang);
984 else if (Format == "msvc")
985 Opts.setFormat(DiagnosticOptions::MSVC);
986 else if (Format == "msvc-fallback") {
987 Opts.setFormat(DiagnosticOptions::MSVC);
988 Opts.CLFallbackMode = true;
989 } else if (Format == "vi")
990 Opts.setFormat(DiagnosticOptions::Vi);
991 else {
992 Success = false;
993 if (Diags)
994 Diags->Report(diag::err_drv_invalid_value)
995 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
996 << Format;
997 }
998
999 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1000 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1001 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
1002 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify);
1003 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1004 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1005 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1006 Diags, DiagMask);
1007 if (Args.hasArg(OPT_verify_ignore_unexpected))
1008 DiagMask = DiagnosticLevelMask::All;
1009 Opts.setVerifyIgnoreUnexpected(DiagMask);
1010 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1011 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1012 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1013 Opts.MacroBacktraceLimit =
1014 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
1015 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
1016 Opts.TemplateBacktraceLimit = getLastArgIntValue(
1017 Args, OPT_ftemplate_backtrace_limit,
1018 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1019 Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1020 Args, OPT_fconstexpr_backtrace_limit,
1021 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
1022 Opts.SpellCheckingLimit = getLastArgIntValue(
1023 Args, OPT_fspell_checking_limit,
1024 DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
1025 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
1026 DiagnosticOptions::DefaultTabStop, Diags);
1027 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1028 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1029 if (Diags)
1030 Diags->Report(diag::warn_ignoring_ftabstop_value)
1031 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1032 }
1033 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
1034 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1035 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1036
1037 return Success;
1038 }
1039
ParseFileSystemArgs(FileSystemOptions & Opts,ArgList & Args)1040 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1041 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1042 }
1043
1044 /// Parse the argument to the -ftest-module-file-extension
1045 /// command-line argument.
1046 ///
1047 /// \returns true on error, false on success.
parseTestModuleFileExtensionArg(StringRef Arg,std::string & BlockName,unsigned & MajorVersion,unsigned & MinorVersion,bool & Hashed,std::string & UserInfo)1048 static bool parseTestModuleFileExtensionArg(StringRef Arg,
1049 std::string &BlockName,
1050 unsigned &MajorVersion,
1051 unsigned &MinorVersion,
1052 bool &Hashed,
1053 std::string &UserInfo) {
1054 SmallVector<StringRef, 5> Args;
1055 Arg.split(Args, ':', 5);
1056 if (Args.size() < 5)
1057 return true;
1058
1059 BlockName = Args[0];
1060 if (Args[1].getAsInteger(10, MajorVersion)) return true;
1061 if (Args[2].getAsInteger(10, MinorVersion)) return true;
1062 if (Args[3].getAsInteger(2, Hashed)) return true;
1063 if (Args.size() > 4)
1064 UserInfo = Args[4];
1065 return false;
1066 }
1067
ParseFrontendArgs(FrontendOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)1068 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1069 DiagnosticsEngine &Diags) {
1070 using namespace options;
1071 Opts.ProgramAction = frontend::ParseSyntaxOnly;
1072 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1073 switch (A->getOption().getID()) {
1074 default:
1075 llvm_unreachable("Invalid option in group!");
1076 case OPT_ast_list:
1077 Opts.ProgramAction = frontend::ASTDeclList; break;
1078 case OPT_ast_dump:
1079 case OPT_ast_dump_lookups:
1080 Opts.ProgramAction = frontend::ASTDump; break;
1081 case OPT_ast_print:
1082 Opts.ProgramAction = frontend::ASTPrint; break;
1083 case OPT_ast_view:
1084 Opts.ProgramAction = frontend::ASTView; break;
1085 case OPT_dump_raw_tokens:
1086 Opts.ProgramAction = frontend::DumpRawTokens; break;
1087 case OPT_dump_tokens:
1088 Opts.ProgramAction = frontend::DumpTokens; break;
1089 case OPT_S:
1090 Opts.ProgramAction = frontend::EmitAssembly; break;
1091 case OPT_emit_llvm_bc:
1092 Opts.ProgramAction = frontend::EmitBC; break;
1093 case OPT_emit_html:
1094 Opts.ProgramAction = frontend::EmitHTML; break;
1095 case OPT_emit_llvm:
1096 Opts.ProgramAction = frontend::EmitLLVM; break;
1097 case OPT_emit_llvm_only:
1098 Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1099 case OPT_emit_codegen_only:
1100 Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
1101 case OPT_emit_obj:
1102 Opts.ProgramAction = frontend::EmitObj; break;
1103 case OPT_fixit_EQ:
1104 Opts.FixItSuffix = A->getValue();
1105 // fall-through!
1106 case OPT_fixit:
1107 Opts.ProgramAction = frontend::FixIt; break;
1108 case OPT_emit_module:
1109 Opts.ProgramAction = frontend::GenerateModule; break;
1110 case OPT_emit_pch:
1111 Opts.ProgramAction = frontend::GeneratePCH; break;
1112 case OPT_emit_pth:
1113 Opts.ProgramAction = frontend::GeneratePTH; break;
1114 case OPT_init_only:
1115 Opts.ProgramAction = frontend::InitOnly; break;
1116 case OPT_fsyntax_only:
1117 Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
1118 case OPT_module_file_info:
1119 Opts.ProgramAction = frontend::ModuleFileInfo; break;
1120 case OPT_verify_pch:
1121 Opts.ProgramAction = frontend::VerifyPCH; break;
1122 case OPT_print_decl_contexts:
1123 Opts.ProgramAction = frontend::PrintDeclContext; break;
1124 case OPT_print_preamble:
1125 Opts.ProgramAction = frontend::PrintPreamble; break;
1126 case OPT_E:
1127 Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
1128 case OPT_rewrite_macros:
1129 Opts.ProgramAction = frontend::RewriteMacros; break;
1130 case OPT_rewrite_objc:
1131 Opts.ProgramAction = frontend::RewriteObjC; break;
1132 case OPT_rewrite_test:
1133 Opts.ProgramAction = frontend::RewriteTest; break;
1134 case OPT_analyze:
1135 Opts.ProgramAction = frontend::RunAnalysis; break;
1136 case OPT_migrate:
1137 Opts.ProgramAction = frontend::MigrateSource; break;
1138 case OPT_Eonly:
1139 Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1140 }
1141 }
1142
1143 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1144 Opts.Plugins.emplace_back(A->getValue(0));
1145 Opts.ProgramAction = frontend::PluginAction;
1146 Opts.ActionName = A->getValue();
1147 }
1148 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1149 for (const Arg *AA : Args.filtered(OPT_plugin_arg))
1150 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1151
1152 for (const std::string &Arg :
1153 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1154 std::string BlockName;
1155 unsigned MajorVersion;
1156 unsigned MinorVersion;
1157 bool Hashed;
1158 std::string UserInfo;
1159 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1160 MinorVersion, Hashed, UserInfo)) {
1161 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1162
1163 continue;
1164 }
1165
1166 // Add the testing module file extension.
1167 Opts.ModuleFileExtensions.push_back(
1168 new TestModuleFileExtension(BlockName, MajorVersion, MinorVersion,
1169 Hashed, UserInfo));
1170 }
1171
1172 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1173 Opts.CodeCompletionAt =
1174 ParsedSourceLocation::FromString(A->getValue());
1175 if (Opts.CodeCompletionAt.FileName.empty())
1176 Diags.Report(diag::err_drv_invalid_value)
1177 << A->getAsString(Args) << A->getValue();
1178 }
1179 Opts.DisableFree = Args.hasArg(OPT_disable_free);
1180
1181 Opts.OutputFile = Args.getLastArgValue(OPT_o);
1182 Opts.Plugins = Args.getAllArgValues(OPT_load);
1183 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1184 Opts.ShowHelp = Args.hasArg(OPT_help);
1185 Opts.ShowStats = Args.hasArg(OPT_print_stats);
1186 Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1187 Opts.ShowVersion = Args.hasArg(OPT_version);
1188 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1189 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1190 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1191 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1192 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1193 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1194 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
1195 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
1196 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
1197 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
1198 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
1199 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1200 Opts.ModuleFiles = Args.getAllArgValues(OPT_fmodule_file);
1201 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1202 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
1203 Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
1204
1205 Opts.CodeCompleteOpts.IncludeMacros
1206 = Args.hasArg(OPT_code_completion_macros);
1207 Opts.CodeCompleteOpts.IncludeCodePatterns
1208 = Args.hasArg(OPT_code_completion_patterns);
1209 Opts.CodeCompleteOpts.IncludeGlobals
1210 = !Args.hasArg(OPT_no_code_completion_globals);
1211 Opts.CodeCompleteOpts.IncludeBriefComments
1212 = Args.hasArg(OPT_code_completion_brief_comments);
1213
1214 Opts.OverrideRecordLayoutsFile
1215 = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
1216 Opts.AuxTriple =
1217 llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple));
1218 Opts.FindPchSource = Args.getLastArgValue(OPT_find_pch_source_EQ);
1219
1220 if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1221 OPT_arcmt_modify,
1222 OPT_arcmt_migrate)) {
1223 switch (A->getOption().getID()) {
1224 default:
1225 llvm_unreachable("missed a case");
1226 case OPT_arcmt_check:
1227 Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1228 break;
1229 case OPT_arcmt_modify:
1230 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1231 break;
1232 case OPT_arcmt_migrate:
1233 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1234 break;
1235 }
1236 }
1237 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
1238 Opts.ARCMTMigrateReportOut
1239 = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1240 Opts.ARCMTMigrateEmitARCErrors
1241 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1242
1243 if (Args.hasArg(OPT_objcmt_migrate_literals))
1244 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1245 if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1246 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
1247 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1248 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
1249 if (Args.hasArg(OPT_objcmt_migrate_property))
1250 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
1251 if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1252 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
1253 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1254 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
1255 if (Args.hasArg(OPT_objcmt_migrate_annotation))
1256 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
1257 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1258 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
1259 if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1260 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
1261 if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1262 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
1263 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1264 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
1265 if (Args.hasArg(OPT_objcmt_atomic_property))
1266 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
1267 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1268 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
1269 if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1270 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
1271 if (Args.hasArg(OPT_objcmt_migrate_all))
1272 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
1273
1274 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
1275
1276 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1277 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1278 Diags.Report(diag::err_drv_argument_not_allowed_with)
1279 << "ARC migration" << "ObjC migration";
1280 }
1281
1282 InputKind DashX = IK_None;
1283 if (const Arg *A = Args.getLastArg(OPT_x)) {
1284 DashX = llvm::StringSwitch<InputKind>(A->getValue())
1285 .Case("c", IK_C)
1286 .Case("cl", IK_OpenCL)
1287 .Case("cuda", IK_CUDA)
1288 .Case("c++", IK_CXX)
1289 .Case("objective-c", IK_ObjC)
1290 .Case("objective-c++", IK_ObjCXX)
1291 .Case("cpp-output", IK_PreprocessedC)
1292 .Case("assembler-with-cpp", IK_Asm)
1293 .Case("c++-cpp-output", IK_PreprocessedCXX)
1294 .Case("cuda-cpp-output", IK_PreprocessedCuda)
1295 .Case("objective-c-cpp-output", IK_PreprocessedObjC)
1296 .Case("objc-cpp-output", IK_PreprocessedObjC)
1297 .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX)
1298 .Case("objc++-cpp-output", IK_PreprocessedObjCXX)
1299 .Case("c-header", IK_C)
1300 .Case("cl-header", IK_OpenCL)
1301 .Case("objective-c-header", IK_ObjC)
1302 .Case("c++-header", IK_CXX)
1303 .Case("objective-c++-header", IK_ObjCXX)
1304 .Cases("ast", "pcm", IK_AST)
1305 .Case("ir", IK_LLVM_IR)
1306 .Case("renderscript", IK_RenderScript)
1307 .Default(IK_None);
1308 if (DashX == IK_None)
1309 Diags.Report(diag::err_drv_invalid_value)
1310 << A->getAsString(Args) << A->getValue();
1311 }
1312
1313 // '-' is the default input if none is given.
1314 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1315 Opts.Inputs.clear();
1316 if (Inputs.empty())
1317 Inputs.push_back("-");
1318 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1319 InputKind IK = DashX;
1320 if (IK == IK_None) {
1321 IK = FrontendOptions::getInputKindForExtension(
1322 StringRef(Inputs[i]).rsplit('.').second);
1323 // FIXME: Remove this hack.
1324 if (i == 0)
1325 DashX = IK;
1326 }
1327 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
1328 }
1329
1330 return DashX;
1331 }
1332
GetResourcesPath(const char * Argv0,void * MainAddr)1333 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1334 void *MainAddr) {
1335 std::string ClangExecutable =
1336 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1337 StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
1338
1339 // Compute the path to the resource directory.
1340 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1341 SmallString<128> P(Dir);
1342 if (ClangResourceDir != "")
1343 llvm::sys::path::append(P, ClangResourceDir);
1344 else
1345 llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX,
1346 "clang", CLANG_VERSION_STRING);
1347
1348 return P.str();
1349 }
1350
ParseHeaderSearchArgs(HeaderSearchOptions & Opts,ArgList & Args)1351 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args) {
1352 using namespace options;
1353 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
1354 Opts.Verbose = Args.hasArg(OPT_v);
1355 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
1356 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
1357 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
1358 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1359 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1360 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
1361 Opts.ModuleCachePath = Args.getLastArgValue(OPT_fmodules_cache_path);
1362 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
1363 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
1364 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
1365 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
1366 Opts.ModuleCachePruneInterval =
1367 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1368 Opts.ModuleCachePruneAfter =
1369 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
1370 Opts.ModulesValidateOncePerBuildSession =
1371 Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1372 Opts.BuildSessionTimestamp =
1373 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
1374 Opts.ModulesValidateSystemHeaders =
1375 Args.hasArg(OPT_fmodules_validate_system_headers);
1376 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1377 Opts.ModuleFormat = A->getValue();
1378
1379 for (const Arg *A : Args.filtered(OPT_fmodules_ignore_macro)) {
1380 StringRef MacroDef = A->getValue();
1381 Opts.ModulesIgnoreMacros.insert(MacroDef.split('=').first);
1382 }
1383
1384 // Add -I..., -F..., and -index-header-map options in order.
1385 bool IsIndexHeaderMap = false;
1386 bool IsSysrootSpecified =
1387 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
1388 for (const Arg *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
1389 if (A->getOption().matches(OPT_index_header_map)) {
1390 // -index-header-map applies to the next -I or -F.
1391 IsIndexHeaderMap = true;
1392 continue;
1393 }
1394
1395 frontend::IncludeDirGroup Group =
1396 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1397
1398 bool IsFramework = A->getOption().matches(OPT_F);
1399 std::string Path = A->getValue();
1400
1401 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1402 SmallString<32> Buffer;
1403 llvm::sys::path::append(Buffer, Opts.Sysroot,
1404 llvm::StringRef(A->getValue()).substr(1));
1405 Path = Buffer.str();
1406 }
1407
1408 Opts.AddPath(Path.c_str(), Group, IsFramework,
1409 /*IgnoreSysroot*/ true);
1410 IsIndexHeaderMap = false;
1411 }
1412
1413 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
1414 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1415 for (const Arg *A :
1416 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
1417 if (A->getOption().matches(OPT_iprefix))
1418 Prefix = A->getValue();
1419 else if (A->getOption().matches(OPT_iwithprefix))
1420 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
1421 else
1422 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
1423 }
1424
1425 for (const Arg *A : Args.filtered(OPT_idirafter))
1426 Opts.AddPath(A->getValue(), frontend::After, false, true);
1427 for (const Arg *A : Args.filtered(OPT_iquote))
1428 Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
1429 for (const Arg *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
1430 Opts.AddPath(A->getValue(), frontend::System, false,
1431 !A->getOption().matches(OPT_iwithsysroot));
1432 for (const Arg *A : Args.filtered(OPT_iframework))
1433 Opts.AddPath(A->getValue(), frontend::System, true, true);
1434
1435 // Add the paths for the various language specific isystem flags.
1436 for (const Arg *A : Args.filtered(OPT_c_isystem))
1437 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
1438 for (const Arg *A : Args.filtered(OPT_cxx_isystem))
1439 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
1440 for (const Arg *A : Args.filtered(OPT_objc_isystem))
1441 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
1442 for (const Arg *A : Args.filtered(OPT_objcxx_isystem))
1443 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1444
1445 // Add the internal paths from a driver that detects standard include paths.
1446 for (const Arg *A :
1447 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1448 frontend::IncludeDirGroup Group = frontend::System;
1449 if (A->getOption().matches(OPT_internal_externc_isystem))
1450 Group = frontend::ExternCSystem;
1451 Opts.AddPath(A->getValue(), Group, false, true);
1452 }
1453
1454 // Add the path prefixes which are implicitly treated as being system headers.
1455 for (const Arg *A :
1456 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1457 Opts.AddSystemHeaderPrefix(
1458 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1459
1460 for (const Arg *A : Args.filtered(OPT_ivfsoverlay))
1461 Opts.AddVFSOverlayFile(A->getValue());
1462 }
1463
isOpenCL(LangStandard::Kind LangStd)1464 bool isOpenCL(LangStandard::Kind LangStd) {
1465 return LangStd == LangStandard::lang_opencl ||
1466 LangStd == LangStandard::lang_opencl11 ||
1467 LangStd == LangStandard::lang_opencl12 ||
1468 LangStd == LangStandard::lang_opencl20;
1469 }
1470
setLangDefaults(LangOptions & Opts,InputKind IK,const llvm::Triple & T,PreprocessorOptions & PPOpts,LangStandard::Kind LangStd)1471 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1472 const llvm::Triple &T,
1473 PreprocessorOptions &PPOpts,
1474 LangStandard::Kind LangStd) {
1475 // Set some properties which depend solely on the input kind; it would be nice
1476 // to move these to the language standard, and have the driver resolve the
1477 // input kind + language standard.
1478 if (IK == IK_Asm) {
1479 Opts.AsmPreprocessor = 1;
1480 } else if (IK == IK_ObjC ||
1481 IK == IK_ObjCXX ||
1482 IK == IK_PreprocessedObjC ||
1483 IK == IK_PreprocessedObjCXX) {
1484 Opts.ObjC1 = Opts.ObjC2 = 1;
1485 }
1486
1487 if (LangStd == LangStandard::lang_unspecified) {
1488 // Based on the base language, pick one.
1489 switch (IK) {
1490 case IK_None:
1491 case IK_AST:
1492 case IK_LLVM_IR:
1493 llvm_unreachable("Invalid input kind!");
1494 case IK_OpenCL:
1495 LangStd = LangStandard::lang_opencl;
1496 break;
1497 case IK_CUDA:
1498 case IK_PreprocessedCuda:
1499 LangStd = LangStandard::lang_cuda;
1500 break;
1501 case IK_Asm:
1502 case IK_C:
1503 case IK_PreprocessedC:
1504 case IK_ObjC:
1505 case IK_PreprocessedObjC:
1506 // The PS4 uses C99 as the default C standard.
1507 if (T.isPS4())
1508 LangStd = LangStandard::lang_gnu99;
1509 else
1510 LangStd = LangStandard::lang_gnu11;
1511 break;
1512 case IK_CXX:
1513 case IK_PreprocessedCXX:
1514 case IK_ObjCXX:
1515 case IK_PreprocessedObjCXX:
1516 LangStd = LangStandard::lang_gnucxx98;
1517 break;
1518 case IK_RenderScript:
1519 LangStd = LangStandard::lang_c99;
1520 break;
1521 }
1522 }
1523
1524 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1525 Opts.LineComment = Std.hasLineComments();
1526 Opts.C99 = Std.isC99();
1527 Opts.C11 = Std.isC11();
1528 Opts.CPlusPlus = Std.isCPlusPlus();
1529 Opts.CPlusPlus11 = Std.isCPlusPlus11();
1530 Opts.CPlusPlus14 = Std.isCPlusPlus14();
1531 Opts.CPlusPlus1z = Std.isCPlusPlus1z();
1532 Opts.Digraphs = Std.hasDigraphs();
1533 Opts.GNUMode = Std.isGNUMode();
1534 Opts.GNUInline = Std.isC89();
1535 Opts.HexFloats = Std.hasHexFloats();
1536 Opts.ImplicitInt = Std.hasImplicitInt();
1537
1538 // Set OpenCL Version.
1539 Opts.OpenCL = isOpenCL(LangStd) || IK == IK_OpenCL;
1540 if (LangStd == LangStandard::lang_opencl)
1541 Opts.OpenCLVersion = 100;
1542 else if (LangStd == LangStandard::lang_opencl11)
1543 Opts.OpenCLVersion = 110;
1544 else if (LangStd == LangStandard::lang_opencl12)
1545 Opts.OpenCLVersion = 120;
1546 else if (LangStd == LangStandard::lang_opencl20)
1547 Opts.OpenCLVersion = 200;
1548
1549 // OpenCL has some additional defaults.
1550 if (Opts.OpenCL) {
1551 Opts.AltiVec = 0;
1552 Opts.ZVector = 0;
1553 Opts.CXXOperatorNames = 1;
1554 Opts.LaxVectorConversions = 0;
1555 Opts.DefaultFPContract = 1;
1556 Opts.NativeHalfType = 1;
1557 Opts.NativeHalfArgsAndReturns = 1;
1558 // Include default header file for OpenCL.
1559 if (Opts.IncludeDefaultHeader) {
1560 PPOpts.Includes.push_back("opencl-c.h");
1561 }
1562 }
1563
1564 Opts.CUDA = IK == IK_CUDA || IK == IK_PreprocessedCuda ||
1565 LangStd == LangStandard::lang_cuda;
1566
1567 Opts.RenderScript = IK == IK_RenderScript;
1568 if (Opts.RenderScript) {
1569 Opts.NativeHalfType = 1;
1570 Opts.NativeHalfArgsAndReturns = 1;
1571 }
1572
1573 // OpenCL and C++ both have bool, true, false keywords.
1574 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1575
1576 // OpenCL has half keyword
1577 Opts.Half = Opts.OpenCL;
1578
1579 // C++ has wchar_t keyword.
1580 Opts.WChar = Opts.CPlusPlus;
1581
1582 Opts.GNUKeywords = Opts.GNUMode;
1583 Opts.CXXOperatorNames = Opts.CPlusPlus;
1584
1585 Opts.DollarIdents = !Opts.AsmPreprocessor;
1586 }
1587
1588 /// Attempt to parse a visibility value out of the given argument.
parseVisibility(Arg * arg,ArgList & args,DiagnosticsEngine & diags)1589 static Visibility parseVisibility(Arg *arg, ArgList &args,
1590 DiagnosticsEngine &diags) {
1591 StringRef value = arg->getValue();
1592 if (value == "default") {
1593 return DefaultVisibility;
1594 } else if (value == "hidden" || value == "internal") {
1595 return HiddenVisibility;
1596 } else if (value == "protected") {
1597 // FIXME: diagnose if target does not support protected visibility
1598 return ProtectedVisibility;
1599 }
1600
1601 diags.Report(diag::err_drv_invalid_value)
1602 << arg->getAsString(args) << value;
1603 return DefaultVisibility;
1604 }
1605
ParseLangArgs(LangOptions & Opts,ArgList & Args,InputKind IK,const TargetOptions & TargetOpts,PreprocessorOptions & PPOpts,DiagnosticsEngine & Diags)1606 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
1607 const TargetOptions &TargetOpts,
1608 PreprocessorOptions &PPOpts,
1609 DiagnosticsEngine &Diags) {
1610 // FIXME: Cleanup per-file based stuff.
1611 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
1612 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
1613 LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1614 #define LANGSTANDARD(id, name, desc, features) \
1615 .Case(name, LangStandard::lang_##id)
1616 #define LANGSTANDARD_ALIAS(id, alias) \
1617 .Case(alias, LangStandard::lang_##id)
1618 #include "clang/Frontend/LangStandards.def"
1619 .Default(LangStandard::lang_unspecified);
1620 if (LangStd == LangStandard::lang_unspecified)
1621 Diags.Report(diag::err_drv_invalid_value)
1622 << A->getAsString(Args) << A->getValue();
1623 else {
1624 // Valid standard, check to make sure language and standard are
1625 // compatible.
1626 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1627 switch (IK) {
1628 case IK_C:
1629 case IK_ObjC:
1630 case IK_PreprocessedC:
1631 case IK_PreprocessedObjC:
1632 if (!(Std.isC89() || Std.isC99()))
1633 Diags.Report(diag::err_drv_argument_not_allowed_with)
1634 << A->getAsString(Args) << "C/ObjC";
1635 break;
1636 case IK_CXX:
1637 case IK_ObjCXX:
1638 case IK_PreprocessedCXX:
1639 case IK_PreprocessedObjCXX:
1640 if (!Std.isCPlusPlus())
1641 Diags.Report(diag::err_drv_argument_not_allowed_with)
1642 << A->getAsString(Args) << "C++/ObjC++";
1643 break;
1644 case IK_OpenCL:
1645 if (!isOpenCL(LangStd))
1646 Diags.Report(diag::err_drv_argument_not_allowed_with)
1647 << A->getAsString(Args) << "OpenCL";
1648 break;
1649 case IK_CUDA:
1650 case IK_PreprocessedCuda:
1651 if (!Std.isCPlusPlus())
1652 Diags.Report(diag::err_drv_argument_not_allowed_with)
1653 << A->getAsString(Args) << "CUDA";
1654 break;
1655 default:
1656 break;
1657 }
1658 }
1659 }
1660
1661 // -cl-std only applies for OpenCL language standards.
1662 // Override the -std option in this case.
1663 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
1664 LangStandard::Kind OpenCLLangStd
1665 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1666 .Cases("cl", "CL", LangStandard::lang_opencl)
1667 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
1668 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
1669 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
1670 .Default(LangStandard::lang_unspecified);
1671
1672 if (OpenCLLangStd == LangStandard::lang_unspecified) {
1673 Diags.Report(diag::err_drv_invalid_value)
1674 << A->getAsString(Args) << A->getValue();
1675 }
1676 else
1677 LangStd = OpenCLLangStd;
1678 }
1679
1680 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
1681
1682 llvm::Triple T(TargetOpts.Triple);
1683 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
1684
1685 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
1686 // This option should be deprecated for CL > 1.0 because
1687 // this option was added for compatibility with OpenCL 1.0.
1688 if (Args.getLastArg(OPT_cl_strict_aliasing)
1689 && Opts.OpenCLVersion > 100) {
1690 std::string VerSpec = llvm::to_string(Opts.OpenCLVersion / 100) +
1691 std::string(".") +
1692 llvm::to_string((Opts.OpenCLVersion % 100) / 10);
1693 Diags.Report(diag::warn_option_invalid_ocl_version)
1694 << VerSpec << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
1695 }
1696
1697 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
1698 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
1699 // while a subset (the non-C++ GNU keywords) is provided by GCC's
1700 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
1701 // name, as it doesn't seem a useful distinction.
1702 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
1703 Opts.GNUKeywords);
1704
1705 if (Args.hasArg(OPT_fno_operator_names))
1706 Opts.CXXOperatorNames = 0;
1707
1708 if (Args.hasArg(OPT_fcuda_is_device))
1709 Opts.CUDAIsDevice = 1;
1710
1711 if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
1712 Opts.CUDAAllowVariadicFunctions = 1;
1713
1714 if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
1715 Opts.CUDAHostDeviceConstexpr = 0;
1716
1717 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_flush_denormals_to_zero))
1718 Opts.CUDADeviceFlushDenormalsToZero = 1;
1719
1720 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
1721 Opts.CUDADeviceApproxTranscendentals = 1;
1722
1723 if (Opts.ObjC1) {
1724 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
1725 StringRef value = arg->getValue();
1726 if (Opts.ObjCRuntime.tryParse(value))
1727 Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
1728 }
1729
1730 if (Args.hasArg(OPT_fobjc_gc_only))
1731 Opts.setGC(LangOptions::GCOnly);
1732 else if (Args.hasArg(OPT_fobjc_gc))
1733 Opts.setGC(LangOptions::HybridGC);
1734 else if (Args.hasArg(OPT_fobjc_arc)) {
1735 Opts.ObjCAutoRefCount = 1;
1736 if (!Opts.ObjCRuntime.allowsARC())
1737 Diags.Report(diag::err_arc_unsupported_on_runtime);
1738 }
1739
1740 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
1741 // whether the feature is actually enabled. This is predominantly
1742 // determined by -fobjc-runtime, but we allow it to be overridden
1743 // from the command line for testing purposes.
1744 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
1745 Opts.ObjCWeakRuntime = 1;
1746 else
1747 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
1748
1749 // ObjCWeak determines whether __weak is actually enabled.
1750 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
1751 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
1752 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
1753 assert(!Opts.ObjCWeak);
1754 } else if (Opts.getGC() != LangOptions::NonGC) {
1755 Diags.Report(diag::err_objc_weak_with_gc);
1756 } else if (!Opts.ObjCWeakRuntime) {
1757 Diags.Report(diag::err_objc_weak_unsupported);
1758 } else {
1759 Opts.ObjCWeak = 1;
1760 }
1761 } else if (Opts.ObjCAutoRefCount) {
1762 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
1763 }
1764
1765 if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
1766 Opts.ObjCInferRelatedResultType = 0;
1767
1768 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
1769 Opts.ObjCSubscriptingLegacyRuntime =
1770 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
1771 }
1772
1773 if (Args.hasArg(OPT_fgnu89_inline)) {
1774 if (Opts.CPlusPlus)
1775 Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fgnu89-inline"
1776 << "C++/ObjC++";
1777 else
1778 Opts.GNUInline = 1;
1779 }
1780
1781 if (Args.hasArg(OPT_fapple_kext)) {
1782 if (!Opts.CPlusPlus)
1783 Diags.Report(diag::warn_c_kext);
1784 else
1785 Opts.AppleKext = 1;
1786 }
1787
1788 if (Args.hasArg(OPT_print_ivar_layout))
1789 Opts.ObjCGCBitmapPrint = 1;
1790 if (Args.hasArg(OPT_fno_constant_cfstrings))
1791 Opts.NoConstantCFStrings = 1;
1792
1793 if (Args.hasArg(OPT_faltivec))
1794 Opts.AltiVec = 1;
1795
1796 if (Args.hasArg(OPT_fzvector))
1797 Opts.ZVector = 1;
1798
1799 if (Args.hasArg(OPT_pthread))
1800 Opts.POSIXThreads = 1;
1801
1802 // The value-visibility mode defaults to "default".
1803 if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
1804 Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
1805 } else {
1806 Opts.setValueVisibilityMode(DefaultVisibility);
1807 }
1808
1809 // The type-visibility mode defaults to the value-visibility mode.
1810 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
1811 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
1812 } else {
1813 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
1814 }
1815
1816 if (Args.hasArg(OPT_fvisibility_inlines_hidden))
1817 Opts.InlineVisibilityHidden = 1;
1818
1819 if (Args.hasArg(OPT_ftrapv)) {
1820 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
1821 // Set the handler, if one is specified.
1822 Opts.OverflowHandler =
1823 Args.getLastArgValue(OPT_ftrapv_handler);
1824 }
1825 else if (Args.hasArg(OPT_fwrapv))
1826 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
1827
1828 Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
1829 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
1830 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
1831 Opts.MSCompatibilityVersion = 0;
1832 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
1833 VersionTuple VT;
1834 if (VT.tryParse(A->getValue()))
1835 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1836 << A->getValue();
1837 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
1838 VT.getMinor().getValueOr(0) * 100000 +
1839 VT.getSubminor().getValueOr(0);
1840 }
1841
1842 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
1843 // is specified, or -std is set to a conforming mode.
1844 // Trigraphs are disabled by default in c++1z onwards.
1845 Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus1z;
1846 Opts.Trigraphs =
1847 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
1848
1849 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
1850 OPT_fno_dollars_in_identifiers,
1851 Opts.DollarIdents);
1852 Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
1853 Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
1854 Opts.Borland = Args.hasArg(OPT_fborland_extensions);
1855 Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
1856 Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
1857 Opts.ConstStrings);
1858 if (Args.hasArg(OPT_fno_lax_vector_conversions))
1859 Opts.LaxVectorConversions = 0;
1860 if (Args.hasArg(OPT_fno_threadsafe_statics))
1861 Opts.ThreadsafeStatics = 0;
1862 Opts.Exceptions = Args.hasArg(OPT_fexceptions);
1863 Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
1864 Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
1865 Opts.SjLjExceptions = Args.hasArg(OPT_fsjlj_exceptions);
1866 Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
1867 Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
1868
1869 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
1870 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
1871 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
1872 && Opts.OpenCLVersion >= 200);
1873 Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
1874 Opts.Coroutines = Args.hasArg(OPT_fcoroutines);
1875 Opts.Modules = Args.hasArg(OPT_fmodules);
1876 Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
1877 Opts.ModulesDeclUse =
1878 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
1879 Opts.ModulesLocalVisibility =
1880 Args.hasArg(OPT_fmodules_local_submodule_visibility);
1881 Opts.ModulesSearchAll = Opts.Modules &&
1882 !Args.hasArg(OPT_fno_modules_search_all) &&
1883 Args.hasArg(OPT_fmodules_search_all);
1884 Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
1885 Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
1886 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
1887 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
1888 Opts.ShortWChar = Args.hasFlag(OPT_fshort_wchar, OPT_fno_short_wchar, false);
1889 Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
1890 Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
1891 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
1892 if (!Opts.NoBuiltin)
1893 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
1894 Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
1895 Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
1896 Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
1897 Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
1898 Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
1899 Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
1900 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
1901 Opts.InstantiationDepth =
1902 getLastArgIntValue(Args, OPT_ftemplate_depth, 256, Diags);
1903 Opts.ArrowDepth =
1904 getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
1905 Opts.ConstexprCallDepth =
1906 getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
1907 Opts.ConstexprStepLimit =
1908 getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
1909 Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
1910 Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
1911 Opts.NumLargeByValueCopy =
1912 getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
1913 Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
1914 Opts.ObjCConstantStringClass =
1915 Args.getLastArgValue(OPT_fconstant_string_class);
1916 Opts.ObjCDefaultSynthProperties =
1917 !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
1918 Opts.EncodeExtendedBlockSig =
1919 Args.hasArg(OPT_fencode_extended_block_signature);
1920 Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
1921 Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
1922 Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
1923 Opts.AlignDouble = Args.hasArg(OPT_malign_double);
1924 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
1925 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
1926 Opts.Static = Args.hasArg(OPT_static_define);
1927 Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
1928 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
1929 || Args.hasArg(OPT_fdump_record_layouts);
1930 Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
1931 Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
1932 Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
1933 Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
1934 Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
1935 Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
1936 Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
1937 Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
1938 Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
1939 Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
1940 Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
1941 Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
1942 Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name_EQ);
1943 Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
1944 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
1945 std::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end());
1946 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
1947 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
1948 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
1949 // is enabled.
1950 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
1951 | Opts.NativeHalfArgsAndReturns;
1952 Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
1953
1954 // __declspec is enabled by default for the PS4 by the driver, and also
1955 // enabled for Microsoft Extensions or Borland Extensions, here.
1956 //
1957 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
1958 // CUDA extension, however it is required for supporting cuda_builtin_vars.h,
1959 // which uses __declspec(property). Once that has been rewritten in terms of
1960 // something more generic, remove the Opts.CUDA term here.
1961 Opts.DeclSpecKeyword =
1962 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
1963 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
1964
1965 // For now, we only support local submodule visibility in C++ (because we
1966 // heavily depend on the ODR for merging redefinitions).
1967 if (Opts.ModulesLocalVisibility && !Opts.CPlusPlus)
1968 Diags.Report(diag::err_drv_argument_not_allowed_with)
1969 << "-fmodules-local-submodule-visibility" << "C";
1970
1971 if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
1972 switch (llvm::StringSwitch<unsigned>(A->getValue())
1973 .Case("target", LangOptions::ASMM_Target)
1974 .Case("no", LangOptions::ASMM_Off)
1975 .Case("yes", LangOptions::ASMM_On)
1976 .Default(255)) {
1977 default:
1978 Diags.Report(diag::err_drv_invalid_value)
1979 << "-faddress-space-map-mangling=" << A->getValue();
1980 break;
1981 case LangOptions::ASMM_Target:
1982 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
1983 break;
1984 case LangOptions::ASMM_On:
1985 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
1986 break;
1987 case LangOptions::ASMM_Off:
1988 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
1989 break;
1990 }
1991 }
1992
1993 if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
1994 LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
1995 llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
1996 A->getValue())
1997 .Case("single",
1998 LangOptions::PPTMK_FullGeneralitySingleInheritance)
1999 .Case("multiple",
2000 LangOptions::PPTMK_FullGeneralityMultipleInheritance)
2001 .Case("virtual",
2002 LangOptions::PPTMK_FullGeneralityVirtualInheritance)
2003 .Default(LangOptions::PPTMK_BestCase);
2004 if (InheritanceModel == LangOptions::PPTMK_BestCase)
2005 Diags.Report(diag::err_drv_invalid_value)
2006 << "-fms-memptr-rep=" << A->getValue();
2007
2008 Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2009 }
2010
2011 // Check for MS default calling conventions being specified.
2012 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2013 LangOptions::DefaultCallingConvention DefaultCC =
2014 llvm::StringSwitch<LangOptions::DefaultCallingConvention>(
2015 A->getValue())
2016 .Case("cdecl", LangOptions::DCC_CDecl)
2017 .Case("fastcall", LangOptions::DCC_FastCall)
2018 .Case("stdcall", LangOptions::DCC_StdCall)
2019 .Case("vectorcall", LangOptions::DCC_VectorCall)
2020 .Default(LangOptions::DCC_None);
2021 if (DefaultCC == LangOptions::DCC_None)
2022 Diags.Report(diag::err_drv_invalid_value)
2023 << "-fdefault-calling-conv=" << A->getValue();
2024
2025 llvm::Triple T(TargetOpts.Triple);
2026 llvm::Triple::ArchType Arch = T.getArch();
2027 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
2028 DefaultCC == LangOptions::DCC_StdCall) &&
2029 Arch != llvm::Triple::x86;
2030 emitError |= DefaultCC == LangOptions::DCC_VectorCall &&
2031 !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2032 if (emitError)
2033 Diags.Report(diag::err_drv_argument_not_allowed_with)
2034 << A->getSpelling() << T.getTriple();
2035 else
2036 Opts.setDefaultCallingConv(DefaultCC);
2037 }
2038
2039 // -mrtd option
2040 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2041 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2042 Diags.Report(diag::err_drv_argument_not_allowed_with)
2043 << A->getSpelling() << "-fdefault-calling-conv";
2044 else {
2045 llvm::Triple T(TargetOpts.Triple);
2046 if (T.getArch() != llvm::Triple::x86)
2047 Diags.Report(diag::err_drv_argument_not_allowed_with)
2048 << A->getSpelling() << T.getTriple();
2049 else
2050 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2051 }
2052 }
2053
2054 // Check if -fopenmp is specified.
2055 Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 1 : 0;
2056 Opts.OpenMPUseTLS =
2057 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
2058 Opts.OpenMPIsDevice =
2059 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2060
2061 if (Opts.OpenMP) {
2062 int Version =
2063 getLastArgIntValue(Args, OPT_fopenmp_version_EQ, Opts.OpenMP, Diags);
2064 if (Version != 0)
2065 Opts.OpenMP = Version;
2066 // Provide diagnostic when a given target is not expected to be an OpenMP
2067 // device or host.
2068 if (!Opts.OpenMPIsDevice) {
2069 switch (T.getArch()) {
2070 default:
2071 break;
2072 // Add unsupported host targets here:
2073 case llvm::Triple::nvptx:
2074 case llvm::Triple::nvptx64:
2075 Diags.Report(clang::diag::err_drv_omp_host_target_not_supported)
2076 << TargetOpts.Triple;
2077 break;
2078 }
2079 }
2080 }
2081
2082 // Get the OpenMP target triples if any.
2083 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
2084
2085 for (unsigned i = 0; i < A->getNumValues(); ++i) {
2086 llvm::Triple TT(A->getValue(i));
2087
2088 if (TT.getArch() == llvm::Triple::UnknownArch)
2089 Diags.Report(clang::diag::err_drv_invalid_omp_target) << A->getValue(i);
2090 else
2091 Opts.OMPTargetTriples.push_back(TT);
2092 }
2093 }
2094
2095 // Get OpenMP host file path if any and report if a non existent file is
2096 // found
2097 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
2098 Opts.OMPHostIRFile = A->getValue();
2099 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
2100 Diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
2101 << Opts.OMPHostIRFile;
2102 }
2103
2104 // Record whether the __DEPRECATED define was requested.
2105 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2106 OPT_fno_deprecated_macro,
2107 Opts.Deprecated);
2108
2109 // FIXME: Eliminate this dependency.
2110 unsigned Opt = getOptimizationLevel(Args, IK, Diags),
2111 OptSize = getOptimizationLevelSize(Args);
2112 Opts.Optimize = Opt != 0;
2113 Opts.OptimizeSize = OptSize != 0;
2114
2115 // This is the __NO_INLINE__ define, which just depends on things like the
2116 // optimization level and -fno-inline, not actually whether the backend has
2117 // inlining enabled.
2118 Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline);
2119
2120 Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
2121 Args.hasArg(OPT_cl_fast_relaxed_math);
2122 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
2123 Args.hasArg(OPT_cl_finite_math_only) ||
2124 Args.hasArg(OPT_cl_fast_relaxed_math);
2125 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
2126 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
2127 Args.hasArg(OPT_cl_fast_relaxed_math);
2128
2129 Opts.RetainCommentsFromSystemHeaders =
2130 Args.hasArg(OPT_fretain_comments_from_system_headers);
2131
2132 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
2133 switch (SSP) {
2134 default:
2135 Diags.Report(diag::err_drv_invalid_value)
2136 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2137 break;
2138 case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2139 case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
2140 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
2141 case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
2142 }
2143
2144 // Parse -fsanitize= arguments.
2145 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2146 Diags, Opts.Sanitize);
2147 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
2148 Opts.SanitizeAddressFieldPadding =
2149 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
2150 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
2151 }
2152
ParsePreprocessorArgs(PreprocessorOptions & Opts,ArgList & Args,FileManager & FileMgr,DiagnosticsEngine & Diags)2153 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
2154 FileManager &FileMgr,
2155 DiagnosticsEngine &Diags) {
2156 using namespace options;
2157 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
2158 Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
2159 if (const Arg *A = Args.getLastArg(OPT_token_cache))
2160 Opts.TokenCache = A->getValue();
2161 else
2162 Opts.TokenCache = Opts.ImplicitPTHInclude;
2163 Opts.UsePredefines = !Args.hasArg(OPT_undef);
2164 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
2165 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
2166
2167 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
2168 for (const Arg *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
2169 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
2170
2171 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
2172 StringRef Value(A->getValue());
2173 size_t Comma = Value.find(',');
2174 unsigned Bytes = 0;
2175 unsigned EndOfLine = 0;
2176
2177 if (Comma == StringRef::npos ||
2178 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2179 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2180 Diags.Report(diag::err_drv_preamble_format);
2181 else {
2182 Opts.PrecompiledPreambleBytes.first = Bytes;
2183 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2184 }
2185 }
2186
2187 // Add macros from the command line.
2188 for (const Arg *A : Args.filtered(OPT_D, OPT_U)) {
2189 if (A->getOption().matches(OPT_D))
2190 Opts.addMacroDef(A->getValue());
2191 else
2192 Opts.addMacroUndef(A->getValue());
2193 }
2194
2195 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
2196
2197 // Add the ordered list of -includes.
2198 for (const Arg *A : Args.filtered(OPT_include))
2199 Opts.Includes.emplace_back(A->getValue());
2200
2201 for (const Arg *A : Args.filtered(OPT_chain_include))
2202 Opts.ChainedIncludes.emplace_back(A->getValue());
2203
2204 for (const Arg *A : Args.filtered(OPT_remap_file)) {
2205 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
2206
2207 if (Split.second.empty()) {
2208 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
2209 continue;
2210 }
2211
2212 Opts.addRemappedFile(Split.first, Split.second);
2213 }
2214
2215 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
2216 StringRef Name = A->getValue();
2217 unsigned Library = llvm::StringSwitch<unsigned>(Name)
2218 .Case("libc++", ARCXX_libcxx)
2219 .Case("libstdc++", ARCXX_libstdcxx)
2220 .Case("none", ARCXX_nolib)
2221 .Default(~0U);
2222 if (Library == ~0U)
2223 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2224 else
2225 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
2226 }
2227 }
2228
ParsePreprocessorOutputArgs(PreprocessorOutputOptions & Opts,ArgList & Args,frontend::ActionKind Action)2229 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
2230 ArgList &Args,
2231 frontend::ActionKind Action) {
2232 using namespace options;
2233
2234 switch (Action) {
2235 case frontend::ASTDeclList:
2236 case frontend::ASTDump:
2237 case frontend::ASTPrint:
2238 case frontend::ASTView:
2239 case frontend::EmitAssembly:
2240 case frontend::EmitBC:
2241 case frontend::EmitHTML:
2242 case frontend::EmitLLVM:
2243 case frontend::EmitLLVMOnly:
2244 case frontend::EmitCodeGenOnly:
2245 case frontend::EmitObj:
2246 case frontend::FixIt:
2247 case frontend::GenerateModule:
2248 case frontend::GeneratePCH:
2249 case frontend::GeneratePTH:
2250 case frontend::ParseSyntaxOnly:
2251 case frontend::ModuleFileInfo:
2252 case frontend::VerifyPCH:
2253 case frontend::PluginAction:
2254 case frontend::PrintDeclContext:
2255 case frontend::RewriteObjC:
2256 case frontend::RewriteTest:
2257 case frontend::RunAnalysis:
2258 case frontend::MigrateSource:
2259 Opts.ShowCPP = 0;
2260 break;
2261
2262 case frontend::DumpRawTokens:
2263 case frontend::DumpTokens:
2264 case frontend::InitOnly:
2265 case frontend::PrintPreamble:
2266 case frontend::PrintPreprocessedInput:
2267 case frontend::RewriteMacros:
2268 case frontend::RunPreprocessorOnly:
2269 Opts.ShowCPP = !Args.hasArg(OPT_dM);
2270 break;
2271 }
2272
2273 Opts.ShowComments = Args.hasArg(OPT_C);
2274 Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
2275 Opts.ShowMacroComments = Args.hasArg(OPT_CC);
2276 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
2277 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
2278 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
2279 }
2280
ParseTargetArgs(TargetOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)2281 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2282 DiagnosticsEngine &Diags) {
2283 using namespace options;
2284 Opts.ABI = Args.getLastArgValue(OPT_target_abi);
2285 if (Arg *A = Args.getLastArg(OPT_meabi)) {
2286 StringRef Value = A->getValue();
2287 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
2288 .Case("default", llvm::EABI::Default)
2289 .Case("4", llvm::EABI::EABI4)
2290 .Case("5", llvm::EABI::EABI5)
2291 .Case("gnu", llvm::EABI::GNU)
2292 .Default(llvm::EABI::Unknown);
2293 if (EABIVersion == llvm::EABI::Unknown)
2294 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2295 << Value;
2296 else
2297 Opts.EABIVersion = Value;
2298 }
2299 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
2300 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
2301 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
2302 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
2303 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
2304 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
2305 // Use the default target triple if unspecified.
2306 if (Opts.Triple.empty())
2307 Opts.Triple = llvm::sys::getDefaultTargetTriple();
2308 }
2309
CreateFromArgs(CompilerInvocation & Res,const char * const * ArgBegin,const char * const * ArgEnd,DiagnosticsEngine & Diags)2310 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
2311 const char *const *ArgBegin,
2312 const char *const *ArgEnd,
2313 DiagnosticsEngine &Diags) {
2314 bool Success = true;
2315
2316 // Parse the arguments.
2317 std::unique_ptr<OptTable> Opts(createDriverOptTable());
2318 const unsigned IncludedFlagsBitmask = options::CC1Option;
2319 unsigned MissingArgIndex, MissingArgCount;
2320 InputArgList Args =
2321 Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
2322 MissingArgCount, IncludedFlagsBitmask);
2323 LangOptions &LangOpts = *Res.getLangOpts();
2324
2325 // Check for missing argument error.
2326 if (MissingArgCount) {
2327 Diags.Report(diag::err_drv_missing_argument)
2328 << Args.getArgString(MissingArgIndex) << MissingArgCount;
2329 Success = false;
2330 }
2331
2332 // Issue errors on unknown arguments.
2333 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
2334 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
2335 Success = false;
2336 }
2337
2338 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
2339 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
2340 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
2341 Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
2342 false /*DefaultDiagColor*/);
2343 ParseCommentArgs(LangOpts.CommentOpts, Args);
2344 ParseFileSystemArgs(Res.getFileSystemOpts(), Args);
2345 // FIXME: We shouldn't have to pass the DashX option around here
2346 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags);
2347 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
2348 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
2349 Res.getTargetOpts());
2350 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args);
2351 if (DashX == IK_AST || DashX == IK_LLVM_IR) {
2352 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
2353 // PassManager in BackendUtil.cpp. They need to be initializd no matter
2354 // what the input type is.
2355 if (Args.hasArg(OPT_fobjc_arc))
2356 LangOpts.ObjCAutoRefCount = 1;
2357 // PIClevel and PIELevel are needed during code generation and this should be
2358 // set regardless of the input type.
2359 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2360 LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
2361 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2362 Diags, LangOpts.Sanitize);
2363 } else {
2364 // Other LangOpts are only initialzed when the input is not AST or LLVM IR.
2365 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
2366 Res.getPreprocessorOpts(), Diags);
2367 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
2368 LangOpts.ObjCExceptions = 1;
2369 }
2370
2371 if (LangOpts.CUDA) {
2372 // During CUDA device-side compilation, the aux triple is the
2373 // triple used for host compilation.
2374 if (LangOpts.CUDAIsDevice)
2375 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
2376
2377 // Set default FP_CONTRACT to FAST.
2378 if (!Args.hasArg(OPT_ffp_contract))
2379 Res.getCodeGenOpts().setFPContractMode(CodeGenOptions::FPC_Fast);
2380 }
2381
2382 // FIXME: Override value name discarding when asan or msan is used because the
2383 // backend passes depend on the name of the alloca in order to print out
2384 // names.
2385 Res.getCodeGenOpts().DiscardValueNames &=
2386 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
2387 !LangOpts.Sanitize.has(SanitizerKind::Memory);
2388
2389 // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of
2390 // PCH file and find the original header name. Remove the need to do that in
2391 // ParsePreprocessorArgs and remove the FileManager
2392 // parameters from the function and the "FileManager.h" #include.
2393 FileManager FileMgr(Res.getFileSystemOpts());
2394 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, FileMgr, Diags);
2395 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
2396 Res.getFrontendOpts().ProgramAction);
2397 return Success;
2398 }
2399
getModuleHash() const2400 std::string CompilerInvocation::getModuleHash() const {
2401 // Note: For QoI reasons, the things we use as a hash here should all be
2402 // dumped via the -module-info flag.
2403 using llvm::hash_code;
2404 using llvm::hash_value;
2405 using llvm::hash_combine;
2406
2407 // Start the signature with the compiler version.
2408 // FIXME: We'd rather use something more cryptographically sound than
2409 // CityHash, but this will do for now.
2410 hash_code code = hash_value(getClangFullRepositoryVersion());
2411
2412 // Extend the signature with the language options
2413 #define LANGOPT(Name, Bits, Default, Description) \
2414 code = hash_combine(code, LangOpts->Name);
2415 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
2416 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
2417 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
2418 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
2419 #include "clang/Basic/LangOptions.def"
2420
2421 for (StringRef Feature : LangOpts->ModuleFeatures)
2422 code = hash_combine(code, Feature);
2423
2424 // Extend the signature with the target options.
2425 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
2426 TargetOpts->ABI);
2427 for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i)
2428 code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]);
2429
2430 // Extend the signature with preprocessor options.
2431 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
2432 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
2433 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
2434
2435 for (std::vector<std::pair<std::string, bool/*isUndef*/>>::const_iterator
2436 I = getPreprocessorOpts().Macros.begin(),
2437 IEnd = getPreprocessorOpts().Macros.end();
2438 I != IEnd; ++I) {
2439 // If we're supposed to ignore this macro for the purposes of modules,
2440 // don't put it into the hash.
2441 if (!hsOpts.ModulesIgnoreMacros.empty()) {
2442 // Check whether we're ignoring this macro.
2443 StringRef MacroDef = I->first;
2444 if (hsOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first))
2445 continue;
2446 }
2447
2448 code = hash_combine(code, I->first, I->second);
2449 }
2450
2451 // Extend the signature with the sysroot and other header search options.
2452 code = hash_combine(code, hsOpts.Sysroot,
2453 hsOpts.ModuleFormat,
2454 hsOpts.UseDebugInfo,
2455 hsOpts.UseBuiltinIncludes,
2456 hsOpts.UseStandardSystemIncludes,
2457 hsOpts.UseStandardCXXIncludes,
2458 hsOpts.UseLibcxx);
2459 code = hash_combine(code, hsOpts.ResourceDir);
2460
2461 // Extend the signature with the user build path.
2462 code = hash_combine(code, hsOpts.ModuleUserBuildPath);
2463
2464 // Extend the signature with the module file extensions.
2465 const FrontendOptions &frontendOpts = getFrontendOpts();
2466 for (const auto &ext : frontendOpts.ModuleFileExtensions) {
2467 code = ext->hashExtension(code);
2468 }
2469
2470 // Darwin-specific hack: if we have a sysroot, use the contents and
2471 // modification time of
2472 // $sysroot/System/Library/CoreServices/SystemVersion.plist
2473 // as part of the module hash.
2474 if (!hsOpts.Sysroot.empty()) {
2475 SmallString<128> systemVersionFile;
2476 systemVersionFile += hsOpts.Sysroot;
2477 llvm::sys::path::append(systemVersionFile, "System");
2478 llvm::sys::path::append(systemVersionFile, "Library");
2479 llvm::sys::path::append(systemVersionFile, "CoreServices");
2480 llvm::sys::path::append(systemVersionFile, "SystemVersion.plist");
2481
2482 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
2483 llvm::MemoryBuffer::getFile(systemVersionFile);
2484 if (buffer) {
2485 code = hash_combine(code, buffer.get()->getBuffer());
2486
2487 struct stat statBuf;
2488 if (stat(systemVersionFile.c_str(), &statBuf) == 0)
2489 code = hash_combine(code, statBuf.st_mtime);
2490 }
2491 }
2492
2493 return llvm::APInt(64, code).toString(36, /*Signed=*/false);
2494 }
2495
2496 namespace clang {
2497
2498 template<typename IntTy>
getLastArgIntValueImpl(const ArgList & Args,OptSpecifier Id,IntTy Default,DiagnosticsEngine * Diags)2499 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
2500 IntTy Default,
2501 DiagnosticsEngine *Diags) {
2502 IntTy Res = Default;
2503 if (Arg *A = Args.getLastArg(Id)) {
2504 if (StringRef(A->getValue()).getAsInteger(10, Res)) {
2505 if (Diags)
2506 Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
2507 << A->getValue();
2508 }
2509 }
2510 return Res;
2511 }
2512
2513
2514 // Declared in clang/Frontend/Utils.h.
getLastArgIntValue(const ArgList & Args,OptSpecifier Id,int Default,DiagnosticsEngine * Diags)2515 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
2516 DiagnosticsEngine *Diags) {
2517 return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
2518 }
2519
getLastArgUInt64Value(const ArgList & Args,OptSpecifier Id,uint64_t Default,DiagnosticsEngine * Diags)2520 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
2521 uint64_t Default,
2522 DiagnosticsEngine *Diags) {
2523 return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
2524 }
2525
BuryPointer(const void * Ptr)2526 void BuryPointer(const void *Ptr) {
2527 // This function may be called only a small fixed amount of times per each
2528 // invocation, otherwise we do actually have a leak which we want to report.
2529 // If this function is called more than kGraveYardMaxSize times, the pointers
2530 // will not be properly buried and a leak detector will report a leak, which
2531 // is what we want in such case.
2532 static const size_t kGraveYardMaxSize = 16;
2533 LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
2534 static std::atomic<unsigned> GraveYardSize;
2535 unsigned Idx = GraveYardSize++;
2536 if (Idx >= kGraveYardMaxSize)
2537 return;
2538 GraveYard[Idx] = Ptr;
2539 }
2540
2541 IntrusiveRefCntPtr<vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags)2542 createVFSFromCompilerInvocation(const CompilerInvocation &CI,
2543 DiagnosticsEngine &Diags) {
2544 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
2545 return vfs::getRealFileSystem();
2546
2547 IntrusiveRefCntPtr<vfs::OverlayFileSystem>
2548 Overlay(new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
2549 // earlier vfs files are on the bottom
2550 for (const std::string &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
2551 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
2552 llvm::MemoryBuffer::getFile(File);
2553 if (!Buffer) {
2554 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
2555 return IntrusiveRefCntPtr<vfs::FileSystem>();
2556 }
2557
2558 IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
2559 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File);
2560 if (!FS.get()) {
2561 Diags.Report(diag::err_invalid_vfs_overlay) << File;
2562 return IntrusiveRefCntPtr<vfs::FileSystem>();
2563 }
2564 Overlay->pushOverlay(FS);
2565 }
2566 return Overlay;
2567 }
2568 } // end namespace clang
2569