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 "clang/Frontend/CompilerInvocation.h"
11 #include "clang/Basic/FileManager.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Config/config.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Options.h"
16 #include "clang/Driver/Util.h"
17 #include "clang/Frontend/FrontendDiagnostic.h"
18 #include "clang/Frontend/LangStandard.h"
19 #include "clang/Frontend/Utils.h"
20 #include "clang/Lex/HeaderSearchOptions.h"
21 #include "clang/Serialization/ASTReader.h"
22 #include "llvm/ADT/Hashing.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Option/Arg.h"
29 #include "llvm/Option/ArgList.h"
30 #include "llvm/Option/OptTable.h"
31 #include "llvm/Option/Option.h"
32 #include "llvm/Support/CodeGen.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Process.h"
38 #include <atomic>
39 #include <memory>
40 #include <sys/stat.h>
41 #include <system_error>
42 using namespace clang;
43 
44 //===----------------------------------------------------------------------===//
45 // Initialization.
46 //===----------------------------------------------------------------------===//
47 
CompilerInvocationBase()48 CompilerInvocationBase::CompilerInvocationBase()
49   : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
50     DiagnosticOpts(new DiagnosticOptions()),
51     HeaderSearchOpts(new HeaderSearchOptions()),
52     PreprocessorOpts(new PreprocessorOptions()) {}
53 
CompilerInvocationBase(const CompilerInvocationBase & X)54 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
55   : RefCountedBase<CompilerInvocation>(),
56     LangOpts(new LangOptions(*X.getLangOpts())),
57     TargetOpts(new TargetOptions(X.getTargetOpts())),
58     DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
59     HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
60     PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
61 
~CompilerInvocationBase()62 CompilerInvocationBase::~CompilerInvocationBase() {}
63 
64 //===----------------------------------------------------------------------===//
65 // Deserialization (from args)
66 //===----------------------------------------------------------------------===//
67 
68 using namespace clang::driver;
69 using namespace clang::driver::options;
70 using namespace llvm::opt;
71 
72 //
73 
getOptimizationLevel(ArgList & Args,InputKind IK,DiagnosticsEngine & Diags)74 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
75                                      DiagnosticsEngine &Diags) {
76   unsigned DefaultOpt = 0;
77   if (IK == IK_OpenCL && !Args.hasArg(OPT_cl_opt_disable))
78     DefaultOpt = 2;
79 
80   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
81     if (A->getOption().matches(options::OPT_O0))
82       return 0;
83 
84     if (A->getOption().matches(options::OPT_Ofast))
85       return 3;
86 
87     assert (A->getOption().matches(options::OPT_O));
88 
89     StringRef S(A->getValue());
90     if (S == "s" || S == "z" || S.empty())
91       return 2;
92 
93     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
94   }
95 
96   return DefaultOpt;
97 }
98 
getOptimizationLevelSize(ArgList & Args)99 static unsigned getOptimizationLevelSize(ArgList &Args) {
100   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
101     if (A->getOption().matches(options::OPT_O)) {
102       switch (A->getValue()[0]) {
103       default:
104         return 0;
105       case 's':
106         return 1;
107       case 'z':
108         return 2;
109       }
110     }
111   }
112   return 0;
113 }
114 
addDiagnosticArgs(ArgList & Args,OptSpecifier Group,OptSpecifier GroupWithValue,std::vector<std::string> & Diagnostics)115 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
116                               OptSpecifier GroupWithValue,
117                               std::vector<std::string> &Diagnostics) {
118   for (Arg *A : Args.filtered(Group)) {
119     if (A->getOption().getKind() == Option::FlagClass) {
120       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
121       // its name (minus the "W" or "R" at the beginning) to the warning list.
122       Diagnostics.push_back(A->getOption().getName().drop_front(1));
123     } else if (A->getOption().matches(GroupWithValue)) {
124       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
125       Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
126     } else {
127       // Otherwise, add its value (for OPT_W_Joined and similar).
128       for (const char *Arg : A->getValues())
129         Diagnostics.push_back(Arg);
130     }
131   }
132 }
133 
ParseAnalyzerArgs(AnalyzerOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)134 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
135                               DiagnosticsEngine &Diags) {
136   using namespace options;
137   bool Success = true;
138   if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
139     StringRef Name = A->getValue();
140     AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
141 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
142       .Case(CMDFLAG, NAME##Model)
143 #include "clang/StaticAnalyzer/Core/Analyses.def"
144       .Default(NumStores);
145     if (Value == NumStores) {
146       Diags.Report(diag::err_drv_invalid_value)
147         << A->getAsString(Args) << Name;
148       Success = false;
149     } else {
150       Opts.AnalysisStoreOpt = Value;
151     }
152   }
153 
154   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
155     StringRef Name = A->getValue();
156     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
157 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
158       .Case(CMDFLAG, NAME##Model)
159 #include "clang/StaticAnalyzer/Core/Analyses.def"
160       .Default(NumConstraints);
161     if (Value == NumConstraints) {
162       Diags.Report(diag::err_drv_invalid_value)
163         << A->getAsString(Args) << Name;
164       Success = false;
165     } else {
166       Opts.AnalysisConstraintsOpt = Value;
167     }
168   }
169 
170   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
171     StringRef Name = A->getValue();
172     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
173 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
174       .Case(CMDFLAG, PD_##NAME)
175 #include "clang/StaticAnalyzer/Core/Analyses.def"
176       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
177     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
178       Diags.Report(diag::err_drv_invalid_value)
179         << A->getAsString(Args) << Name;
180       Success = false;
181     } else {
182       Opts.AnalysisDiagOpt = Value;
183     }
184   }
185 
186   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
187     StringRef Name = A->getValue();
188     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
189 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
190       .Case(CMDFLAG, NAME)
191 #include "clang/StaticAnalyzer/Core/Analyses.def"
192       .Default(NumPurgeModes);
193     if (Value == NumPurgeModes) {
194       Diags.Report(diag::err_drv_invalid_value)
195         << A->getAsString(Args) << Name;
196       Success = false;
197     } else {
198       Opts.AnalysisPurgeOpt = Value;
199     }
200   }
201 
202   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
203     StringRef Name = A->getValue();
204     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
205 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
206       .Case(CMDFLAG, NAME)
207 #include "clang/StaticAnalyzer/Core/Analyses.def"
208       .Default(NumInliningModes);
209     if (Value == NumInliningModes) {
210       Diags.Report(diag::err_drv_invalid_value)
211         << A->getAsString(Args) << Name;
212       Success = false;
213     } else {
214       Opts.InliningMode = Value;
215     }
216   }
217 
218   Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
219   Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
220 
221   Opts.visualizeExplodedGraphWithGraphViz =
222     Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
223   Opts.visualizeExplodedGraphWithUbiGraph =
224     Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
225   Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
226   Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
227   Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
228   Opts.AnalyzeNestedBlocks =
229     Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
230   Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
231   Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
232   Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
233   Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
234   Opts.maxBlockVisitOnPath =
235       getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
236   Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
237   Opts.InlineMaxStackDepth =
238       getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
239                          Opts.InlineMaxStackDepth, Diags);
240 
241   Opts.CheckersControlList.clear();
242   for (arg_iterator it = Args.filtered_begin(OPT_analyzer_checker,
243                                              OPT_analyzer_disable_checker),
244          ie = Args.filtered_end(); it != ie; ++it) {
245     const Arg *A = *it;
246     A->claim();
247     bool enable = (A->getOption().getID() == OPT_analyzer_checker);
248     // We can have a list of comma separated checker names, e.g:
249     // '-analyzer-checker=cocoa,unix'
250     StringRef checkerList = A->getValue();
251     SmallVector<StringRef, 4> checkers;
252     checkerList.split(checkers, ",");
253     for (unsigned i = 0, e = checkers.size(); i != e; ++i)
254       Opts.CheckersControlList.push_back(std::make_pair(checkers[i], enable));
255   }
256 
257   // Go through the analyzer configuration options.
258   for (arg_iterator it = Args.filtered_begin(OPT_analyzer_config),
259        ie = Args.filtered_end(); it != ie; ++it) {
260     const Arg *A = *it;
261     A->claim();
262     // We can have a list of comma separated config names, e.g:
263     // '-analyzer-config key1=val1,key2=val2'
264     StringRef configList = A->getValue();
265     SmallVector<StringRef, 4> configVals;
266     configList.split(configVals, ",");
267     for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
268       StringRef key, val;
269       std::tie(key, val) = configVals[i].split("=");
270       if (val.empty()) {
271         Diags.Report(SourceLocation(),
272                      diag::err_analyzer_config_no_value) << configVals[i];
273         Success = false;
274         break;
275       }
276       if (val.find('=') != StringRef::npos) {
277         Diags.Report(SourceLocation(),
278                      diag::err_analyzer_config_multiple_values)
279           << configVals[i];
280         Success = false;
281         break;
282       }
283       Opts.Config[key] = val;
284     }
285   }
286 
287   return Success;
288 }
289 
ParseMigratorArgs(MigratorOptions & Opts,ArgList & Args)290 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
291   Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
292   Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
293   return true;
294 }
295 
ParseCommentArgs(CommentOptions & Opts,ArgList & Args)296 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
297   Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
298   Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
299 }
300 
getCodeModel(ArgList & Args,DiagnosticsEngine & Diags)301 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
302   if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
303     StringRef Value = A->getValue();
304     if (Value == "small" || Value == "kernel" || Value == "medium" ||
305         Value == "large")
306       return Value;
307     Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
308   }
309   return "default";
310 }
311 
312 /// \brief Create a new Regex instance out of the string value in \p RpassArg.
313 /// It returns a pointer to the newly generated Regex instance.
314 static std::shared_ptr<llvm::Regex>
GenerateOptimizationRemarkRegex(DiagnosticsEngine & Diags,ArgList & Args,Arg * RpassArg)315 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
316                                 Arg *RpassArg) {
317   StringRef Val = RpassArg->getValue();
318   std::string RegexError;
319   std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
320   if (!Pattern->isValid(RegexError)) {
321     Diags.Report(diag::err_drv_optimization_remark_pattern)
322         << RegexError << RpassArg->getAsString(Args);
323     Pattern.reset();
324   }
325   return Pattern;
326 }
327 
parseSanitizerKinds(StringRef FlagName,const std::vector<std::string> & Sanitizers,DiagnosticsEngine & Diags,SanitizerSet & S)328 static void parseSanitizerKinds(StringRef FlagName,
329                                 const std::vector<std::string> &Sanitizers,
330                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
331   for (const auto &Sanitizer : Sanitizers) {
332     SanitizerKind K = llvm::StringSwitch<SanitizerKind>(Sanitizer)
333 #define SANITIZER(NAME, ID) .Case(NAME, SanitizerKind::ID)
334 #include "clang/Basic/Sanitizers.def"
335                           .Default(SanitizerKind::Unknown);
336     if (K == SanitizerKind::Unknown)
337       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
338     else
339       S.set(K, true);
340   }
341 }
342 
ParseCodeGenArgs(CodeGenOptions & Opts,ArgList & Args,InputKind IK,DiagnosticsEngine & Diags,const TargetOptions & TargetOpts)343 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
344                              DiagnosticsEngine &Diags,
345                              const TargetOptions &TargetOpts) {
346   using namespace options;
347   bool Success = true;
348 
349   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
350   // TODO: This could be done in Driver
351   unsigned MaxOptLevel = 3;
352   if (OptimizationLevel > MaxOptLevel) {
353     // If the optimization level is not supported, fall back on the default
354     // optimization
355     Diags.Report(diag::warn_drv_optimization_value)
356         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
357     OptimizationLevel = MaxOptLevel;
358   }
359   Opts.OptimizationLevel = OptimizationLevel;
360 
361   // We must always run at least the always inlining pass.
362   Opts.setInlining(
363     (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalInlining
364                                  : CodeGenOptions::OnlyAlwaysInlining);
365   // -fno-inline-functions overrides OptimizationLevel > 1.
366   Opts.NoInline = Args.hasArg(OPT_fno_inline);
367   Opts.setInlining(Args.hasArg(OPT_fno_inline_functions) ?
368                      CodeGenOptions::OnlyAlwaysInlining : Opts.getInlining());
369 
370   if (Arg *A = Args.getLastArg(OPT_fveclib)) {
371     StringRef Name = A->getValue();
372     if (Name == "Accelerate")
373       Opts.setVecLib(CodeGenOptions::Accelerate);
374     else if (Name == "none")
375       Opts.setVecLib(CodeGenOptions::NoLibrary);
376     else
377       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
378   }
379 
380   if (Args.hasArg(OPT_gline_tables_only)) {
381     Opts.setDebugInfo(CodeGenOptions::DebugLineTablesOnly);
382   } else if (Args.hasArg(OPT_g_Flag) || Args.hasArg(OPT_gdwarf_2) ||
383              Args.hasArg(OPT_gdwarf_3) || Args.hasArg(OPT_gdwarf_4)) {
384     bool Default = false;
385     // Until dtrace (via CTF) and LLDB can deal with distributed debug info,
386     // Darwin and FreeBSD default to standalone/full debug info.
387     if (llvm::Triple(TargetOpts.Triple).isOSDarwin() ||
388         llvm::Triple(TargetOpts.Triple).isOSFreeBSD())
389       Default = true;
390 
391     if (Args.hasFlag(OPT_fstandalone_debug, OPT_fno_standalone_debug, Default))
392       Opts.setDebugInfo(CodeGenOptions::FullDebugInfo);
393     else
394       Opts.setDebugInfo(CodeGenOptions::LimitedDebugInfo);
395   }
396   Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
397   Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
398   if (Args.hasArg(OPT_gdwarf_2))
399     Opts.DwarfVersion = 2;
400   else if (Args.hasArg(OPT_gdwarf_3))
401     Opts.DwarfVersion = 3;
402   else if (Args.hasArg(OPT_gdwarf_4))
403     Opts.DwarfVersion = 4;
404   else if (Opts.getDebugInfo() != CodeGenOptions::NoDebugInfo)
405     // Default Dwarf version is 4 if we are generating debug information.
406     Opts.DwarfVersion = 4;
407 
408   if (const Arg *A =
409           Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
410     Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
411 
412   Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns);
413   Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
414   Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
415   Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
416     OPT_fuse_register_sized_bitfield_access);
417   Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
418   Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
419   Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
420   Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants);
421   Opts.NoCommon = Args.hasArg(OPT_fno_common);
422   Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
423   Opts.OptimizeSize = getOptimizationLevelSize(Args);
424   Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
425                             Args.hasArg(OPT_ffreestanding));
426   Opts.UnrollLoops =
427       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
428                    (Opts.OptimizationLevel > 1 && !Opts.OptimizeSize));
429   Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
430 
431   Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
432   Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
433   Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
434   Opts.ProfileInstrGenerate = Args.hasArg(OPT_fprofile_instr_generate);
435   Opts.InstrProfileInput = Args.getLastArgValue(OPT_fprofile_instr_use_EQ);
436   Opts.CoverageMapping = Args.hasArg(OPT_fcoverage_mapping);
437   Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
438   Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
439   Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
440   Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
441   Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
442   Opts.CodeModel = getCodeModel(Args, Diags);
443   Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
444   Opts.DisableFPElim = Args.hasArg(OPT_mdisable_fp_elim);
445   Opts.DisableFree = Args.hasArg(OPT_disable_free);
446   Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
447   Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
448   Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable);
449   Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
450   Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
451                        Args.hasArg(OPT_cl_finite_math_only) ||
452                        Args.hasArg(OPT_cl_fast_relaxed_math));
453   Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
454                        Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
455                        Args.hasArg(OPT_cl_finite_math_only) ||
456                        Args.hasArg(OPT_cl_fast_relaxed_math));
457   Opts.NoSignedZeros = Args.hasArg(OPT_fno_signed_zeros);
458   Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
459   Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
460   Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
461   Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
462   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
463   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
464   Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
465   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
466   Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
467   Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
468   Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
469   Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
470   Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
471   Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
472                       Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
473                       Args.hasArg(OPT_cl_fast_relaxed_math);
474   Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
475   Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
476   Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
477   if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
478     Diags.Report(diag::err_drv_invalid_value)
479         << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
480         << Opts.ThreadModel;
481   Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
482   Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
483 
484   Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
485                                        OPT_fno_function_sections, false);
486   Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
487                                    OPT_fno_data_sections, false);
488   Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
489                                          OPT_fno_unique_section_names, true);
490 
491   Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
492 
493   Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
494 
495   Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive);
496   Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
497   Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
498 
499   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
500   Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
501 
502   Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
503   Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
504   Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
505   if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
506     Opts.CoverageFile = Args.getLastArgValue(OPT_coverage_file);
507     Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
508     Opts.CoverageNoFunctionNamesInData =
509         Args.hasArg(OPT_coverage_no_function_names_in_data);
510     Opts.CoverageExitBlockBeforeBody =
511         Args.hasArg(OPT_coverage_exit_block_before_body);
512     if (Args.hasArg(OPT_coverage_version_EQ)) {
513       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
514       if (CoverageVersion.size() != 4) {
515         Diags.Report(diag::err_drv_invalid_value)
516             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
517             << CoverageVersion;
518       } else {
519         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
520       }
521     }
522   }
523 
524   Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
525   Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
526   Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
527   Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections);
528   Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
529   Opts.LinkBitcodeFile = Args.getLastArgValue(OPT_mlink_bitcode_file);
530   Opts.SanitizeCoverage =
531       getLastArgIntValue(Args, OPT_fsanitize_coverage, 0, Diags);
532   Opts.SanitizeMemoryTrackOrigins =
533       getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
534   Opts.SanitizeUndefinedTrapOnError =
535       Args.hasArg(OPT_fsanitize_undefined_trap_on_error);
536   Opts.SSPBufferSize =
537       getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
538   Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
539   if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
540     StringRef Val = A->getValue();
541     unsigned StackAlignment = Opts.StackAlignment;
542     Val.getAsInteger(10, StackAlignment);
543     Opts.StackAlignment = StackAlignment;
544   }
545 
546   if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
547     StringRef Val = A->getValue();
548     unsigned StackProbeSize = Opts.StackProbeSize;
549     Val.getAsInteger(0, StackProbeSize);
550     Opts.StackProbeSize = StackProbeSize;
551   }
552 
553   if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
554     StringRef Name = A->getValue();
555     unsigned Method = llvm::StringSwitch<unsigned>(Name)
556       .Case("legacy", CodeGenOptions::Legacy)
557       .Case("non-legacy", CodeGenOptions::NonLegacy)
558       .Case("mixed", CodeGenOptions::Mixed)
559       .Default(~0U);
560     if (Method == ~0U) {
561       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
562       Success = false;
563     } else {
564       Opts.setObjCDispatchMethod(
565         static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
566     }
567   }
568 
569   if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
570     StringRef Name = A->getValue();
571     unsigned Model = llvm::StringSwitch<unsigned>(Name)
572         .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
573         .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
574         .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
575         .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
576         .Default(~0U);
577     if (Model == ~0U) {
578       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
579       Success = false;
580     } else {
581       Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
582     }
583   }
584 
585   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
586     StringRef Val = A->getValue();
587     if (Val == "fast")
588       Opts.setFPContractMode(CodeGenOptions::FPC_Fast);
589     else if (Val == "on")
590       Opts.setFPContractMode(CodeGenOptions::FPC_On);
591     else if (Val == "off")
592       Opts.setFPContractMode(CodeGenOptions::FPC_Off);
593     else
594       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
595   }
596 
597   if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
598     if (A->getOption().matches(OPT_fpcc_struct_return)) {
599       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
600     } else {
601       assert(A->getOption().matches(OPT_freg_struct_return));
602       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
603     }
604   }
605 
606   Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
607   bool NeedLocTracking = false;
608 
609   if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
610     Opts.OptimizationRemarkPattern =
611         GenerateOptimizationRemarkRegex(Diags, Args, A);
612     NeedLocTracking = true;
613   }
614 
615   if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
616     Opts.OptimizationRemarkMissedPattern =
617         GenerateOptimizationRemarkRegex(Diags, Args, A);
618     NeedLocTracking = true;
619   }
620 
621   if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
622     Opts.OptimizationRemarkAnalysisPattern =
623         GenerateOptimizationRemarkRegex(Diags, Args, A);
624     NeedLocTracking = true;
625   }
626 
627   // If the user requested to use a sample profile for PGO, then the
628   // backend will need to track source location information so the profile
629   // can be incorporated into the IR.
630   if (!Opts.SampleProfileFile.empty())
631     NeedLocTracking = true;
632 
633   // If the user requested a flag that requires source locations available in
634   // the backend, make sure that the backend tracks source location information.
635   if (NeedLocTracking && Opts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
636     Opts.setDebugInfo(CodeGenOptions::LocTrackingOnly);
637 
638   Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
639 
640   // Parse -fsanitize-recover= arguments.
641   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
642   parseSanitizerKinds("-fsanitize-recover=",
643                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
644                       Opts.SanitizeRecover);
645 
646   return Success;
647 }
648 
ParseDependencyOutputArgs(DependencyOutputOptions & Opts,ArgList & Args)649 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
650                                       ArgList &Args) {
651   using namespace options;
652   Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
653   Opts.Targets = Args.getAllArgValues(OPT_MT);
654   Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
655   Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
656   Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
657   Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
658   Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
659   Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
660   Opts.PrintShowIncludes = Args.hasArg(OPT_show_includes);
661   Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
662   Opts.ModuleDependencyOutputDir =
663       Args.getLastArgValue(OPT_module_dependency_dir);
664 }
665 
ParseDiagnosticArgs(DiagnosticOptions & Opts,ArgList & Args,DiagnosticsEngine * Diags)666 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
667                                 DiagnosticsEngine *Diags) {
668   using namespace options;
669   bool Success = true;
670 
671   Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
672   if (Arg *A =
673           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
674     Opts.DiagnosticSerializationFile = A->getValue();
675   Opts.IgnoreWarnings = Args.hasArg(OPT_w);
676   Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
677   Opts.Pedantic = Args.hasArg(OPT_pedantic);
678   Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
679   Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
680   Opts.ShowColors = Args.hasArg(OPT_fcolor_diagnostics);
681   Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
682                                  OPT_fno_show_column,
683                                  /*Default=*/true);
684   Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
685   Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
686   Opts.ShowOptionNames = Args.hasArg(OPT_fdiagnostics_show_option);
687 
688   llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
689 
690   // Default behavior is to not to show note include stacks.
691   Opts.ShowNoteIncludeStack = false;
692   if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
693                                OPT_fno_diagnostics_show_note_include_stack))
694     if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
695       Opts.ShowNoteIncludeStack = true;
696 
697   StringRef ShowOverloads =
698     Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
699   if (ShowOverloads == "best")
700     Opts.setShowOverloads(Ovl_Best);
701   else if (ShowOverloads == "all")
702     Opts.setShowOverloads(Ovl_All);
703   else {
704     Success = false;
705     if (Diags)
706       Diags->Report(diag::err_drv_invalid_value)
707       << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
708       << ShowOverloads;
709   }
710 
711   StringRef ShowCategory =
712     Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
713   if (ShowCategory == "none")
714     Opts.ShowCategories = 0;
715   else if (ShowCategory == "id")
716     Opts.ShowCategories = 1;
717   else if (ShowCategory == "name")
718     Opts.ShowCategories = 2;
719   else {
720     Success = false;
721     if (Diags)
722       Diags->Report(diag::err_drv_invalid_value)
723       << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
724       << ShowCategory;
725   }
726 
727   StringRef Format =
728     Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
729   if (Format == "clang")
730     Opts.setFormat(DiagnosticOptions::Clang);
731   else if (Format == "msvc")
732     Opts.setFormat(DiagnosticOptions::MSVC);
733   else if (Format == "msvc-fallback") {
734     Opts.setFormat(DiagnosticOptions::MSVC);
735     Opts.CLFallbackMode = true;
736   } else if (Format == "vi")
737     Opts.setFormat(DiagnosticOptions::Vi);
738   else {
739     Success = false;
740     if (Diags)
741       Diags->Report(diag::err_drv_invalid_value)
742       << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
743       << Format;
744   }
745 
746   Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
747   Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
748   Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
749   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify);
750   Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
751   Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
752   Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
753   Opts.MacroBacktraceLimit =
754       getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
755                          DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
756   Opts.TemplateBacktraceLimit = getLastArgIntValue(
757       Args, OPT_ftemplate_backtrace_limit,
758       DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
759   Opts.ConstexprBacktraceLimit = getLastArgIntValue(
760       Args, OPT_fconstexpr_backtrace_limit,
761       DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
762   Opts.SpellCheckingLimit = getLastArgIntValue(
763       Args, OPT_fspell_checking_limit,
764       DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
765   Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
766                                     DiagnosticOptions::DefaultTabStop, Diags);
767   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
768     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
769     if (Diags)
770       Diags->Report(diag::warn_ignoring_ftabstop_value)
771       << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
772   }
773   Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
774   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
775   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
776 
777   return Success;
778 }
779 
ParseFileSystemArgs(FileSystemOptions & Opts,ArgList & Args)780 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
781   Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
782 }
783 
ParseFrontendArgs(FrontendOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)784 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
785                                    DiagnosticsEngine &Diags) {
786   using namespace options;
787   Opts.ProgramAction = frontend::ParseSyntaxOnly;
788   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
789     switch (A->getOption().getID()) {
790     default:
791       llvm_unreachable("Invalid option in group!");
792     case OPT_ast_list:
793       Opts.ProgramAction = frontend::ASTDeclList; break;
794     case OPT_ast_dump:
795     case OPT_ast_dump_lookups:
796       Opts.ProgramAction = frontend::ASTDump; break;
797     case OPT_ast_print:
798       Opts.ProgramAction = frontend::ASTPrint; break;
799     case OPT_ast_view:
800       Opts.ProgramAction = frontend::ASTView; break;
801     case OPT_dump_raw_tokens:
802       Opts.ProgramAction = frontend::DumpRawTokens; break;
803     case OPT_dump_tokens:
804       Opts.ProgramAction = frontend::DumpTokens; break;
805     case OPT_S:
806       Opts.ProgramAction = frontend::EmitAssembly; break;
807     case OPT_emit_llvm_bc:
808       Opts.ProgramAction = frontend::EmitBC; break;
809     case OPT_emit_html:
810       Opts.ProgramAction = frontend::EmitHTML; break;
811     case OPT_emit_llvm:
812       Opts.ProgramAction = frontend::EmitLLVM; break;
813     case OPT_emit_llvm_only:
814       Opts.ProgramAction = frontend::EmitLLVMOnly; break;
815     case OPT_emit_codegen_only:
816       Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
817     case OPT_emit_obj:
818       Opts.ProgramAction = frontend::EmitObj; break;
819     case OPT_fixit_EQ:
820       Opts.FixItSuffix = A->getValue();
821       // fall-through!
822     case OPT_fixit:
823       Opts.ProgramAction = frontend::FixIt; break;
824     case OPT_emit_module:
825       Opts.ProgramAction = frontend::GenerateModule; break;
826     case OPT_emit_pch:
827       Opts.ProgramAction = frontend::GeneratePCH; break;
828     case OPT_emit_pth:
829       Opts.ProgramAction = frontend::GeneratePTH; break;
830     case OPT_init_only:
831       Opts.ProgramAction = frontend::InitOnly; break;
832     case OPT_fsyntax_only:
833       Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
834     case OPT_module_file_info:
835       Opts.ProgramAction = frontend::ModuleFileInfo; break;
836     case OPT_verify_pch:
837       Opts.ProgramAction = frontend::VerifyPCH; break;
838     case OPT_print_decl_contexts:
839       Opts.ProgramAction = frontend::PrintDeclContext; break;
840     case OPT_print_preamble:
841       Opts.ProgramAction = frontend::PrintPreamble; break;
842     case OPT_E:
843       Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
844     case OPT_rewrite_macros:
845       Opts.ProgramAction = frontend::RewriteMacros; break;
846     case OPT_rewrite_objc:
847       Opts.ProgramAction = frontend::RewriteObjC; break;
848     case OPT_rewrite_test:
849       Opts.ProgramAction = frontend::RewriteTest; break;
850     case OPT_analyze:
851       Opts.ProgramAction = frontend::RunAnalysis; break;
852     case OPT_migrate:
853       Opts.ProgramAction = frontend::MigrateSource; break;
854     case OPT_Eonly:
855       Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
856     }
857   }
858 
859   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
860     Opts.Plugins.push_back(A->getValue(0));
861     Opts.ProgramAction = frontend::PluginAction;
862     Opts.ActionName = A->getValue();
863 
864     for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
865            end = Args.filtered_end(); it != end; ++it) {
866       if ((*it)->getValue(0) == Opts.ActionName)
867         Opts.PluginArgs.push_back((*it)->getValue(1));
868     }
869   }
870 
871   Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
872   Opts.AddPluginArgs.resize(Opts.AddPluginActions.size());
873   for (int i = 0, e = Opts.AddPluginActions.size(); i != e; ++i) {
874     for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
875            end = Args.filtered_end(); it != end; ++it) {
876       if ((*it)->getValue(0) == Opts.AddPluginActions[i])
877         Opts.AddPluginArgs[i].push_back((*it)->getValue(1));
878     }
879   }
880 
881   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
882     Opts.CodeCompletionAt =
883       ParsedSourceLocation::FromString(A->getValue());
884     if (Opts.CodeCompletionAt.FileName.empty())
885       Diags.Report(diag::err_drv_invalid_value)
886         << A->getAsString(Args) << A->getValue();
887   }
888   Opts.DisableFree = Args.hasArg(OPT_disable_free);
889 
890   Opts.OutputFile = Args.getLastArgValue(OPT_o);
891   Opts.Plugins = Args.getAllArgValues(OPT_load);
892   Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
893   Opts.ShowHelp = Args.hasArg(OPT_help);
894   Opts.ShowStats = Args.hasArg(OPT_print_stats);
895   Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
896   Opts.ShowVersion = Args.hasArg(OPT_version);
897   Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
898   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
899   Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
900   Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
901   Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
902   Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
903   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
904   Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
905   Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
906   Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
907   Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
908   Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
909   Opts.ModuleFiles = Args.getAllArgValues(OPT_fmodule_file);
910 
911   Opts.CodeCompleteOpts.IncludeMacros
912     = Args.hasArg(OPT_code_completion_macros);
913   Opts.CodeCompleteOpts.IncludeCodePatterns
914     = Args.hasArg(OPT_code_completion_patterns);
915   Opts.CodeCompleteOpts.IncludeGlobals
916     = !Args.hasArg(OPT_no_code_completion_globals);
917   Opts.CodeCompleteOpts.IncludeBriefComments
918     = Args.hasArg(OPT_code_completion_brief_comments);
919 
920   Opts.OverrideRecordLayoutsFile
921     = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
922   if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
923                                      OPT_arcmt_modify,
924                                      OPT_arcmt_migrate)) {
925     switch (A->getOption().getID()) {
926     default:
927       llvm_unreachable("missed a case");
928     case OPT_arcmt_check:
929       Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
930       break;
931     case OPT_arcmt_modify:
932       Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
933       break;
934     case OPT_arcmt_migrate:
935       Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
936       break;
937     }
938   }
939   Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
940   Opts.ARCMTMigrateReportOut
941     = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
942   Opts.ARCMTMigrateEmitARCErrors
943     = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
944 
945   if (Args.hasArg(OPT_objcmt_migrate_literals))
946     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
947   if (Args.hasArg(OPT_objcmt_migrate_subscripting))
948     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
949   if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
950     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
951   if (Args.hasArg(OPT_objcmt_migrate_property))
952     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
953   if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
954     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
955   if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
956     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
957   if (Args.hasArg(OPT_objcmt_migrate_annotation))
958     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
959   if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
960     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
961   if (Args.hasArg(OPT_objcmt_migrate_instancetype))
962     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
963   if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
964     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
965   if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
966     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
967   if (Args.hasArg(OPT_objcmt_atomic_property))
968     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
969   if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
970     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
971   if (Args.hasArg(OPT_objcmt_migrate_designated_init))
972     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
973   if (Args.hasArg(OPT_objcmt_migrate_all))
974     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
975 
976   Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
977 
978   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
979       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
980     Diags.Report(diag::err_drv_argument_not_allowed_with)
981       << "ARC migration" << "ObjC migration";
982   }
983 
984   InputKind DashX = IK_None;
985   if (const Arg *A = Args.getLastArg(OPT_x)) {
986     DashX = llvm::StringSwitch<InputKind>(A->getValue())
987       .Case("c", IK_C)
988       .Case("cl", IK_OpenCL)
989       .Case("cuda", IK_CUDA)
990       .Case("c++", IK_CXX)
991       .Case("objective-c", IK_ObjC)
992       .Case("objective-c++", IK_ObjCXX)
993       .Case("cpp-output", IK_PreprocessedC)
994       .Case("assembler-with-cpp", IK_Asm)
995       .Case("c++-cpp-output", IK_PreprocessedCXX)
996       .Case("cuda-cpp-output", IK_PreprocessedCuda)
997       .Case("objective-c-cpp-output", IK_PreprocessedObjC)
998       .Case("objc-cpp-output", IK_PreprocessedObjC)
999       .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX)
1000       .Case("objc++-cpp-output", IK_PreprocessedObjCXX)
1001       .Case("c-header", IK_C)
1002       .Case("cl-header", IK_OpenCL)
1003       .Case("objective-c-header", IK_ObjC)
1004       .Case("c++-header", IK_CXX)
1005       .Case("objective-c++-header", IK_ObjCXX)
1006       .Cases("ast", "pcm", IK_AST)
1007       .Case("ir", IK_LLVM_IR)
1008       .Default(IK_None);
1009     if (DashX == IK_None)
1010       Diags.Report(diag::err_drv_invalid_value)
1011         << A->getAsString(Args) << A->getValue();
1012   }
1013 
1014   // '-' is the default input if none is given.
1015   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1016   Opts.Inputs.clear();
1017   if (Inputs.empty())
1018     Inputs.push_back("-");
1019   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1020     InputKind IK = DashX;
1021     if (IK == IK_None) {
1022       IK = FrontendOptions::getInputKindForExtension(
1023         StringRef(Inputs[i]).rsplit('.').second);
1024       // FIXME: Remove this hack.
1025       if (i == 0)
1026         DashX = IK;
1027     }
1028     Opts.Inputs.push_back(FrontendInputFile(Inputs[i], IK));
1029   }
1030 
1031   return DashX;
1032 }
1033 
GetResourcesPath(const char * Argv0,void * MainAddr)1034 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1035                                                  void *MainAddr) {
1036   std::string ClangExecutable =
1037       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1038   StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
1039 
1040   // Compute the path to the resource directory.
1041   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1042   SmallString<128> P(Dir);
1043   if (ClangResourceDir != "") {
1044     llvm::sys::path::append(P, ClangResourceDir);
1045   } else {
1046     StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
1047     llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
1048                             CLANG_VERSION_STRING);
1049   }
1050 
1051   return P.str();
1052 }
1053 
ParseHeaderSearchArgs(HeaderSearchOptions & Opts,ArgList & Args)1054 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args) {
1055   using namespace options;
1056   Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
1057   Opts.Verbose = Args.hasArg(OPT_v);
1058   Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
1059   Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
1060   Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
1061   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1062     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1063   Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
1064   Opts.ModuleCachePath = Args.getLastArgValue(OPT_fmodules_cache_path);
1065   Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
1066   Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
1067   // -fmodules implies -fmodule-maps
1068   Opts.ModuleMaps = Args.hasArg(OPT_fmodule_maps) || Args.hasArg(OPT_fmodules);
1069   Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
1070   Opts.ModuleCachePruneInterval =
1071       getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1072   Opts.ModuleCachePruneAfter =
1073       getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
1074   Opts.ModulesValidateOncePerBuildSession =
1075       Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1076   Opts.BuildSessionTimestamp =
1077       getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
1078   Opts.ModulesValidateSystemHeaders =
1079       Args.hasArg(OPT_fmodules_validate_system_headers);
1080 
1081   for (arg_iterator it = Args.filtered_begin(OPT_fmodules_ignore_macro),
1082                     ie = Args.filtered_end();
1083        it != ie; ++it) {
1084     StringRef MacroDef = (*it)->getValue();
1085     Opts.ModulesIgnoreMacros.insert(MacroDef.split('=').first);
1086   }
1087 
1088   // Add -I..., -F..., and -index-header-map options in order.
1089   bool IsIndexHeaderMap = false;
1090   for (arg_iterator it = Args.filtered_begin(OPT_I, OPT_F,
1091                                              OPT_index_header_map),
1092        ie = Args.filtered_end(); it != ie; ++it) {
1093     if ((*it)->getOption().matches(OPT_index_header_map)) {
1094       // -index-header-map applies to the next -I or -F.
1095       IsIndexHeaderMap = true;
1096       continue;
1097     }
1098 
1099     frontend::IncludeDirGroup Group
1100       = IsIndexHeaderMap? frontend::IndexHeaderMap : frontend::Angled;
1101 
1102     Opts.AddPath((*it)->getValue(), Group,
1103                  /*IsFramework=*/ (*it)->getOption().matches(OPT_F), true);
1104     IsIndexHeaderMap = false;
1105   }
1106 
1107   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
1108   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1109   for (arg_iterator it = Args.filtered_begin(OPT_iprefix, OPT_iwithprefix,
1110                                              OPT_iwithprefixbefore),
1111          ie = Args.filtered_end(); it != ie; ++it) {
1112     const Arg *A = *it;
1113     if (A->getOption().matches(OPT_iprefix))
1114       Prefix = A->getValue();
1115     else if (A->getOption().matches(OPT_iwithprefix))
1116       Opts.AddPath(Prefix.str() + A->getValue(),
1117                    frontend::After, false, true);
1118     else
1119       Opts.AddPath(Prefix.str() + A->getValue(),
1120                    frontend::Angled, false, true);
1121   }
1122 
1123   for (arg_iterator it = Args.filtered_begin(OPT_idirafter),
1124          ie = Args.filtered_end(); it != ie; ++it)
1125     Opts.AddPath((*it)->getValue(), frontend::After, false, true);
1126   for (arg_iterator it = Args.filtered_begin(OPT_iquote),
1127          ie = Args.filtered_end(); it != ie; ++it)
1128     Opts.AddPath((*it)->getValue(), frontend::Quoted, false, true);
1129   for (arg_iterator it = Args.filtered_begin(OPT_isystem,
1130          OPT_iwithsysroot), ie = Args.filtered_end(); it != ie; ++it)
1131     Opts.AddPath((*it)->getValue(), frontend::System, false,
1132                  !(*it)->getOption().matches(OPT_iwithsysroot));
1133   for (arg_iterator it = Args.filtered_begin(OPT_iframework),
1134          ie = Args.filtered_end(); it != ie; ++it)
1135     Opts.AddPath((*it)->getValue(), frontend::System, true, true);
1136 
1137   // Add the paths for the various language specific isystem flags.
1138   for (arg_iterator it = Args.filtered_begin(OPT_c_isystem),
1139        ie = Args.filtered_end(); it != ie; ++it)
1140     Opts.AddPath((*it)->getValue(), frontend::CSystem, false, true);
1141   for (arg_iterator it = Args.filtered_begin(OPT_cxx_isystem),
1142        ie = Args.filtered_end(); it != ie; ++it)
1143     Opts.AddPath((*it)->getValue(), frontend::CXXSystem, false, true);
1144   for (arg_iterator it = Args.filtered_begin(OPT_objc_isystem),
1145        ie = Args.filtered_end(); it != ie; ++it)
1146     Opts.AddPath((*it)->getValue(), frontend::ObjCSystem, false,true);
1147   for (arg_iterator it = Args.filtered_begin(OPT_objcxx_isystem),
1148        ie = Args.filtered_end(); it != ie; ++it)
1149     Opts.AddPath((*it)->getValue(), frontend::ObjCXXSystem, false, true);
1150 
1151   // Add the internal paths from a driver that detects standard include paths.
1152   for (arg_iterator I = Args.filtered_begin(OPT_internal_isystem,
1153                                             OPT_internal_externc_isystem),
1154                     E = Args.filtered_end();
1155        I != E; ++I) {
1156     frontend::IncludeDirGroup Group = frontend::System;
1157     if ((*I)->getOption().matches(OPT_internal_externc_isystem))
1158       Group = frontend::ExternCSystem;
1159     Opts.AddPath((*I)->getValue(), Group, false, true);
1160   }
1161 
1162   // Add the path prefixes which are implicitly treated as being system headers.
1163   for (arg_iterator I = Args.filtered_begin(OPT_system_header_prefix,
1164                                             OPT_no_system_header_prefix),
1165                     E = Args.filtered_end();
1166        I != E; ++I)
1167     Opts.AddSystemHeaderPrefix(
1168         (*I)->getValue(), (*I)->getOption().matches(OPT_system_header_prefix));
1169 
1170   for (arg_iterator I = Args.filtered_begin(OPT_ivfsoverlay),
1171        E = Args.filtered_end(); I != E; ++I)
1172     Opts.AddVFSOverlayFile((*I)->getValue());
1173 }
1174 
setLangDefaults(LangOptions & Opts,InputKind IK,LangStandard::Kind LangStd)1175 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1176                                          LangStandard::Kind LangStd) {
1177   // Set some properties which depend solely on the input kind; it would be nice
1178   // to move these to the language standard, and have the driver resolve the
1179   // input kind + language standard.
1180   if (IK == IK_Asm) {
1181     Opts.AsmPreprocessor = 1;
1182   } else if (IK == IK_ObjC ||
1183              IK == IK_ObjCXX ||
1184              IK == IK_PreprocessedObjC ||
1185              IK == IK_PreprocessedObjCXX) {
1186     Opts.ObjC1 = Opts.ObjC2 = 1;
1187   }
1188 
1189   if (LangStd == LangStandard::lang_unspecified) {
1190     // Based on the base language, pick one.
1191     switch (IK) {
1192     case IK_None:
1193     case IK_AST:
1194     case IK_LLVM_IR:
1195       llvm_unreachable("Invalid input kind!");
1196     case IK_OpenCL:
1197       LangStd = LangStandard::lang_opencl;
1198       break;
1199     case IK_CUDA:
1200     case IK_PreprocessedCuda:
1201       LangStd = LangStandard::lang_cuda;
1202       break;
1203     case IK_Asm:
1204     case IK_C:
1205     case IK_PreprocessedC:
1206     case IK_ObjC:
1207     case IK_PreprocessedObjC:
1208       LangStd = LangStandard::lang_gnu11;
1209       break;
1210     case IK_CXX:
1211     case IK_PreprocessedCXX:
1212     case IK_ObjCXX:
1213     case IK_PreprocessedObjCXX:
1214       LangStd = LangStandard::lang_gnucxx98;
1215       break;
1216     }
1217   }
1218 
1219   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1220   Opts.LineComment = Std.hasLineComments();
1221   Opts.C99 = Std.isC99();
1222   Opts.C11 = Std.isC11();
1223   Opts.CPlusPlus = Std.isCPlusPlus();
1224   Opts.CPlusPlus11 = Std.isCPlusPlus11();
1225   Opts.CPlusPlus14 = Std.isCPlusPlus14();
1226   Opts.CPlusPlus1z = Std.isCPlusPlus1z();
1227   Opts.Digraphs = Std.hasDigraphs();
1228   Opts.GNUMode = Std.isGNUMode();
1229   Opts.GNUInline = !Std.isC99();
1230   Opts.HexFloats = Std.hasHexFloats();
1231   Opts.ImplicitInt = Std.hasImplicitInt();
1232 
1233   // Set OpenCL Version.
1234   Opts.OpenCL = LangStd == LangStandard::lang_opencl || IK == IK_OpenCL;
1235   if (LangStd == LangStandard::lang_opencl)
1236     Opts.OpenCLVersion = 100;
1237   else if (LangStd == LangStandard::lang_opencl11)
1238     Opts.OpenCLVersion = 110;
1239   else if (LangStd == LangStandard::lang_opencl12)
1240     Opts.OpenCLVersion = 120;
1241   else if (LangStd == LangStandard::lang_opencl20)
1242     Opts.OpenCLVersion = 200;
1243 
1244   // OpenCL has some additional defaults.
1245   if (Opts.OpenCL) {
1246     Opts.AltiVec = 0;
1247     Opts.CXXOperatorNames = 1;
1248     Opts.LaxVectorConversions = 0;
1249     Opts.DefaultFPContract = 1;
1250     Opts.NativeHalfType = 1;
1251   }
1252 
1253   Opts.CUDA = IK == IK_CUDA || IK == IK_PreprocessedCuda ||
1254               LangStd == LangStandard::lang_cuda;
1255 
1256   // OpenCL and C++ both have bool, true, false keywords.
1257   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1258 
1259   // OpenCL has half keyword
1260   Opts.Half = Opts.OpenCL;
1261 
1262   // C++ has wchar_t keyword.
1263   Opts.WChar = Opts.CPlusPlus;
1264 
1265   Opts.GNUKeywords = Opts.GNUMode;
1266   Opts.CXXOperatorNames = Opts.CPlusPlus;
1267 
1268   Opts.DollarIdents = !Opts.AsmPreprocessor;
1269 }
1270 
1271 /// Attempt to parse a visibility value out of the given argument.
parseVisibility(Arg * arg,ArgList & args,DiagnosticsEngine & diags)1272 static Visibility parseVisibility(Arg *arg, ArgList &args,
1273                                   DiagnosticsEngine &diags) {
1274   StringRef value = arg->getValue();
1275   if (value == "default") {
1276     return DefaultVisibility;
1277   } else if (value == "hidden") {
1278     return HiddenVisibility;
1279   } else if (value == "protected") {
1280     // FIXME: diagnose if target does not support protected visibility
1281     return ProtectedVisibility;
1282   }
1283 
1284   diags.Report(diag::err_drv_invalid_value)
1285     << arg->getAsString(args) << value;
1286   return DefaultVisibility;
1287 }
1288 
ParseLangArgs(LangOptions & Opts,ArgList & Args,InputKind IK,DiagnosticsEngine & Diags)1289 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
1290                           DiagnosticsEngine &Diags) {
1291   // FIXME: Cleanup per-file based stuff.
1292   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
1293   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
1294     LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1295 #define LANGSTANDARD(id, name, desc, features) \
1296       .Case(name, LangStandard::lang_##id)
1297 #include "clang/Frontend/LangStandards.def"
1298       .Default(LangStandard::lang_unspecified);
1299     if (LangStd == LangStandard::lang_unspecified)
1300       Diags.Report(diag::err_drv_invalid_value)
1301         << A->getAsString(Args) << A->getValue();
1302     else {
1303       // Valid standard, check to make sure language and standard are
1304       // compatible.
1305       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1306       switch (IK) {
1307       case IK_C:
1308       case IK_ObjC:
1309       case IK_PreprocessedC:
1310       case IK_PreprocessedObjC:
1311         if (!(Std.isC89() || Std.isC99()))
1312           Diags.Report(diag::err_drv_argument_not_allowed_with)
1313             << A->getAsString(Args) << "C/ObjC";
1314         break;
1315       case IK_CXX:
1316       case IK_ObjCXX:
1317       case IK_PreprocessedCXX:
1318       case IK_PreprocessedObjCXX:
1319         if (!Std.isCPlusPlus())
1320           Diags.Report(diag::err_drv_argument_not_allowed_with)
1321             << A->getAsString(Args) << "C++/ObjC++";
1322         break;
1323       case IK_OpenCL:
1324         if (!Std.isC99())
1325           Diags.Report(diag::err_drv_argument_not_allowed_with)
1326             << A->getAsString(Args) << "OpenCL";
1327         break;
1328       case IK_CUDA:
1329       case IK_PreprocessedCuda:
1330         if (!Std.isCPlusPlus())
1331           Diags.Report(diag::err_drv_argument_not_allowed_with)
1332             << A->getAsString(Args) << "CUDA";
1333         break;
1334       default:
1335         break;
1336       }
1337     }
1338   }
1339 
1340   // -cl-std only applies for OpenCL language standards.
1341   // Override the -std option in this case.
1342   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
1343     LangStandard::Kind OpenCLLangStd
1344     = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1345     .Case("CL", LangStandard::lang_opencl)
1346     .Case("CL1.1", LangStandard::lang_opencl11)
1347     .Case("CL1.2", LangStandard::lang_opencl12)
1348     .Case("CL2.0", LangStandard::lang_opencl20)
1349     .Default(LangStandard::lang_unspecified);
1350 
1351     if (OpenCLLangStd == LangStandard::lang_unspecified) {
1352       Diags.Report(diag::err_drv_invalid_value)
1353       << A->getAsString(Args) << A->getValue();
1354     }
1355     else
1356       LangStd = OpenCLLangStd;
1357   }
1358 
1359   CompilerInvocation::setLangDefaults(Opts, IK, LangStd);
1360 
1361   // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
1362   // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
1363   // while a subset (the non-C++ GNU keywords) is provided by GCC's
1364   // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
1365   // name, as it doesn't seem a useful distinction.
1366   Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
1367                                   Opts.GNUKeywords);
1368 
1369   if (Args.hasArg(OPT_fno_operator_names))
1370     Opts.CXXOperatorNames = 0;
1371 
1372   if (Args.hasArg(OPT_fcuda_is_device))
1373     Opts.CUDAIsDevice = 1;
1374 
1375   if (Args.hasArg(OPT_fcuda_allow_host_calls_from_host_device))
1376     Opts.CUDAAllowHostCallsFromHostDevice = 1;
1377 
1378   if (Args.hasArg(OPT_fcuda_disable_target_call_checks))
1379     Opts.CUDADisableTargetCallChecks = 1;
1380 
1381   if (Opts.ObjC1) {
1382     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
1383       StringRef value = arg->getValue();
1384       if (Opts.ObjCRuntime.tryParse(value))
1385         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
1386     }
1387 
1388     if (Args.hasArg(OPT_fobjc_gc_only))
1389       Opts.setGC(LangOptions::GCOnly);
1390     else if (Args.hasArg(OPT_fobjc_gc))
1391       Opts.setGC(LangOptions::HybridGC);
1392     else if (Args.hasArg(OPT_fobjc_arc)) {
1393       Opts.ObjCAutoRefCount = 1;
1394       if (!Opts.ObjCRuntime.allowsARC())
1395         Diags.Report(diag::err_arc_unsupported_on_runtime);
1396 
1397       // Only set ObjCARCWeak if ARC is enabled.
1398       if (Args.hasArg(OPT_fobjc_runtime_has_weak))
1399         Opts.ObjCARCWeak = 1;
1400       else
1401         Opts.ObjCARCWeak = Opts.ObjCRuntime.allowsWeak();
1402     }
1403 
1404     if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
1405       Opts.ObjCInferRelatedResultType = 0;
1406 
1407     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
1408       Opts.ObjCSubscriptingLegacyRuntime =
1409         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
1410   }
1411 
1412   if (Args.hasArg(OPT_fgnu89_inline))
1413     Opts.GNUInline = 1;
1414 
1415   if (Args.hasArg(OPT_fapple_kext)) {
1416     if (!Opts.CPlusPlus)
1417       Diags.Report(diag::warn_c_kext);
1418     else
1419       Opts.AppleKext = 1;
1420   }
1421 
1422   if (Args.hasArg(OPT_print_ivar_layout))
1423     Opts.ObjCGCBitmapPrint = 1;
1424   if (Args.hasArg(OPT_fno_constant_cfstrings))
1425     Opts.NoConstantCFStrings = 1;
1426 
1427   if (Args.hasArg(OPT_faltivec))
1428     Opts.AltiVec = 1;
1429 
1430   if (Args.hasArg(OPT_pthread))
1431     Opts.POSIXThreads = 1;
1432 
1433   // The value-visibility mode defaults to "default".
1434   if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
1435     Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
1436   } else {
1437     Opts.setValueVisibilityMode(DefaultVisibility);
1438   }
1439 
1440   // The type-visibility mode defaults to the value-visibility mode.
1441   if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
1442     Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
1443   } else {
1444     Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
1445   }
1446 
1447   if (Args.hasArg(OPT_fvisibility_inlines_hidden))
1448     Opts.InlineVisibilityHidden = 1;
1449 
1450   if (Args.hasArg(OPT_ftrapv)) {
1451     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
1452     // Set the handler, if one is specified.
1453     Opts.OverflowHandler =
1454         Args.getLastArgValue(OPT_ftrapv_handler);
1455   }
1456   else if (Args.hasArg(OPT_fwrapv))
1457     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
1458 
1459   Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
1460   Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
1461   Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
1462   Opts.MSCompatibilityVersion = 0;
1463   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
1464     VersionTuple VT;
1465     if (VT.tryParse(A->getValue()))
1466       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1467                                                 << A->getValue();
1468     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
1469                                   VT.getMinor().getValueOr(0) * 100000 +
1470                                   VT.getSubminor().getValueOr(0);
1471   }
1472 
1473   // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
1474   // is specified, or -std is set to a conforming mode.
1475   // Trigraphs are disabled by default in c++1z onwards.
1476   Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus1z;
1477   Opts.Trigraphs =
1478       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
1479 
1480   Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
1481                                    OPT_fno_dollars_in_identifiers,
1482                                    Opts.DollarIdents);
1483   Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
1484   Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
1485   Opts.Borland = Args.hasArg(OPT_fborland_extensions);
1486   Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
1487   Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
1488                                    Opts.ConstStrings);
1489   if (Args.hasArg(OPT_fno_lax_vector_conversions))
1490     Opts.LaxVectorConversions = 0;
1491   if (Args.hasArg(OPT_fno_threadsafe_statics))
1492     Opts.ThreadsafeStatics = 0;
1493   Opts.Exceptions = Args.hasArg(OPT_fexceptions);
1494   Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
1495   Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
1496   Opts.SjLjExceptions = Args.hasArg(OPT_fsjlj_exceptions);
1497   Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
1498 
1499   Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
1500   Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
1501   Opts.Blocks = Args.hasArg(OPT_fblocks);
1502   Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
1503   Opts.Modules = Args.hasArg(OPT_fmodules);
1504   Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
1505   Opts.ModulesDeclUse =
1506       Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
1507   Opts.ModulesSearchAll = Opts.Modules &&
1508     !Args.hasArg(OPT_fno_modules_search_all) &&
1509     Args.hasArg(OPT_fmodules_search_all);
1510   Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
1511   Opts.ModulesImplicitMaps = Args.hasFlag(OPT_fmodules_implicit_maps,
1512                                           OPT_fno_modules_implicit_maps, true);
1513   Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
1514   Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
1515   Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
1516   Opts.ShortWChar = Args.hasFlag(OPT_fshort_wchar, OPT_fno_short_wchar, false);
1517   Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
1518   Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
1519   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
1520   Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
1521   Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
1522   Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
1523   Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
1524   Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
1525   Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
1526   Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
1527   Opts.InstantiationDepth =
1528       getLastArgIntValue(Args, OPT_ftemplate_depth, 256, Diags);
1529   Opts.ArrowDepth =
1530       getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
1531   Opts.ConstexprCallDepth =
1532       getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
1533   Opts.ConstexprStepLimit =
1534       getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
1535   Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
1536   Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
1537   Opts.NumLargeByValueCopy =
1538       getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
1539   Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
1540   Opts.ObjCConstantStringClass =
1541     Args.getLastArgValue(OPT_fconstant_string_class);
1542   Opts.ObjCDefaultSynthProperties =
1543     !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
1544   Opts.EncodeExtendedBlockSig =
1545     Args.hasArg(OPT_fencode_extended_block_signature);
1546   Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
1547   Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
1548   Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
1549   Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
1550   Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags);
1551   Opts.Static = Args.hasArg(OPT_static_define);
1552   Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
1553   Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
1554                         || Args.hasArg(OPT_fdump_record_layouts);
1555   Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
1556   Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
1557   Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
1558   Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
1559   Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
1560   Opts.MRTD = Args.hasArg(OPT_mrtd);
1561   Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
1562   Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
1563   Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
1564   Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
1565   Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
1566   Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
1567   Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
1568   Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name);
1569   Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
1570   Opts.ImplementationOfModule =
1571       Args.getLastArgValue(OPT_fmodule_implementation_of);
1572   Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
1573   Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
1574   Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns);
1575   Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
1576 
1577   if (!Opts.CurrentModule.empty() && !Opts.ImplementationOfModule.empty() &&
1578       Opts.CurrentModule != Opts.ImplementationOfModule) {
1579     Diags.Report(diag::err_conflicting_module_names)
1580         << Opts.CurrentModule << Opts.ImplementationOfModule;
1581   }
1582 
1583   if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
1584     switch (llvm::StringSwitch<unsigned>(A->getValue())
1585       .Case("target", LangOptions::ASMM_Target)
1586       .Case("no", LangOptions::ASMM_Off)
1587       .Case("yes", LangOptions::ASMM_On)
1588       .Default(255)) {
1589     default:
1590       Diags.Report(diag::err_drv_invalid_value)
1591         << "-faddress-space-map-mangling=" << A->getValue();
1592       break;
1593     case LangOptions::ASMM_Target:
1594       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
1595       break;
1596     case LangOptions::ASMM_On:
1597       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
1598       break;
1599     case LangOptions::ASMM_Off:
1600       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
1601       break;
1602     }
1603   }
1604 
1605   if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
1606     LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
1607         llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
1608             A->getValue())
1609             .Case("single",
1610                   LangOptions::PPTMK_FullGeneralitySingleInheritance)
1611             .Case("multiple",
1612                   LangOptions::PPTMK_FullGeneralityMultipleInheritance)
1613             .Case("virtual",
1614                   LangOptions::PPTMK_FullGeneralityVirtualInheritance)
1615             .Default(LangOptions::PPTMK_BestCase);
1616     if (InheritanceModel == LangOptions::PPTMK_BestCase)
1617       Diags.Report(diag::err_drv_invalid_value)
1618           << "-fms-memptr-rep=" << A->getValue();
1619 
1620     Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
1621   }
1622 
1623   // Check if -fopenmp= is specified.
1624   if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
1625     Opts.OpenMP = llvm::StringSwitch<bool>(A->getValue())
1626         .Case("libiomp5", true)
1627         .Default(false);
1628   }
1629 
1630   // Record whether the __DEPRECATED define was requested.
1631   Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
1632                                  OPT_fno_deprecated_macro,
1633                                  Opts.Deprecated);
1634 
1635   // FIXME: Eliminate this dependency.
1636   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
1637        OptSize = getOptimizationLevelSize(Args);
1638   Opts.Optimize = Opt != 0;
1639   Opts.OptimizeSize = OptSize != 0;
1640 
1641   // This is the __NO_INLINE__ define, which just depends on things like the
1642   // optimization level and -fno-inline, not actually whether the backend has
1643   // inlining enabled.
1644   Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline);
1645 
1646   Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
1647       Args.hasArg(OPT_cl_fast_relaxed_math);
1648   Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
1649       Args.hasArg(OPT_cl_finite_math_only) ||
1650       Args.hasArg(OPT_cl_fast_relaxed_math);
1651 
1652   Opts.RetainCommentsFromSystemHeaders =
1653       Args.hasArg(OPT_fretain_comments_from_system_headers);
1654 
1655   unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
1656   switch (SSP) {
1657   default:
1658     Diags.Report(diag::err_drv_invalid_value)
1659       << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
1660     break;
1661   case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
1662   case 1: Opts.setStackProtector(LangOptions::SSPOn);  break;
1663   case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
1664   case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
1665   }
1666 
1667   // Parse -fsanitize= arguments.
1668   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
1669                       Diags, Opts.Sanitize);
1670   // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
1671   Opts.SanitizeAddressFieldPadding =
1672       getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
1673   Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
1674 }
1675 
ParsePreprocessorArgs(PreprocessorOptions & Opts,ArgList & Args,FileManager & FileMgr,DiagnosticsEngine & Diags)1676 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
1677                                   FileManager &FileMgr,
1678                                   DiagnosticsEngine &Diags) {
1679   using namespace options;
1680   Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
1681   Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
1682   if (const Arg *A = Args.getLastArg(OPT_token_cache))
1683       Opts.TokenCache = A->getValue();
1684   else
1685     Opts.TokenCache = Opts.ImplicitPTHInclude;
1686   Opts.UsePredefines = !Args.hasArg(OPT_undef);
1687   Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
1688   Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
1689 
1690   Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
1691   for (arg_iterator it = Args.filtered_begin(OPT_error_on_deserialized_pch_decl),
1692          ie = Args.filtered_end(); it != ie; ++it) {
1693     const Arg *A = *it;
1694     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
1695   }
1696 
1697   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
1698     StringRef Value(A->getValue());
1699     size_t Comma = Value.find(',');
1700     unsigned Bytes = 0;
1701     unsigned EndOfLine = 0;
1702 
1703     if (Comma == StringRef::npos ||
1704         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
1705         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
1706       Diags.Report(diag::err_drv_preamble_format);
1707     else {
1708       Opts.PrecompiledPreambleBytes.first = Bytes;
1709       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
1710     }
1711   }
1712 
1713   // Add macros from the command line.
1714   for (arg_iterator it = Args.filtered_begin(OPT_D, OPT_U),
1715          ie = Args.filtered_end(); it != ie; ++it) {
1716     if ((*it)->getOption().matches(OPT_D))
1717       Opts.addMacroDef((*it)->getValue());
1718     else
1719       Opts.addMacroUndef((*it)->getValue());
1720   }
1721 
1722   Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
1723 
1724   // Add the ordered list of -includes.
1725   for (arg_iterator it = Args.filtered_begin(OPT_include),
1726          ie = Args.filtered_end(); it != ie; ++it) {
1727     const Arg *A = *it;
1728     Opts.Includes.push_back(A->getValue());
1729   }
1730 
1731   for (arg_iterator it = Args.filtered_begin(OPT_chain_include),
1732          ie = Args.filtered_end(); it != ie; ++it) {
1733     const Arg *A = *it;
1734     Opts.ChainedIncludes.push_back(A->getValue());
1735   }
1736 
1737   // Include 'altivec.h' if -faltivec option present
1738   if (Args.hasArg(OPT_faltivec))
1739     Opts.Includes.push_back("altivec.h");
1740 
1741   for (arg_iterator it = Args.filtered_begin(OPT_remap_file),
1742          ie = Args.filtered_end(); it != ie; ++it) {
1743     const Arg *A = *it;
1744     std::pair<StringRef,StringRef> Split =
1745       StringRef(A->getValue()).split(';');
1746 
1747     if (Split.second.empty()) {
1748       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
1749       continue;
1750     }
1751 
1752     Opts.addRemappedFile(Split.first, Split.second);
1753   }
1754 
1755   if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
1756     StringRef Name = A->getValue();
1757     unsigned Library = llvm::StringSwitch<unsigned>(Name)
1758       .Case("libc++", ARCXX_libcxx)
1759       .Case("libstdc++", ARCXX_libstdcxx)
1760       .Case("none", ARCXX_nolib)
1761       .Default(~0U);
1762     if (Library == ~0U)
1763       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1764     else
1765       Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
1766   }
1767 }
1768 
ParsePreprocessorOutputArgs(PreprocessorOutputOptions & Opts,ArgList & Args,frontend::ActionKind Action)1769 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
1770                                         ArgList &Args,
1771                                         frontend::ActionKind Action) {
1772   using namespace options;
1773 
1774   switch (Action) {
1775   case frontend::ASTDeclList:
1776   case frontend::ASTDump:
1777   case frontend::ASTPrint:
1778   case frontend::ASTView:
1779   case frontend::EmitAssembly:
1780   case frontend::EmitBC:
1781   case frontend::EmitHTML:
1782   case frontend::EmitLLVM:
1783   case frontend::EmitLLVMOnly:
1784   case frontend::EmitCodeGenOnly:
1785   case frontend::EmitObj:
1786   case frontend::FixIt:
1787   case frontend::GenerateModule:
1788   case frontend::GeneratePCH:
1789   case frontend::GeneratePTH:
1790   case frontend::ParseSyntaxOnly:
1791   case frontend::ModuleFileInfo:
1792   case frontend::VerifyPCH:
1793   case frontend::PluginAction:
1794   case frontend::PrintDeclContext:
1795   case frontend::RewriteObjC:
1796   case frontend::RewriteTest:
1797   case frontend::RunAnalysis:
1798   case frontend::MigrateSource:
1799     Opts.ShowCPP = 0;
1800     break;
1801 
1802   case frontend::DumpRawTokens:
1803   case frontend::DumpTokens:
1804   case frontend::InitOnly:
1805   case frontend::PrintPreamble:
1806   case frontend::PrintPreprocessedInput:
1807   case frontend::RewriteMacros:
1808   case frontend::RunPreprocessorOnly:
1809     Opts.ShowCPP = !Args.hasArg(OPT_dM);
1810     break;
1811   }
1812 
1813   Opts.ShowComments = Args.hasArg(OPT_C);
1814   Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
1815   Opts.ShowMacroComments = Args.hasArg(OPT_CC);
1816   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
1817   Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
1818   Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
1819 }
1820 
ParseTargetArgs(TargetOptions & Opts,ArgList & Args)1821 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) {
1822   using namespace options;
1823   Opts.ABI = Args.getLastArgValue(OPT_target_abi);
1824   Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
1825   Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
1826   Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
1827   Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
1828   Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
1829 
1830   // Use the default target triple if unspecified.
1831   if (Opts.Triple.empty())
1832     Opts.Triple = llvm::sys::getDefaultTargetTriple();
1833 }
1834 
CreateFromArgs(CompilerInvocation & Res,const char * const * ArgBegin,const char * const * ArgEnd,DiagnosticsEngine & Diags)1835 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
1836                                         const char *const *ArgBegin,
1837                                         const char *const *ArgEnd,
1838                                         DiagnosticsEngine &Diags) {
1839   bool Success = true;
1840 
1841   // Parse the arguments.
1842   std::unique_ptr<OptTable> Opts(createDriverOptTable());
1843   const unsigned IncludedFlagsBitmask = options::CC1Option;
1844   unsigned MissingArgIndex, MissingArgCount;
1845   std::unique_ptr<InputArgList> Args(
1846       Opts->ParseArgs(ArgBegin, ArgEnd, MissingArgIndex, MissingArgCount,
1847                       IncludedFlagsBitmask));
1848 
1849   // Check for missing argument error.
1850   if (MissingArgCount) {
1851     Diags.Report(diag::err_drv_missing_argument)
1852       << Args->getArgString(MissingArgIndex) << MissingArgCount;
1853     Success = false;
1854   }
1855 
1856   // Issue errors on unknown arguments.
1857   for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
1858          ie = Args->filtered_end(); it != ie; ++it) {
1859     Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Args);
1860     Success = false;
1861   }
1862 
1863   Success = ParseAnalyzerArgs(*Res.getAnalyzerOpts(), *Args, Diags) && Success;
1864   Success = ParseMigratorArgs(Res.getMigratorOpts(), *Args) && Success;
1865   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), *Args);
1866   Success = ParseDiagnosticArgs(Res.getDiagnosticOpts(), *Args, &Diags)
1867             && Success;
1868   ParseCommentArgs(Res.getLangOpts()->CommentOpts, *Args);
1869   ParseFileSystemArgs(Res.getFileSystemOpts(), *Args);
1870   // FIXME: We shouldn't have to pass the DashX option around here
1871   InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), *Args, Diags);
1872   ParseTargetArgs(Res.getTargetOpts(), *Args);
1873   Success = ParseCodeGenArgs(Res.getCodeGenOpts(), *Args, DashX, Diags,
1874                              Res.getTargetOpts()) && Success;
1875   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), *Args);
1876   if (DashX != IK_AST && DashX != IK_LLVM_IR) {
1877     ParseLangArgs(*Res.getLangOpts(), *Args, DashX, Diags);
1878     if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
1879       Res.getLangOpts()->ObjCExceptions = 1;
1880   }
1881   // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of
1882   // PCH file and find the original header name. Remove the need to do that in
1883   // ParsePreprocessorArgs and remove the FileManager
1884   // parameters from the function and the "FileManager.h" #include.
1885   FileManager FileMgr(Res.getFileSystemOpts());
1886   ParsePreprocessorArgs(Res.getPreprocessorOpts(), *Args, FileMgr, Diags);
1887   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), *Args,
1888                               Res.getFrontendOpts().ProgramAction);
1889   return Success;
1890 }
1891 
1892 namespace {
1893 
1894   class ModuleSignature {
1895     SmallVector<uint64_t, 16> Data;
1896     unsigned CurBit;
1897     uint64_t CurValue;
1898 
1899   public:
ModuleSignature()1900     ModuleSignature() : CurBit(0), CurValue(0) { }
1901 
1902     void add(uint64_t Value, unsigned Bits);
1903     void add(StringRef Value);
1904     void flush();
1905 
1906     llvm::APInt getAsInteger() const;
1907   };
1908 }
1909 
add(uint64_t Value,unsigned int NumBits)1910 void ModuleSignature::add(uint64_t Value, unsigned int NumBits) {
1911   CurValue |= Value << CurBit;
1912   if (CurBit + NumBits < 64) {
1913     CurBit += NumBits;
1914     return;
1915   }
1916 
1917   // Add the current word.
1918   Data.push_back(CurValue);
1919 
1920   if (CurBit)
1921     CurValue = Value >> (64-CurBit);
1922   else
1923     CurValue = 0;
1924   CurBit = (CurBit+NumBits) & 63;
1925 }
1926 
flush()1927 void ModuleSignature::flush() {
1928   if (CurBit == 0)
1929     return;
1930 
1931   Data.push_back(CurValue);
1932   CurBit = 0;
1933   CurValue = 0;
1934 }
1935 
add(StringRef Value)1936 void ModuleSignature::add(StringRef Value) {
1937   for (StringRef::iterator I = Value.begin(), IEnd = Value.end(); I != IEnd;++I)
1938     add(*I, 8);
1939 }
1940 
getAsInteger() const1941 llvm::APInt ModuleSignature::getAsInteger() const {
1942   return llvm::APInt(Data.size() * 64, Data);
1943 }
1944 
getModuleHash() const1945 std::string CompilerInvocation::getModuleHash() const {
1946   // Note: For QoI reasons, the things we use as a hash here should all be
1947   // dumped via the -module-info flag.
1948   using llvm::hash_code;
1949   using llvm::hash_value;
1950   using llvm::hash_combine;
1951 
1952   // Start the signature with the compiler version.
1953   // FIXME: We'd rather use something more cryptographically sound than
1954   // CityHash, but this will do for now.
1955   hash_code code = hash_value(getClangFullRepositoryVersion());
1956 
1957   // Extend the signature with the language options
1958 #define LANGOPT(Name, Bits, Default, Description) \
1959    code = hash_combine(code, LangOpts->Name);
1960 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1961   code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
1962 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
1963 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
1964 #include "clang/Basic/LangOptions.def"
1965 
1966   // Extend the signature with the target options.
1967   code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
1968                       TargetOpts->ABI);
1969   for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i)
1970     code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]);
1971 
1972   // Extend the signature with preprocessor options.
1973   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
1974   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
1975   code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
1976 
1977   for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
1978             I = getPreprocessorOpts().Macros.begin(),
1979          IEnd = getPreprocessorOpts().Macros.end();
1980        I != IEnd; ++I) {
1981     // If we're supposed to ignore this macro for the purposes of modules,
1982     // don't put it into the hash.
1983     if (!hsOpts.ModulesIgnoreMacros.empty()) {
1984       // Check whether we're ignoring this macro.
1985       StringRef MacroDef = I->first;
1986       if (hsOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first))
1987         continue;
1988     }
1989 
1990     code = hash_combine(code, I->first, I->second);
1991   }
1992 
1993   // Extend the signature with the sysroot.
1994   code = hash_combine(code, hsOpts.Sysroot, hsOpts.UseBuiltinIncludes,
1995                       hsOpts.UseStandardSystemIncludes,
1996                       hsOpts.UseStandardCXXIncludes,
1997                       hsOpts.UseLibcxx);
1998   code = hash_combine(code, hsOpts.ResourceDir);
1999 
2000   // Extend the signature with the user build path.
2001   code = hash_combine(code, hsOpts.ModuleUserBuildPath);
2002 
2003   // Darwin-specific hack: if we have a sysroot, use the contents and
2004   // modification time of
2005   //   $sysroot/System/Library/CoreServices/SystemVersion.plist
2006   // as part of the module hash.
2007   if (!hsOpts.Sysroot.empty()) {
2008     SmallString<128> systemVersionFile;
2009     systemVersionFile += hsOpts.Sysroot;
2010     llvm::sys::path::append(systemVersionFile, "System");
2011     llvm::sys::path::append(systemVersionFile, "Library");
2012     llvm::sys::path::append(systemVersionFile, "CoreServices");
2013     llvm::sys::path::append(systemVersionFile, "SystemVersion.plist");
2014 
2015     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
2016         llvm::MemoryBuffer::getFile(systemVersionFile);
2017     if (buffer) {
2018       code = hash_combine(code, buffer.get()->getBuffer());
2019 
2020       struct stat statBuf;
2021       if (stat(systemVersionFile.c_str(), &statBuf) == 0)
2022         code = hash_combine(code, statBuf.st_mtime);
2023     }
2024   }
2025 
2026   return llvm::APInt(64, code).toString(36, /*Signed=*/false);
2027 }
2028 
2029 namespace clang {
2030 
2031 template<typename IntTy>
getLastArgIntValueImpl(const ArgList & Args,OptSpecifier Id,IntTy Default,DiagnosticsEngine * Diags)2032 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
2033                                     IntTy Default,
2034                                     DiagnosticsEngine *Diags) {
2035   IntTy Res = Default;
2036   if (Arg *A = Args.getLastArg(Id)) {
2037     if (StringRef(A->getValue()).getAsInteger(10, Res)) {
2038       if (Diags)
2039         Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
2040                                                        << A->getValue();
2041     }
2042   }
2043   return Res;
2044 }
2045 
2046 
2047 // Declared in clang/Frontend/Utils.h.
getLastArgIntValue(const ArgList & Args,OptSpecifier Id,int Default,DiagnosticsEngine * Diags)2048 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
2049                        DiagnosticsEngine *Diags) {
2050   return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
2051 }
2052 
getLastArgUInt64Value(const ArgList & Args,OptSpecifier Id,uint64_t Default,DiagnosticsEngine * Diags)2053 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
2054                                uint64_t Default,
2055                                DiagnosticsEngine *Diags) {
2056   return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
2057 }
2058 
BuryPointer(const void * Ptr)2059 void BuryPointer(const void *Ptr) {
2060   // This function may be called only a small fixed amount of times per each
2061   // invocation, otherwise we do actually have a leak which we want to report.
2062   // If this function is called more than kGraveYardMaxSize times, the pointers
2063   // will not be properly buried and a leak detector will report a leak, which
2064   // is what we want in such case.
2065   static const size_t kGraveYardMaxSize = 16;
2066   LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
2067   static std::atomic<unsigned> GraveYardSize;
2068   unsigned Idx = GraveYardSize++;
2069   if (Idx >= kGraveYardMaxSize)
2070     return;
2071   GraveYard[Idx] = Ptr;
2072 }
2073 
2074 IntrusiveRefCntPtr<vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags)2075 createVFSFromCompilerInvocation(const CompilerInvocation &CI,
2076                                 DiagnosticsEngine &Diags) {
2077   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
2078     return vfs::getRealFileSystem();
2079 
2080   IntrusiveRefCntPtr<vfs::OverlayFileSystem>
2081     Overlay(new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
2082   // earlier vfs files are on the bottom
2083   for (const std::string &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
2084     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
2085         llvm::MemoryBuffer::getFile(File);
2086     if (!Buffer) {
2087       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
2088       return IntrusiveRefCntPtr<vfs::FileSystem>();
2089     }
2090 
2091     IntrusiveRefCntPtr<vfs::FileSystem> FS =
2092         vfs::getVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr);
2093     if (!FS.get()) {
2094       Diags.Report(diag::err_invalid_vfs_overlay) << File;
2095       return IntrusiveRefCntPtr<vfs::FileSystem>();
2096     }
2097     Overlay->pushOverlay(FS);
2098   }
2099   return Overlay;
2100 }
2101 } // end namespace clang
2102