blob: 46f8c9f235fcdfecac51ecccc39d9a119301ee38 [file] [log] [blame]
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001//===- CompilerInvocation.cpp ---------------------------------------------===//
Daniel Dunbar629f6bb2009-11-17 06:02:29 +00002//
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
Mehdi Amini9670f842016-07-18 19:02:11 +000010#include "clang/Frontend/CompilerInvocation.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011#include "TestModuleFileExtension.h"
Chad Rosier7dbc9cf2016-01-06 14:35:46 +000012#include "clang/Basic/Builtins.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000013#include "clang/Basic/CharInfo.h"
14#include "clang/Basic/CommentOptions.h"
15#include "clang/Basic/DebugInfoOptions.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticOptions.h"
18#include "clang/Basic/FileSystemOptions.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/ObjCRuntime.h"
22#include "clang/Basic/Sanitizers.h"
23#include "clang/Basic/SourceLocation.h"
24#include "clang/Basic/TargetOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Basic/Version.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000026#include "clang/Basic/VersionTuple.h"
27#include "clang/Basic/VirtualFileSystem.h"
28#include "clang/Basic/Visibility.h"
Dean Michael Berris488f7c22018-04-13 02:31:58 +000029#include "clang/Basic/XRayInstr.h"
Chandler Carruthfd3cc702014-12-29 12:09:08 +000030#include "clang/Config/config.h"
Daniel Dunbarc70c3932009-12-01 03:16:53 +000031#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Driver/Options.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000033#include "clang/Frontend/CodeGenOptions.h"
34#include "clang/Frontend/CommandLineSourceLoc.h"
35#include "clang/Frontend/DependencyOutputOptions.h"
Ben Langmuir8832c062014-04-15 18:16:25 +000036#include "clang/Frontend/FrontendDiagnostic.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000037#include "clang/Frontend/FrontendOptions.h"
Daniel Dunbarc70c3932009-12-01 03:16:53 +000038#include "clang/Frontend/LangStandard.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000039#include "clang/Frontend/MigratorOptions.h"
40#include "clang/Frontend/PreprocessorOutputOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000041#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "clang/Lex/HeaderSearchOptions.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000043#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000044#include "clang/Sema/CodeCompleteOptions.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000045#include "clang/Serialization/ModuleFileExtension.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000046#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
47#include "llvm/ADT/APInt.h"
48#include "llvm/ADT/ArrayRef.h"
49#include "llvm/ADT/CachedHashString.h"
Douglas Gregor7fd08492012-11-05 19:45:09 +000050#include "llvm/ADT/Hashing.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000051#include "llvm/ADT/None.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/SmallString.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000054#include "llvm/ADT/SmallVector.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000055#include "llvm/ADT/StringRef.h"
Daniel Dunbarc70c3932009-12-01 03:16:53 +000056#include "llvm/ADT/StringSwitch.h"
Duncan Sandsf610b5b2010-08-30 09:42:39 +000057#include "llvm/ADT/Triple.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000058#include "llvm/ADT/Twine.h"
Artem Belevich5d40ae32015-10-27 17:56:59 +000059#include "llvm/Linker/Linker.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000060#include "llvm/MC/MCTargetOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000061#include "llvm/Option/Arg.h"
62#include "llvm/Option/ArgList.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000063#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000064#include "llvm/Option/OptTable.h"
65#include "llvm/Option/Option.h"
Rong Xu9c6f1532016-03-02 20:59:36 +000066#include "llvm/ProfileData/InstrProfReader.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000067#include "llvm/Support/CodeGen.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000068#include "llvm/Support/Compiler.h"
69#include "llvm/Support/Error.h"
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000070#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000071#include "llvm/Support/ErrorOr.h"
Rafael Espindola9678d272013-06-26 05:03:40 +000072#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000073#include "llvm/Support/Host.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000074#include "llvm/Support/MathExtras.h"
75#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000076#include "llvm/Support/Path.h"
Nico Rieck7857d462013-09-11 00:38:02 +000077#include "llvm/Support/Process.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000078#include "llvm/Support/Regex.h"
79#include "llvm/Support/raw_ostream.h"
Renato Golin4854d802015-11-09 12:40:41 +000080#include "llvm/Target/TargetOptions.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000081#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000082#include <atomic>
Eugene Zelenko44357ee2018-03-26 21:45:04 +000083#include <cassert>
84#include <cstddef>
85#include <cstring>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000086#include <memory>
Eugene Zelenko44357ee2018-03-26 21:45:04 +000087#include <string>
88#include <tuple>
89#include <utility>
90#include <vector>
91
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000092using namespace clang;
Eugene Zelenko44357ee2018-03-26 21:45:04 +000093using namespace driver;
94using namespace options;
95using namespace llvm::opt;
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000096
Ted Kremenek8cf47df2011-11-17 23:01:24 +000097//===----------------------------------------------------------------------===//
98// Initialization.
99//===----------------------------------------------------------------------===//
100
Ted Kremenek2acedbd2011-11-18 04:32:13 +0000101CompilerInvocationBase::CompilerInvocationBase()
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000102 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
103 DiagnosticOpts(new DiagnosticOptions()),
104 HeaderSearchOpts(new HeaderSearchOptions()),
105 PreprocessorOpts(new PreprocessorOptions()) {}
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000106
Ted Kremenek2acedbd2011-11-18 04:32:13 +0000107CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
David Blaikieea4395e2017-01-06 19:49:01 +0000108 : LangOpts(new LangOptions(*X.getLangOpts())),
109 TargetOpts(new TargetOptions(X.getTargetOpts())),
110 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
111 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
112 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000113
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000114CompilerInvocationBase::~CompilerInvocationBase() = default;
Alp Tokerc7dc0622014-05-11 22:10:52 +0000115
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000116//===----------------------------------------------------------------------===//
Richard Smith33fd5512012-11-01 03:48:49 +0000117// Deserialization (from args)
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000118//===----------------------------------------------------------------------===//
119
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000120static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
David Blaikie9c902b52011-09-25 23:23:43 +0000121 DiagnosticsEngine &Diags) {
Peter Collingbourne31587c82010-12-04 01:50:45 +0000122 unsigned DefaultOpt = 0;
Richard Smith40c0efa2017-04-26 18:57:40 +0000123 if (IK.getLanguage() == InputKind::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
Peter Collingbourne31587c82010-12-04 01:50:45 +0000124 DefaultOpt = 2;
James Molloya3c85b82012-05-01 14:57:16 +0000125
126 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
127 if (A->getOption().matches(options::OPT_O0))
128 return 0;
129
Chad Rosier153d7c62013-04-10 21:26:02 +0000130 if (A->getOption().matches(options::OPT_Ofast))
131 return 3;
132
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000133 assert(A->getOption().matches(options::OPT_O));
James Molloya3c85b82012-05-01 14:57:16 +0000134
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000135 StringRef S(A->getValue());
James Molloya3c85b82012-05-01 14:57:16 +0000136 if (S == "s" || S == "z" || S.empty())
137 return 2;
138
Sylvestre Ledrud340ccc2016-11-11 17:29:56 +0000139 if (S == "g")
140 return 1;
141
Reid Kleckner898229a2013-06-14 17:17:23 +0000142 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
James Molloya3c85b82012-05-01 14:57:16 +0000143 }
144
145 return DefaultOpt;
146}
147
Chad Rosierf2d39642013-04-10 21:30:03 +0000148static unsigned getOptimizationLevelSize(ArgList &Args) {
James Molloya3c85b82012-05-01 14:57:16 +0000149 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
150 if (A->getOption().matches(options::OPT_O)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000151 switch (A->getValue()[0]) {
James Molloya3c85b82012-05-01 14:57:16 +0000152 default:
153 return 0;
154 case 's':
155 return 1;
156 case 'z':
157 return 2;
158 }
159 }
160 }
161 return 0;
162}
163
Richard Smith3be1cb22014-08-07 00:24:21 +0000164static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
165 OptSpecifier GroupWithValue,
166 std::vector<std::string> &Diagnostics) {
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000167 for (auto *A : Args.filtered(Group)) {
James Molloya3c85b82012-05-01 14:57:16 +0000168 if (A->getOption().getKind() == Option::FlagClass) {
Richard Smith3be1cb22014-08-07 00:24:21 +0000169 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
170 // its name (minus the "W" or "R" at the beginning) to the warning list.
171 Diagnostics.push_back(A->getOption().getName().drop_front(1));
172 } else if (A->getOption().matches(GroupWithValue)) {
173 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
174 Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
James Molloya3c85b82012-05-01 14:57:16 +0000175 } else {
Richard Smith3be1cb22014-08-07 00:24:21 +0000176 // Otherwise, add its value (for OPT_W_Joined and similar).
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000177 for (const auto *Arg : A->getValues())
Benjamin Kramer3204b152015-05-29 19:42:19 +0000178 Diagnostics.emplace_back(Arg);
James Molloya3c85b82012-05-01 14:57:16 +0000179 }
180 }
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000181}
182
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000183static void getAllNoBuiltinFuncValues(ArgList &Args,
184 std::vector<std::string> &Funcs) {
185 SmallVector<const char *, 8> Values;
186 for (const auto &Arg : Args) {
187 const Option &O = Arg->getOption();
188 if (O.matches(options::OPT_fno_builtin_)) {
189 const char *FuncName = Arg->getValue();
190 if (Builtin::Context::isBuiltinFunc(FuncName))
191 Values.push_back(FuncName);
192 }
193 }
194 Funcs.insert(Funcs.end(), Values.begin(), Values.end());
195}
196
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000197static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
David Blaikie9c902b52011-09-25 23:23:43 +0000198 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000199 bool Success = true;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000200 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000201 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000202 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
203#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
204 .Case(CMDFLAG, NAME##Model)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000205#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000206 .Default(NumStores);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000207 if (Value == NumStores) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000208 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000209 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000210 Success = false;
211 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000212 Opts.AnalysisStoreOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000213 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000214 }
215
216 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000217 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000218 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
219#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
220 .Case(CMDFLAG, NAME##Model)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000221#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000222 .Default(NumConstraints);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000223 if (Value == NumConstraints) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000224 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000225 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000226 Success = false;
227 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000228 Opts.AnalysisConstraintsOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000229 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000230 }
231
232 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000233 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000234 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
Jordan Rose367843a2013-08-16 01:06:30 +0000235#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000236 .Case(CMDFLAG, PD_##NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000237#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000238 .Default(NUM_ANALYSIS_DIAG_CLIENTS);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000239 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000240 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000241 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000242 Success = false;
243 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000244 Opts.AnalysisDiagOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000245 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000246 }
247
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000248 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000249 StringRef Name = A->getValue();
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000250 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
251#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
252 .Case(CMDFLAG, NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000253#include "clang/StaticAnalyzer/Core/Analyses.def"
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000254 .Default(NumPurgeModes);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000255 if (Value == NumPurgeModes) {
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000256 Diags.Report(diag::err_drv_invalid_value)
257 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000258 Success = false;
259 } else {
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000260 Opts.AnalysisPurgeOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000261 }
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000262 }
263
Anna Zaks0af3e062012-03-08 23:16:35 +0000264 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000265 StringRef Name = A->getValue();
Anna Zaks0af3e062012-03-08 23:16:35 +0000266 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
267#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
268 .Case(CMDFLAG, NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000269#include "clang/StaticAnalyzer/Core/Analyses.def"
Anna Zaks0af3e062012-03-08 23:16:35 +0000270 .Default(NumInliningModes);
271 if (Value == NumInliningModes) {
272 Diags.Report(diag::err_drv_invalid_value)
273 << A->getAsString(Args) << Name;
274 Success = false;
275 } else {
276 Opts.InliningMode = Value;
277 }
278 }
279
Argyrios Kyrtzidis17bee3e2011-02-25 00:09:51 +0000280 Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
Gabor Horvathc4309902016-08-08 13:41:04 +0000281 Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
Anna Zaksd5478fd2014-08-29 20:01:38 +0000282 Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
283
Ted Kremenekb8f8b352012-08-30 19:26:53 +0000284 Opts.visualizeExplodedGraphWithGraphViz =
285 Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
286 Opts.visualizeExplodedGraphWithUbiGraph =
287 Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
Anna Zaks72eee392012-03-28 19:59:16 +0000288 Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000289 Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
290 Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
Ted Kremenek68189912009-12-07 22:06:12 +0000291 Opts.AnalyzeNestedBlocks =
292 Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
Ted Kremenek6f5131f2012-08-30 19:26:48 +0000293 Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
Daniel Dunbar37300482010-05-20 16:54:55 +0000294 Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
Ted Kremenek4a2b2372010-08-03 00:09:51 +0000295 Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000296 Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
Reid Kleckner898229a2013-06-14 17:17:23 +0000297 Opts.maxBlockVisitOnPath =
298 getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
Anna Zaksb0286542012-02-27 21:33:16 +0000299 Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
Anna Zaks26508772012-03-02 19:05:03 +0000300 Opts.InlineMaxStackDepth =
Reid Kleckner898229a2013-06-14 17:17:23 +0000301 getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
302 Opts.InlineMaxStackDepth, Diags);
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000303
304 Opts.CheckersControlList.clear();
Sean Silva14facf32015-06-09 01:57:17 +0000305 for (const Arg *A :
306 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000307 A->claim();
308 bool enable = (A->getOption().getID() == OPT_analyzer_checker);
Argyrios Kyrtzidisc08d89e2011-02-24 08:42:20 +0000309 // We can have a list of comma separated checker names, e.g:
310 // '-analyzer-checker=cocoa,unix'
Richard Smithbd55daf2012-11-01 04:30:05 +0000311 StringRef checkerList = A->getValue();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000312 SmallVector<StringRef, 4> checkers;
Argyrios Kyrtzidisc08d89e2011-02-24 08:42:20 +0000313 checkerList.split(checkers, ",");
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000314 for (auto checker : checkers)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000315 Opts.CheckersControlList.emplace_back(checker, enable);
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000316 }
Jacques Pienaara50178c2015-02-24 21:45:33 +0000317
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000318 // Go through the analyzer configuration options.
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000319 for (const auto *A : Args.filtered(OPT_analyzer_config)) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000320 A->claim();
321 // We can have a list of comma separated config names, e.g:
Ted Kremenek53f3e7d2012-08-30 05:49:16 +0000322 // '-analyzer-config key1=val1,key2=val2'
Richard Smithbd55daf2012-11-01 04:30:05 +0000323 StringRef configList = A->getValue();
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000324 SmallVector<StringRef, 4> configVals;
325 configList.split(configVals, ",");
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000326 for (const auto &configVal : configVals) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000327 StringRef key, val;
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000328 std::tie(key, val) = configVal.split("=");
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000329 if (val.empty()) {
330 Diags.Report(SourceLocation(),
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000331 diag::err_analyzer_config_no_value) << configVal;
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000332 Success = false;
333 break;
334 }
Ted Kremenek53f3e7d2012-08-30 05:49:16 +0000335 if (val.find('=') != StringRef::npos) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000336 Diags.Report(SourceLocation(),
337 diag::err_analyzer_config_multiple_values)
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000338 << configVal;
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000339 Success = false;
340 break;
341 }
342 Opts.Config[key] = val;
343 }
344 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000345
George Karpenkov4a190fe2018-01-23 19:28:52 +0000346 llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000347 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
George Karpenkov4a190fe2018-01-23 19:28:52 +0000348 if (i != 0)
349 os << " ";
350 os << Args.getArgString(i);
351 }
352 os.flush();
353
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000354 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000355}
356
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000357static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
358 Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000359 Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000360 return true;
361}
362
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000363static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
364 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000365 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000366}
367
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000368static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
369 if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
370 StringRef Value = A->getValue();
371 if (Value == "small" || Value == "kernel" || Value == "medium" ||
372 Value == "large")
373 return Value;
374 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
375 }
376 return "default";
377}
378
Rafael Espindolae1d70532018-01-18 00:20:03 +0000379static llvm::Reloc::Model getRelocModel(ArgList &Args,
380 DiagnosticsEngine &Diags) {
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000381 if (Arg *A = Args.getLastArg(OPT_mrelocation_model)) {
382 StringRef Value = A->getValue();
Rafael Espindolae1d70532018-01-18 00:20:03 +0000383 auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(Value)
384 .Case("static", llvm::Reloc::Static)
385 .Case("pic", llvm::Reloc::PIC_)
386 .Case("ropi", llvm::Reloc::ROPI)
387 .Case("rwpi", llvm::Reloc::RWPI)
388 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
389 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
390 .Default(None);
391 if (RM.hasValue())
392 return *RM;
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000393 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
394 }
Rafael Espindolae1d70532018-01-18 00:20:03 +0000395 return llvm::Reloc::PIC_;
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000396}
397
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000398/// Create a new Regex instance out of the string value in \p RpassArg.
Diego Novillod23ec942014-05-29 19:55:06 +0000399/// It returns a pointer to the newly generated Regex instance.
400static std::shared_ptr<llvm::Regex>
401GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
402 Arg *RpassArg) {
403 StringRef Val = RpassArg->getValue();
404 std::string RegexError;
405 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
406 if (!Pattern->isValid(RegexError)) {
407 Diags.Report(diag::err_drv_optimization_remark_pattern)
408 << RegexError << RpassArg->getAsString(Args);
409 Pattern.reset();
410 }
411 return Pattern;
412}
413
Eric Fiselier098e6de2015-06-13 07:11:40 +0000414static bool parseDiagnosticLevelMask(StringRef FlagName,
415 const std::vector<std::string> &Levels,
416 DiagnosticsEngine *Diags,
417 DiagnosticLevelMask &M) {
418 bool Success = true;
419 for (const auto &Level : Levels) {
420 DiagnosticLevelMask const PM =
421 llvm::StringSwitch<DiagnosticLevelMask>(Level)
422 .Case("note", DiagnosticLevelMask::Note)
423 .Case("remark", DiagnosticLevelMask::Remark)
424 .Case("warning", DiagnosticLevelMask::Warning)
425 .Case("error", DiagnosticLevelMask::Error)
426 .Default(DiagnosticLevelMask::None);
427 if (PM == DiagnosticLevelMask::None) {
428 Success = false;
429 if (Diags)
430 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
431 }
432 M = M | PM;
433 }
434 return Success;
435}
436
Alexey Samsonov88459522015-01-12 22:39:12 +0000437static void parseSanitizerKinds(StringRef FlagName,
438 const std::vector<std::string> &Sanitizers,
439 DiagnosticsEngine &Diags, SanitizerSet &S) {
440 for (const auto &Sanitizer : Sanitizers) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000441 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000442 if (K == 0)
Alexey Samsonov88459522015-01-12 22:39:12 +0000443 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
444 else
445 S.set(K, true);
446 }
447}
448
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000449static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
450 ArgList &Args, DiagnosticsEngine &D,
451 XRayInstrSet &S) {
452 llvm::SmallVector<StringRef, 2> BundleParts;
453 llvm::SplitString(Bundle, BundleParts, ",");
454 for (const auto B : BundleParts) {
455 auto Mask = parseXRayInstrValue(B);
456 if (Mask == XRayInstrKind::None)
457 if (B != "none")
458 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
459 else
460 S.Mask = Mask;
461 else if (Mask == XRayInstrKind::All)
462 S.Mask = Mask;
463 else
464 S.set(Mask, true);
465 }
466}
467
Rong Xu9c6f1532016-03-02 20:59:36 +0000468// Set the profile kind for fprofile-instrument.
469static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
470 DiagnosticsEngine &Diags) {
471 Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
472 if (A == nullptr)
473 return;
474 StringRef S = A->getValue();
475 unsigned I = llvm::StringSwitch<unsigned>(S)
476 .Case("none", CodeGenOptions::ProfileNone)
477 .Case("clang", CodeGenOptions::ProfileClangInstr)
478 .Case("llvm", CodeGenOptions::ProfileIRInstr)
479 .Default(~0U);
480 if (I == ~0U) {
481 Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
482 << S;
483 return;
484 }
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000485 auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I);
Rong Xu9c6f1532016-03-02 20:59:36 +0000486 Opts.setProfileInstr(Instrumentor);
487}
488
489// Set the profile kind using fprofile-instrument-use-path.
490static void setPGOUseInstrumentor(CodeGenOptions &Opts,
Benjamin Kramer442b9a92016-05-29 11:04:56 +0000491 const Twine &ProfileName) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000492 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
493 // In error, return silently and let Clang PGOUse report the error message.
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000494 if (auto E = ReaderOrErr.takeError()) {
495 llvm::consumeError(std::move(E));
Rong Xu9c6f1532016-03-02 20:59:36 +0000496 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
497 return;
498 }
499 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
500 std::move(ReaderOrErr.get());
501 if (PGOReader->isIRLevelProfile())
502 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
503 else
504 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
505}
506
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000507static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Adrian Prantla7634472014-01-07 01:19:08 +0000508 DiagnosticsEngine &Diags,
Teresa Johnson9e4321c2018-04-17 16:39:25 +0000509 const TargetOptions &TargetOpts,
510 const FrontendOptions &FrontendOpts) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000511 bool Success = true;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000512 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000513
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000514 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
Sylvestre Ledru5abf2ec2013-11-18 13:23:07 +0000515 // TODO: This could be done in Driver
516 unsigned MaxOptLevel = 3;
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000517 if (OptimizationLevel > MaxOptLevel) {
518 // If the optimization level is not supported, fall back on the default
519 // optimization
Sylvestre Ledru5abf2ec2013-11-18 13:23:07 +0000520 Diags.Report(diag::warn_drv_optimization_value)
521 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000522 OptimizationLevel = MaxOptLevel;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000523 }
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000524 Opts.OptimizationLevel = OptimizationLevel;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000525
Chandler Carruthfcd33142016-12-23 01:24:49 +0000526 // At O0 we want to fully disable inlining outside of cases marked with
527 // 'alwaysinline' that are required for correctness.
528 Opts.setInlining((Opts.OptimizationLevel == 0)
529 ? CodeGenOptions::OnlyAlwaysInlining
530 : CodeGenOptions::NormalInlining);
531 // Explicit inlining flags can disable some or all inlining even at
532 // optimization levels above zero.
533 if (Arg *InlineArg = Args.getLastArg(
534 options::OPT_finline_functions, options::OPT_finline_hint_functions,
535 options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
536 if (Opts.OptimizationLevel > 0) {
537 const Option &InlineOpt = InlineArg->getOption();
538 if (InlineOpt.matches(options::OPT_finline_functions))
539 Opts.setInlining(CodeGenOptions::NormalInlining);
540 else if (InlineOpt.matches(options::OPT_finline_hint_functions))
541 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
542 else
543 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
544 }
Hans Wennborg7a008882016-05-24 20:40:51 +0000545 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000546
Chandler Carruth50f9e892016-12-23 20:44:01 +0000547 Opts.ExperimentalNewPassManager = Args.hasFlag(
548 OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager,
Petr Hosekc3aa97a2018-04-06 00:53:00 +0000549 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000550
Tim Shenb13eebe2017-06-29 23:10:13 +0000551 Opts.DebugPassManager =
552 Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager,
553 /* Default */ false);
554
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000555 if (Arg *A = Args.getLastArg(OPT_fveclib)) {
556 StringRef Name = A->getValue();
557 if (Name == "Accelerate")
558 Opts.setVecLib(CodeGenOptions::Accelerate);
Matt Masten6731dea2016-07-29 16:44:24 +0000559 else if (Name == "SVML")
560 Opts.setVecLib(CodeGenOptions::SVML);
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000561 else if (Name == "none")
562 Opts.setVecLib(CodeGenOptions::NoLibrary);
563 else
564 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
565 }
566
Douglas Katzman3459ce22015-10-08 04:24:12 +0000567 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000568 unsigned Val =
569 llvm::StringSwitch<unsigned>(A->getValue())
Benjamin Kramer8c305922016-02-02 11:06:51 +0000570 .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
571 .Case("limited", codegenoptions::LimitedDebugInfo)
572 .Case("standalone", codegenoptions::FullDebugInfo)
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000573 .Default(~0U);
574 if (Val == ~0U)
575 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
576 << A->getValue();
577 else
Benjamin Kramer8c305922016-02-02 11:06:51 +0000578 Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000579 }
Paul Robinson45784a72015-12-19 02:24:10 +0000580 if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000581 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
Paul Robinson9ef13db2016-02-05 23:23:25 +0000582 .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
583 .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
584 .Case("sce", unsigned(llvm::DebuggerKind::SCE))
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000585 .Default(~0U);
586 if (Val == ~0U)
587 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
588 << A->getValue();
589 else
Paul Robinson9ef13db2016-02-05 23:23:25 +0000590 Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
Paul Robinson45784a72015-12-19 02:24:10 +0000591 }
Douglas Katzman3459ce22015-10-08 04:24:12 +0000592 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
Eric Christophera2f7eb72012-10-18 21:52:18 +0000593 Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
Douglas Katzman3459ce22015-10-08 04:24:12 +0000594 Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
Amjad Aboud546bc112017-02-09 22:07:24 +0000595 Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
Peter Collingbournefb532b92016-02-24 20:46:36 +0000596 Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000597 Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
David Blaikie81503552017-04-21 23:35:36 +0000598 Opts.EnableSplitDwarf = Args.hasArg(OPT_enable_split_dwarf);
Eric Christopherf1545832013-02-22 23:50:16 +0000599 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
David Blaikiea45c31a2016-08-24 18:29:58 +0000600 Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000601 Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
Paul Robinsona8280812017-09-29 21:25:07 +0000602 Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
Paul Robinson1787f812017-09-28 18:37:02 +0000603 Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
Scott Lindera2fbcef2018-02-26 17:32:31 +0000604 Opts.EmbedSource = Args.hasArg(OPT_gembed_source);
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000605
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000606 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
607 Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
608
Duncan P. N. Exon Smithbb618252015-04-15 01:16:18 +0000609 if (const Arg *A =
610 Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
611 Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
612
Steven Wu546a1962015-07-17 20:09:56 +0000613 Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
Mehdi Amini7f873072017-01-06 23:18:09 +0000614 Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000615 Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000616 Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
John McCall7ef5cb32011-03-18 02:56:14 +0000617 Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
Daniel Dunbard3f3d932011-06-21 18:54:46 +0000618 Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
619 OPT_fuse_register_sized_bitfield_access);
Chad Rosierb71f6aa2013-04-24 18:09:54 +0000620 Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
Manman Renf5d9d342013-10-11 20:48:38 +0000621 Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
Ivan A. Kosarevfa03a6a2017-11-20 11:16:16 +0000622 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
623 Args.hasArg(OPT_new_struct_path_tbaa);
Wei Mi9b3d6272017-10-16 16:50:27 +0000624 Opts.FineGrainedBitfieldAccesses =
625 Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
626 OPT_fno_fine_grained_bitfield_accesses, false);
Daniel Dunbar37300482010-05-20 16:54:55 +0000627 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
Manoj Gupta4b3eefa2018-04-05 15:29:52 +0000628 Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000629 Opts.NoCommon = Args.hasArg(OPT_fno_common);
630 Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
Chad Rosierf2d39642013-04-10 21:30:03 +0000631 Opts.OptimizeSize = getOptimizationLevelSize(Args);
Daniel Dunbar6d5824f2010-06-07 23:19:17 +0000632 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
633 Args.hasArg(OPT_ffreestanding));
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000634 if (Opts.SimplifyLibCalls)
635 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
Chandler Carruth54c29102013-08-08 08:34:35 +0000636 Opts.UnrollLoops =
637 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
Marianne Mailhot-Sarrasin21ac3bf2016-05-04 15:26:28 +0000638 (Opts.OptimizationLevel > 1));
Hal Finkelce0697f2013-11-17 16:03:29 +0000639 Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000640
Saleem Abdulrasoolcfeb90d2014-02-23 00:40:30 +0000641 Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
Daniel Dunbare246fbe2013-04-16 18:21:19 +0000642 Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
Diego Novillo5c297052013-11-13 12:22:39 +0000643 Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
Dehao Chenb3a70de2017-01-19 00:44:21 +0000644 Opts.DebugInfoForProfiling = Args.hasFlag(
645 OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
Peter Collingbourneb52e2362017-09-12 21:50:41 +0000646 Opts.GnuPubnames = Args.hasArg(OPT_ggnu_pubnames);
Rong Xu9837ef52016-02-04 18:39:09 +0000647
Rong Xu9c6f1532016-03-02 20:59:36 +0000648 setPGOInstrumentor(Opts, Args, Diags);
649 Opts.InstrProfileOutput =
650 Args.getLastArgValue(OPT_fprofile_instrument_path_EQ);
651 Opts.ProfileInstrumentUsePath =
652 Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ);
653 if (!Opts.ProfileInstrumentUsePath.empty())
654 setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
Rong Xu9837ef52016-02-04 18:39:09 +0000655
Diego Novilloc4b94da2015-08-05 23:27:40 +0000656 Opts.CoverageMapping =
657 Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000658 Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000659 Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
Nirav Dave993a1392016-07-27 19:57:40 +0000660 Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
Richard Smith351241c2016-04-07 21:46:12 +0000661 Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
John McCall31168b02011-06-15 23:02:42 +0000662 Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000663 Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
Akira Hatanaka617e2612018-04-17 18:41:52 +0000664 Opts.RegisterGlobalDtorsWithAtExit =
665 Args.hasArg(OPT_fregister_global_dtors_with_atexit);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000666 Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000667 Opts.CodeModel = getCodeModel(Args, Diags);
Daniel Dunbar37300482010-05-20 16:54:55 +0000668 Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
Xinliang David Li4dff8752015-11-23 17:30:31 +0000669 Opts.DisableFPElim =
670 (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg));
Nick Lewycky92a6c742013-06-21 21:15:32 +0000671 Opts.DisableFree = Args.hasArg(OPT_disable_free);
Benjamin Kramer12f2de12016-03-14 13:23:58 +0000672 Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
Nick Lewycky1c8c4362012-01-23 08:29:12 +0000673 Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
Akira Hatanaka627586b2018-03-02 01:53:15 +0000674 Opts.NoEscapingBlockTailCalls =
675 Args.hasArg(OPT_fno_escaping_block_tail_calls);
Daniel Dunbar37300482010-05-20 16:54:55 +0000676 Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
Egor Churaev45c26ee2017-03-27 10:38:01 +0000677 Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
678 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
679 Args.hasArg(OPT_cl_fast_relaxed_math);
Daniel Dunbar37300482010-05-20 16:54:55 +0000680 Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000681 Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
Pekka Jaaskelainen37014502014-12-10 16:41:14 +0000682 Args.hasArg(OPT_cl_finite_math_only) ||
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000683 Args.hasArg(OPT_cl_fast_relaxed_math));
684 Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
Pekka Jaaskelainen37014502014-12-10 16:41:14 +0000685 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
686 Args.hasArg(OPT_cl_finite_math_only) ||
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000687 Args.hasArg(OPT_cl_fast_relaxed_math));
Yaxun Liu79c99fb2016-07-08 20:28:29 +0000688 Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
Egor Churaev45c26ee2017-03-27 10:38:01 +0000689 Args.hasArg(OPT_cl_no_signed_zeros) ||
690 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
691 Args.hasArg(OPT_cl_fast_relaxed_math));
Sanjay Patelcb8c0092017-12-16 16:11:17 +0000692 Opts.Reassociate = Args.hasArg(OPT_mreassociate);
Yaxun Liu2c17e822016-08-09 19:43:38 +0000693 Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero);
Yaxun Liuffb60902016-08-09 20:10:18 +0000694 Opts.CorrectlyRoundedDivSqrt =
695 Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
Alexey Sotkin20f65922018-02-22 11:54:14 +0000696 Opts.UniformWGSize =
697 Args.hasArg(OPT_cl_uniform_work_group_size);
Craig Topper402b4312017-11-20 17:09:22 +0000698 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
Sanjay Patel359b1052015-04-09 15:03:23 +0000699 Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +0000700 Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
Sanjay Patelc81450e2018-04-30 18:19:03 +0000701 Opts.StrictFloatCastOverflow =
702 !Args.hasArg(OPT_fno_strict_float_cast_overflow);
Sanjay Pateld1754762018-04-27 14:22:48 +0000703
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000704 Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
Reid Kleckner898229a2013-06-14 17:17:23 +0000705 Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
Nick Lewyckyca6b90d2011-06-21 00:14:18 +0000706 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000707 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
Eric Christopher006208c2013-04-04 06:29:47 +0000708 Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
Daniel Dunbarc43b6b22010-05-27 05:39:39 +0000709 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
David Majnemer2b9349d2015-12-21 22:09:34 +0000710 Opts.IncrementalLinkerCompatible =
711 Args.hasArg(OPT_mincremental_linker_compatible);
Sriraman Tallam165a8842016-10-19 20:24:06 +0000712 Opts.PIECopyRelocations =
713 Args.hasArg(OPT_mpie_copy_relocations);
Sriraman Tallam5c651482017-11-07 19:37:51 +0000714 Opts.NoPLT = Args.hasArg(OPT_fno_plt);
Daniel Dunbarbb7ac522010-07-01 01:31:45 +0000715 Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
Daniel Dunbar67919b22011-03-28 22:49:28 +0000716 Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
Nick Lewycky1d617ac2011-10-17 23:05:52 +0000717 Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000718 Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
Chandler Carruth8b4140d2012-03-27 23:58:37 +0000719 Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
Alex Lorenzc1608f72017-01-04 13:40:34 +0000720 Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
Piotr Padlewski338c9d02015-09-15 21:46:47 +0000721 Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
Chandler Carruth306bd2c2012-01-02 14:19:45 +0000722 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
723 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
Peter Collingbourne61d6a752010-12-04 01:51:23 +0000724 Args.hasArg(OPT_cl_fast_relaxed_math);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000725 Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000726 Opts.RelocationModel = getRelocModel(Args, Diags);
Jonathan Roelofsb140a102014-10-03 21:57:44 +0000727 Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
728 if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
729 Diags.Report(diag::err_drv_invalid_value)
730 << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
731 << Opts.ThreadModel;
Bob Wilson14adb362012-02-03 06:27:22 +0000732 Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
Rafael Espindola66aa0452012-06-19 01:26:10 +0000733 Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000734
Nick Lewycky3a410fe2013-10-11 03:35:10 +0000735 Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
736 OPT_fno_function_sections, false);
737 Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
738 OPT_fno_data_sections, false);
Sean Eveson5110d4f2018-01-08 13:42:26 +0000739 Opts.StackSizeSection =
740 Args.hasFlag(OPT_fstack_size_section, OPT_fno_stack_size_section, false);
Rafael Espindola6b07a1c2015-02-20 18:08:57 +0000741 Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
742 OPT_fno_unique_section_names, true);
743
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000744 Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
Chris Lattnerdc6040b2010-04-13 00:38:24 +0000745
Nirav Daved2f44d82016-04-05 17:50:43 +0000746 Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
747
Dehao Chen5e97f232017-08-24 21:37:33 +0000748 Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
749
Teresa Johnson945bc502015-10-15 20:35:53 +0000750 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
Yuka Takahashi50a9dfa2017-06-14 15:37:11 +0000751 Opts.EmitSummaryIndex = false;
752 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
753 StringRef S = A->getValue();
754 if (S == "thin")
755 Opts.EmitSummaryIndex = true;
756 else if (S != "full")
757 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
758 }
Peter Collingbourne1e1475a2017-01-18 23:55:27 +0000759 Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
Teresa Johnsonaff22322015-12-07 19:21:34 +0000760 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
Richard Smith40c0efa2017-04-26 18:57:40 +0000761 if (IK.getLanguage() != InputKind::LLVM_IR)
Teresa Johnsonaff22322015-12-07 19:21:34 +0000762 Diags.Report(diag::err_drv_argument_only_allowed_with)
763 << A->getAsString(Args) << "-x ir";
764 Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
765 }
Teresa Johnson9e4321c2018-04-17 16:39:25 +0000766 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
767 Opts.SaveTempsFilePrefix =
768 llvm::StringSwitch<std::string>(A->getValue())
769 .Case("obj", FrontendOpts.OutputFile)
770 .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
771
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000772 Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ);
Teresa Johnson8749d8042015-07-06 16:23:00 +0000773
David Majnemera5b195a2015-02-14 01:35:12 +0000774 Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
775
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000776 Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
777 Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
778
Craig Topper9a724aa2017-12-11 21:09:19 +0000779 Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
780
Daniel Dunbar37300482010-05-20 16:54:55 +0000781 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
John McCallcfcb7752010-02-12 23:47:27 +0000782 Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000783
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000784 Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
785
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000786 Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
Nick Lewycky207bce32011-04-21 23:44:07 +0000787 Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
788 Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
Nick Lewycky737a4522013-03-07 08:28:53 +0000789 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000790 Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file);
791 Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file);
Nick Lewycky737a4522013-03-07 08:28:53 +0000792 Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000793 Opts.CoverageNoFunctionNamesInData =
794 Args.hasArg(OPT_coverage_no_function_names_in_data);
Justin Bogner4e462372015-03-16 23:52:21 +0000795 Opts.CoverageExitBlockBeforeBody =
796 Args.hasArg(OPT_coverage_exit_block_before_body);
Nick Lewycky737a4522013-03-07 08:28:53 +0000797 if (Args.hasArg(OPT_coverage_version_EQ)) {
798 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
799 if (CoverageVersion.size() != 4) {
800 Diags.Report(diag::err_drv_invalid_value)
801 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
802 << CoverageVersion;
803 } else {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000804 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
Nick Lewycky737a4522013-03-07 08:28:53 +0000805 }
806 }
807 }
Steven Wu27fb5222016-05-11 16:26:03 +0000808 // Handle -fembed-bitcode option.
809 if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
810 StringRef Name = A->getValue();
811 unsigned Model = llvm::StringSwitch<unsigned>(Name)
812 .Case("off", CodeGenOptions::Embed_Off)
813 .Case("all", CodeGenOptions::Embed_All)
814 .Case("bitcode", CodeGenOptions::Embed_Bitcode)
815 .Case("marker", CodeGenOptions::Embed_Marker)
816 .Default(~0U);
817 if (Model == ~0U) {
818 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
819 Success = false;
820 } else
821 Opts.setEmbedBitcode(
822 static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
823 }
824 // FIXME: For backend options that are not yet recorded as function
825 // attributes in the IR, keep track of them so we can embed them in a
826 // separate data section and use them when building the bitcode.
827 if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
828 for (const auto &A : Args) {
829 // Do not encode output and input.
830 if (A->getOption().getID() == options::OPT_o ||
831 A->getOption().getID() == options::OPT_INPUT ||
832 A->getOption().getID() == options::OPT_x ||
833 A->getOption().getID() == options::OPT_fembed_bitcode ||
834 (A->getOption().getGroup().isValid() &&
835 A->getOption().getGroup().getID() == options::OPT_W_Group))
836 continue;
837 ArgStringList ASL;
838 A->render(Args, ASL);
839 for (const auto &arg : ASL) {
840 StringRef ArgStr(arg);
841 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
842 // using \00 to seperate each commandline options.
843 Opts.CmdArgs.push_back('\0');
844 }
845 }
846 }
Nick Lewycky737a4522013-03-07 08:28:53 +0000847
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +0000848 Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
Nick Lewycky737a4522013-03-07 08:28:53 +0000849 Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
Hans Wennborg76c26c12017-11-14 21:13:27 +0000850 Opts.InstrumentFunctionsAfterInlining =
851 Args.hasArg(OPT_finstrument_functions_after_inlining);
Hans Wennborg14e8a5a2017-11-21 17:30:34 +0000852 Opts.InstrumentFunctionEntryBare =
853 Args.hasArg(OPT_finstrument_function_entry_bare);
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000854
855 Opts.XRayInstrumentFunctions =
856 Args.hasArg(OPT_fxray_instrument);
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +0000857 Opts.XRayAlwaysEmitCustomEvents =
858 Args.hasArg(OPT_fxray_always_emit_customevents);
Keith Wyssf437e352018-04-17 21:32:43 +0000859 Opts.XRayAlwaysEmitTypedEvents =
860 Args.hasArg(OPT_fxray_always_emit_typedevents);
Aaron Ballman7d2aecb2016-07-13 22:32:15 +0000861 Opts.XRayInstructionThreshold =
Dean Michael Berris504fc222017-03-30 22:46:45 +0000862 getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000863
864 auto XRayInstrBundles =
865 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
866 if (XRayInstrBundles.empty())
867 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
868 else
869 for (const auto &A : XRayInstrBundles)
870 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
871 Diags, Opts.XRayInstrumentationBundle);
872
Nick Lewycky737a4522013-03-07 08:28:53 +0000873 Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
Nirav Dave0c86ccf2017-01-31 17:00:35 +0000874 Opts.CallFEntry = Args.hasArg(OPT_mfentry);
Nick Lewycky737a4522013-03-07 08:28:53 +0000875 Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000876
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000877 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
878 StringRef Name = A->getValue();
879 if (Name == "full") {
880 Opts.CFProtectionReturn = 1;
881 Opts.CFProtectionBranch = 1;
882 } else if (Name == "return")
883 Opts.CFProtectionReturn = 1;
884 else if (Name == "branch")
885 Opts.CFProtectionBranch = 1;
886 else if (Name != "none") {
887 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
888 Success = false;
889 }
890 }
891
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000892 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
893 OPT_compress_debug_sections_EQ)) {
894 if (A->getOption().getID() == OPT_compress_debug_sections) {
895 // TODO: be more clever about the compression type auto-detection
896 Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
897 } else {
898 auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
899 .Case("none", llvm::DebugCompressionType::None)
900 .Case("zlib", llvm::DebugCompressionType::Z)
901 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
902 .Default(llvm::DebugCompressionType::None);
903 Opts.setCompressDebugSections(DCT);
904 }
905 }
906
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000907 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Nick Lewyckyba743b72011-10-21 02:32:14 +0000908 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000909 for (auto *A :
910 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
Justin Lebarb080b632017-01-25 21:29:48 +0000911 CodeGenOptions::BitcodeFileToLink F;
912 F.Filename = A->getValue();
913 if (A->getOption().matches(OPT_mlink_cuda_bitcode)) {
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000914 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
Justin Lebarb080b632017-01-25 21:29:48 +0000915 // When linking CUDA bitcode, propagate function attributes so that
916 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
917 F.PropagateAttrs = true;
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000918 F.Internalize = true;
Justin Lebarb080b632017-01-25 21:29:48 +0000919 }
920 Opts.LinkBitcodeFiles.push_back(F);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000921 }
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000922 Opts.SanitizeCoverageType =
923 getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
924 Opts.SanitizeCoverageIndirectCalls =
925 Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
926 Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
927 Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
Kostya Serebryany3b419712016-08-30 01:27:03 +0000928 Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
929 Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000930 Opts.SanitizeCoverage8bitCounters =
931 Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000932 Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000933 Opts.SanitizeCoverageTracePCGuard =
934 Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000935 Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000936 Opts.SanitizeCoverageInline8bitCounters =
937 Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
Kostya Serebryany61457762017-07-28 00:10:10 +0000938 Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000939 Opts.SanitizeCoverageStackDepth =
940 Args.hasArg(OPT_fsanitize_coverage_stack_depth);
Alexey Samsonov29524a92013-01-20 13:12:12 +0000941 Opts.SanitizeMemoryTrackOrigins =
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000942 getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000943 Opts.SanitizeMemoryUseAfterDtor =
Matt Morehousebb26f862017-09-14 23:14:37 +0000944 Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
945 OPT_fno_sanitize_memory_use_after_dtor,
946 false);
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000947 Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000948 Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +0000949 Opts.SanitizeCfiICallGeneralizePointers =
950 Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
Peter Collingbournedc134532016-01-16 00:31:22 +0000951 Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +0000952 if (Arg *A = Args.getLastArg(
953 OPT_fsanitize_address_poison_class_member_array_new_cookie,
954 OPT_fno_sanitize_address_poison_class_member_array_new_cookie)) {
955 Opts.SanitizeAddressPoisonClassMemberArrayNewCookie =
956 A->getOption().getID() ==
957 OPT_fsanitize_address_poison_class_member_array_new_cookie;
958 }
Vitaly Bukaa77ac1b2016-10-10 21:31:50 +0000959 if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
960 OPT_fno_sanitize_address_use_after_scope)) {
961 Opts.SanitizeAddressUseAfterScope =
962 A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
963 }
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000964 Opts.SanitizeAddressGlobalsDeadStripping =
965 Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
Chad Rosierdb3da832012-08-21 16:16:06 +0000966 Opts.SSPBufferSize =
Reid Kleckner898229a2013-06-14 17:17:23 +0000967 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
Nick Lewyckyf4d3f7a2011-12-06 03:33:03 +0000968 Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +0000969 if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000970 StringRef Val = A->getValue();
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000971 unsigned StackAlignment = Opts.StackAlignment;
972 Val.getAsInteger(10, StackAlignment);
973 Opts.StackAlignment = StackAlignment;
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +0000974 }
Chris Lattner3c77a352010-06-22 00:03:40 +0000975
Hans Wennborg77dc2362015-01-20 19:45:50 +0000976 if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
977 StringRef Val = A->getValue();
978 unsigned StackProbeSize = Opts.StackProbeSize;
979 Val.getAsInteger(0, StackProbeSize);
980 Opts.StackProbeSize = StackProbeSize;
981 }
982
Hans Wennborgd43f40d2018-02-23 13:47:36 +0000983 Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
984
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000985 if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000986 StringRef Name = A->getValue();
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000987 unsigned Method = llvm::StringSwitch<unsigned>(Name)
988 .Case("legacy", CodeGenOptions::Legacy)
989 .Case("non-legacy", CodeGenOptions::NonLegacy)
990 .Case("mixed", CodeGenOptions::Mixed)
991 .Default(~0U);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000992 if (Method == ~0U) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000993 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000994 Success = false;
995 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000996 Opts.setObjCDispatchMethod(
997 static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000998 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000999 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001000
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00001001 if (Args.getLastArg(OPT_femulated_tls) ||
1002 Args.getLastArg(OPT_fno_emulated_tls)) {
1003 Opts.ExplicitEmulatedTLS = true;
1004 Opts.EmulatedTLS =
1005 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1006 }
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001007
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001008 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001009 StringRef Name = A->getValue();
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001010 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1011 .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1012 .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1013 .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1014 .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1015 .Default(~0U);
1016 if (Model == ~0U) {
1017 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1018 Success = false;
1019 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001020 Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001021 }
1022 }
1023
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001024 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1025 StringRef Val = A->getValue();
1026 if (Val == "ieee")
1027 Opts.FPDenormalMode = "ieee";
1028 else if (Val == "preserve-sign")
1029 Opts.FPDenormalMode = "preserve-sign";
1030 else if (Val == "positive-zero")
1031 Opts.FPDenormalMode = "positive-zero";
1032 else
1033 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1034 }
1035
John McCall1fe2a8c2013-06-18 02:46:29 +00001036 if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
1037 if (A->getOption().matches(OPT_fpcc_struct_return)) {
1038 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1039 } else {
1040 assert(A->getOption().matches(OPT_freg_struct_return));
1041 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1042 }
1043 }
1044
Hans Wennborg75958c42013-08-08 00:17:41 +00001045 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
Peter Collingbournedc134532016-01-16 00:31:22 +00001046 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
Diego Novillo913690c2014-06-24 17:02:17 +00001047 bool NeedLocTracking = false;
Hans Wennborg75958c42013-08-08 00:17:41 +00001048
Hal Finkel8f96e822016-10-11 00:26:09 +00001049 Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file);
1050 if (!Opts.OptRecordFile.empty())
1051 NeedLocTracking = true;
1052
Diego Novillo913690c2014-06-24 17:02:17 +00001053 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001054 Opts.OptimizationRemarkPattern =
1055 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001056 NeedLocTracking = true;
1057 }
Diego Novillod23ec942014-05-29 19:55:06 +00001058
Diego Novillo913690c2014-06-24 17:02:17 +00001059 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001060 Opts.OptimizationRemarkMissedPattern =
1061 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001062 NeedLocTracking = true;
1063 }
Diego Novillod23ec942014-05-29 19:55:06 +00001064
Diego Novillo913690c2014-06-24 17:02:17 +00001065 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001066 Opts.OptimizationRemarkAnalysisPattern =
1067 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001068 NeedLocTracking = true;
1069 }
1070
Adam Nemet1eea3e52016-09-13 04:32:40 +00001071 Opts.DiagnosticsWithHotness =
1072 Args.hasArg(options::OPT_fdiagnostics_show_hotness);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001073 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
Brian Gesiak562eab92017-07-01 05:45:26 +00001074 bool UsingProfile = UsingSampleProfile ||
1075 (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001076
Teresa Johnson66744f82018-05-05 14:37:29 +00001077 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1078 // An IR file will contain PGO as metadata
1079 IK.getLanguage() != InputKind::LLVM_IR)
Brian Gesiak562eab92017-07-01 05:45:26 +00001080 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1081 << "-fdiagnostics-show-hotness";
1082
1083 Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1084 Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1085 if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
1086 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1087 << "-fdiagnostics-hotness-threshold=";
Adam Nemet1eea3e52016-09-13 04:32:40 +00001088
Diego Novillo795f53b2014-10-22 13:00:05 +00001089 // If the user requested to use a sample profile for PGO, then the
1090 // backend will need to track source location information so the profile
1091 // can be incorporated into the IR.
Brian Gesiak0ea58882017-06-23 02:38:45 +00001092 if (UsingSampleProfile)
Diego Novillo795f53b2014-10-22 13:00:05 +00001093 NeedLocTracking = true;
1094
1095 // If the user requested a flag that requires source locations available in
1096 // the backend, make sure that the backend tracks source location information.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001097 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1098 Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
Diego Novillod23ec942014-05-29 19:55:06 +00001099
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +00001100 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1101
Alexey Samsonov88459522015-01-12 22:39:12 +00001102 // Parse -fsanitize-recover= arguments.
1103 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1104 parseSanitizerKinds("-fsanitize-recover=",
1105 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1106 Opts.SanitizeRecover);
Peter Collingbourne9881b782015-06-18 23:59:22 +00001107 parseSanitizerKinds("-fsanitize-trap=",
1108 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1109 Opts.SanitizeTrap);
Alexey Samsonov88459522015-01-12 22:39:12 +00001110
Jonas Hahnfelde7681322018-02-28 17:53:46 +00001111 Opts.CudaGpuBinaryFileName =
1112 Args.getLastArgValue(OPT_fcuda_include_gpubinary);
Artem Belevich52cc4872015-05-07 19:34:16 +00001113
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001114 Opts.Backchain = Args.hasArg(OPT_mbackchain);
1115
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00001116 Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1117 Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1118
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00001119 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1120
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001121 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001122}
1123
1124static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1125 ArgList &Args) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001126 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1127 Opts.Targets = Args.getAllArgValues(OPT_MT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001128 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00001129 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001130 Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
Daniel Dunbar27734fd2011-02-02 15:41:17 +00001131 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +00001132 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001133 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
Erich Keane425f48d2018-05-04 15:58:31 +00001134 if (Args.hasArg(OPT_show_includes)) {
1135 // Writing both /showIncludes and preprocessor output to stdout
1136 // would produce interleaved output, so use stderr for /showIncludes.
1137 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1138 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1139 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1140 else
1141 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1142 } else {
1143 Opts.ShowIncludesDest = ShowIncludesDestination::None;
1144 }
Douglas Gregor2e129652012-02-02 23:45:13 +00001145 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
Justin Bogner86d12592014-06-19 19:36:03 +00001146 Opts.ModuleDependencyOutputDir =
1147 Args.getLastArgValue(OPT_module_dependency_dir);
Paul Robinsond7214a72015-04-27 18:14:32 +00001148 if (Args.hasArg(OPT_MV))
1149 Opts.OutputFormat = DependencyOutputFormat::NMake;
Ivan Krasin1193f2c2015-08-13 04:04:37 +00001150 // Add sanitizer blacklists as extra dependencies.
1151 // They won't be discovered by the regular preprocessor, so
1152 // we let make / ninja to know about this implicit dependency.
Ivan Krasin4c3f2372015-09-02 20:02:38 +00001153 Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001154 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001155 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001156 StringRef Val = A->getValue();
1157 if (Val.find('=') == StringRef::npos)
1158 Opts.ExtraDeps.push_back(Val);
1159 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001160}
1161
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001162static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1163 // Color diagnostics default to auto ("on" if terminal supports) in the driver
1164 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1165 // Support both clang's -f[no-]color-diagnostics and gcc's
1166 // -f[no-]diagnostics-colors[=never|always|auto].
1167 enum {
1168 Colors_On,
1169 Colors_Off,
1170 Colors_Auto
1171 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001172 for (auto *A : Args) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001173 const Option &O = A->getOption();
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001174 if (O.matches(options::OPT_fcolor_diagnostics) ||
1175 O.matches(options::OPT_fdiagnostics_color)) {
1176 ShowColors = Colors_On;
1177 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1178 O.matches(options::OPT_fno_diagnostics_color)) {
1179 ShowColors = Colors_Off;
Yaron Keren9181e772016-12-10 14:55:14 +00001180 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001181 StringRef Value(A->getValue());
1182 if (Value == "always")
1183 ShowColors = Colors_On;
1184 else if (Value == "never")
1185 ShowColors = Colors_Off;
1186 else if (Value == "auto")
1187 ShowColors = Colors_Auto;
1188 }
1189 }
Yaron Keren9181e772016-12-10 14:55:14 +00001190 return ShowColors == Colors_On ||
1191 (ShowColors == Colors_Auto &&
1192 llvm::sys::Process::StandardErrHasColors());
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001193}
1194
Hal Finkel05e46482017-12-16 02:23:22 +00001195static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1196 DiagnosticsEngine *Diags) {
1197 bool Success = true;
1198 for (const auto &Prefix : VerifyPrefixes) {
1199 // Every prefix must start with a letter and contain only alphanumeric
1200 // characters, hyphens, and underscores.
1201 auto BadChar = std::find_if(Prefix.begin(), Prefix.end(),
1202 [](char C){return !isAlphanumeric(C)
1203 && C != '-' && C != '_';});
1204 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1205 Success = false;
1206 if (Diags) {
1207 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1208 Diags->Report(diag::note_drv_verify_prefix_spelling);
1209 }
1210 }
1211 }
1212 return Success;
1213}
1214
Chad Rosierd6f716a2012-03-13 20:09:56 +00001215bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001216 DiagnosticsEngine *Diags,
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001217 bool DefaultDiagColor, bool DefaultShowOpt) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001218 bool Success = true;
1219
Daniel Dunbar6b584862011-04-07 18:11:14 +00001220 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +00001221 if (Arg *A =
1222 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1223 Opts.DiagnosticSerializationFile = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001224 Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1225 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1226 Opts.Pedantic = Args.hasArg(OPT_pedantic);
1227 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1228 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001229 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
Douglas Gregor643c9222011-05-21 17:07:29 +00001230 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1231 OPT_fno_show_column,
1232 /*Default=*/true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001233 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1234 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
Hans Wennborgb30f4372016-08-26 15:45:36 +00001235 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001236 Opts.ShowOptionNames =
1237 Args.hasFlag(OPT_fdiagnostics_show_option,
1238 OPT_fno_diagnostics_show_option, DefaultShowOpt);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001239
Nico Rieck7857d462013-09-11 00:38:02 +00001240 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1241
Chandler Carruth24284af2011-03-27 20:00:08 +00001242 // Default behavior is to not to show note include stacks.
1243 Opts.ShowNoteIncludeStack = false;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001244 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1245 OPT_fno_diagnostics_show_note_include_stack))
Chandler Carruth24284af2011-03-27 20:00:08 +00001246 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1247 Opts.ShowNoteIncludeStack = true;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001248
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001249 StringRef ShowOverloads =
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001250 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1251 if (ShowOverloads == "best")
Douglas Gregor79591782012-10-23 23:11:23 +00001252 Opts.setShowOverloads(Ovl_Best);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001253 else if (ShowOverloads == "all")
Douglas Gregor79591782012-10-23 23:11:23 +00001254 Opts.setShowOverloads(Ovl_All);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001255 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001256 Success = false;
1257 if (Diags)
1258 Diags->Report(diag::err_drv_invalid_value)
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001259 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1260 << ShowOverloads;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001261 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001262
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001263 StringRef ShowCategory =
Daniel Dunbar37300482010-05-20 16:54:55 +00001264 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001265 if (ShowCategory == "none")
1266 Opts.ShowCategories = 0;
1267 else if (ShowCategory == "id")
1268 Opts.ShowCategories = 1;
1269 else if (ShowCategory == "name")
1270 Opts.ShowCategories = 2;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001271 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001272 Success = false;
1273 if (Diags)
1274 Diags->Report(diag::err_drv_invalid_value)
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001275 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1276 << ShowCategory;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001277 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001278
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001279 StringRef Format =
Douglas Gregor643c9222011-05-21 17:07:29 +00001280 Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1281 if (Format == "clang")
Douglas Gregor79591782012-10-23 23:11:23 +00001282 Opts.setFormat(DiagnosticOptions::Clang);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001283 else if (Format == "msvc")
David Majnemer8ab003a2015-02-02 19:30:52 +00001284 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001285 else if (Format == "msvc-fallback") {
David Majnemer8ab003a2015-02-02 19:30:52 +00001286 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001287 Opts.CLFallbackMode = true;
1288 } else if (Format == "vi")
Douglas Gregor79591782012-10-23 23:11:23 +00001289 Opts.setFormat(DiagnosticOptions::Vi);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001290 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001291 Success = false;
1292 if (Diags)
1293 Diags->Report(diag::err_drv_invalid_value)
Douglas Gregor643c9222011-05-21 17:07:29 +00001294 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1295 << Format;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001296 }
Eric Fiselier098e6de2015-06-13 07:11:40 +00001297
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001298 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
Douglas Gregoreec975c2010-08-19 20:24:43 +00001299 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
Richard Smith0b50cb72012-11-14 23:55:25 +00001300 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
Hal Finkel05e46482017-12-16 02:23:22 +00001301 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1302 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1303 if (Args.hasArg(OPT_verify))
1304 Opts.VerifyPrefixes.push_back("expected");
1305 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1306 // then sort it to prepare for fast lookup using std::binary_search.
1307 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1308 Opts.VerifyDiagnostics = false;
1309 Success = false;
1310 }
1311 else
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001312 llvm::sort(Opts.VerifyPrefixes.begin(), Opts.VerifyPrefixes.end());
Eric Fiselier098e6de2015-06-13 07:11:40 +00001313 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1314 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1315 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1316 Diags, DiagMask);
1317 if (Args.hasArg(OPT_verify_ignore_unexpected))
1318 DiagMask = DiagnosticLevelMask::All;
1319 Opts.setVerifyIgnoreUnexpected(DiagMask);
Richard Trieu91844232012-06-26 18:18:47 +00001320 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1321 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
Reid Kleckner898229a2013-06-14 17:17:23 +00001322 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1323 Opts.MacroBacktraceLimit =
1324 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
Douglas Gregorcd121fb2010-05-04 17:13:42 +00001325 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001326 Opts.TemplateBacktraceLimit = getLastArgIntValue(
1327 Args, OPT_ftemplate_backtrace_limit,
1328 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1329 Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1330 Args, OPT_fconstexpr_backtrace_limit,
1331 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
Nick Lewycky24653262014-12-16 21:39:02 +00001332 Opts.SpellCheckingLimit = getLastArgIntValue(
1333 Args, OPT_fspell_checking_limit,
1334 DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001335 Opts.SnippetLineLimit = getLastArgIntValue(
1336 Args, OPT_fcaret_diagnostics_max_lines,
1337 DiagnosticOptions::DefaultSnippetLineLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001338 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
Chris Lattner3d756f12010-01-13 03:06:50 +00001339 DiagnosticOptions::DefaultTabStop, Diags);
1340 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
Chris Lattner3d756f12010-01-13 03:06:50 +00001341 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
Chad Rosierd6f716a2012-03-13 20:09:56 +00001342 if (Diags)
1343 Diags->Report(diag::warn_ignoring_ftabstop_value)
1344 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
Chris Lattner3d756f12010-01-13 03:06:50 +00001345 }
Reid Kleckner898229a2013-06-14 17:17:23 +00001346 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
Richard Smith3be1cb22014-08-07 00:24:21 +00001347 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1348 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001349
1350 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001351}
1352
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001353static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1354 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1355}
1356
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001357/// Parse the argument to the -ftest-module-file-extension
1358/// command-line argument.
1359///
1360/// \returns true on error, false on success.
1361static bool parseTestModuleFileExtensionArg(StringRef Arg,
1362 std::string &BlockName,
1363 unsigned &MajorVersion,
1364 unsigned &MinorVersion,
1365 bool &Hashed,
1366 std::string &UserInfo) {
1367 SmallVector<StringRef, 5> Args;
1368 Arg.split(Args, ':', 5);
1369 if (Args.size() < 5)
1370 return true;
1371
1372 BlockName = Args[0];
1373 if (Args[1].getAsInteger(10, MajorVersion)) return true;
1374 if (Args[2].getAsInteger(10, MinorVersion)) return true;
1375 if (Args[3].getAsInteger(2, Hashed)) return true;
1376 if (Args.size() > 4)
1377 UserInfo = Args[4];
1378 return false;
1379}
1380
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001381static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Erik Verbruggene0bde752016-10-27 14:17:10 +00001382 DiagnosticsEngine &Diags,
1383 bool &IsHeaderFile) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001384 Opts.ProgramAction = frontend::ParseSyntaxOnly;
1385 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1386 switch (A->getOption().getID()) {
1387 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001388 llvm_unreachable("Invalid option in group!");
Alexander Kornienko4de03592012-07-31 09:37:40 +00001389 case OPT_ast_list:
1390 Opts.ProgramAction = frontend::ASTDeclList; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001391 case OPT_ast_dump:
Richard Smith3a36ac12017-03-09 22:00:01 +00001392 case OPT_ast_dump_all:
Richard Smith35f986d2014-08-11 22:11:07 +00001393 case OPT_ast_dump_lookups:
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001394 Opts.ProgramAction = frontend::ASTDump; break;
1395 case OPT_ast_print:
1396 Opts.ProgramAction = frontend::ASTPrint; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001397 case OPT_ast_view:
1398 Opts.ProgramAction = frontend::ASTView; break;
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00001399 case OPT_compiler_options_dump:
1400 Opts.ProgramAction = frontend::DumpCompilerOptions; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001401 case OPT_dump_raw_tokens:
1402 Opts.ProgramAction = frontend::DumpRawTokens; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001403 case OPT_dump_tokens:
1404 Opts.ProgramAction = frontend::DumpTokens; break;
1405 case OPT_S:
1406 Opts.ProgramAction = frontend::EmitAssembly; break;
1407 case OPT_emit_llvm_bc:
1408 Opts.ProgramAction = frontend::EmitBC; break;
1409 case OPT_emit_html:
1410 Opts.ProgramAction = frontend::EmitHTML; break;
1411 case OPT_emit_llvm:
1412 Opts.ProgramAction = frontend::EmitLLVM; break;
1413 case OPT_emit_llvm_only:
1414 Opts.ProgramAction = frontend::EmitLLVMOnly; break;
Daniel Dunbar4c77a642010-05-25 18:41:01 +00001415 case OPT_emit_codegen_only:
1416 Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
Daniel Dunbar92db0fb2010-02-03 01:18:43 +00001417 case OPT_emit_obj:
1418 Opts.ProgramAction = frontend::EmitObj; break;
Nick Lewycky784fad72010-04-24 01:30:46 +00001419 case OPT_fixit_EQ:
Richard Smithbd55daf2012-11-01 04:30:05 +00001420 Opts.FixItSuffix = A->getValue();
Nick Lewycky784fad72010-04-24 01:30:46 +00001421 // fall-through!
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001422 case OPT_fixit:
1423 Opts.ProgramAction = frontend::FixIt; break;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001424 case OPT_emit_module:
1425 Opts.ProgramAction = frontend::GenerateModule; break;
Richard Smithbbcc9f02016-08-26 00:14:38 +00001426 case OPT_emit_module_interface:
1427 Opts.ProgramAction = frontend::GenerateModuleInterface; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001428 case OPT_emit_pch:
1429 Opts.ProgramAction = frontend::GeneratePCH; break;
1430 case OPT_emit_pth:
1431 Opts.ProgramAction = frontend::GeneratePTH; break;
Daniel Dunbar1c201fb2010-03-19 19:44:04 +00001432 case OPT_init_only:
1433 Opts.ProgramAction = frontend::InitOnly; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001434 case OPT_fsyntax_only:
1435 Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00001436 case OPT_module_file_info:
1437 Opts.ProgramAction = frontend::ModuleFileInfo; break;
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001438 case OPT_verify_pch:
1439 Opts.ProgramAction = frontend::VerifyPCH; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001440 case OPT_print_decl_contexts:
1441 Opts.ProgramAction = frontend::PrintDeclContext; break;
Douglas Gregoraf82e352010-07-20 20:18:03 +00001442 case OPT_print_preamble:
1443 Opts.ProgramAction = frontend::PrintPreamble; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001444 case OPT_E:
1445 Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
Gabor Horvath207e7b12018-02-10 14:04:45 +00001446 case OPT_templight_dump:
1447 Opts.ProgramAction = frontend::TemplightDump; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001448 case OPT_rewrite_macros:
1449 Opts.ProgramAction = frontend::RewriteMacros; break;
1450 case OPT_rewrite_objc:
1451 Opts.ProgramAction = frontend::RewriteObjC; break;
1452 case OPT_rewrite_test:
1453 Opts.ProgramAction = frontend::RewriteTest; break;
1454 case OPT_analyze:
1455 Opts.ProgramAction = frontend::RunAnalysis; break;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001456 case OPT_migrate:
1457 Opts.ProgramAction = frontend::MigrateSource; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001458 case OPT_Eonly:
1459 Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1460 }
1461 }
Daniel Dunbar7c995e82010-06-16 16:59:23 +00001462
1463 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00001464 Opts.Plugins.emplace_back(A->getValue(0));
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001465 Opts.ProgramAction = frontend::PluginAction;
Richard Smithbd55daf2012-11-01 04:30:05 +00001466 Opts.ActionName = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001467 }
Nico Weber2992efa2011-01-25 20:34:14 +00001468 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001469 for (const auto *AA : Args.filtered(OPT_plugin_arg))
John Brawn6c789742016-03-15 12:51:40 +00001470 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
Nico Weber2992efa2011-01-25 20:34:14 +00001471
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001472 for (const std::string &Arg :
1473 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1474 std::string BlockName;
1475 unsigned MajorVersion;
1476 unsigned MinorVersion;
1477 bool Hashed;
1478 std::string UserInfo;
1479 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1480 MinorVersion, Hashed, UserInfo)) {
1481 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1482
1483 continue;
1484 }
1485
1486 // Add the testing module file extension.
1487 Opts.ModuleFileExtensions.push_back(
David Blaikie61137e12017-01-05 18:23:18 +00001488 std::make_shared<TestModuleFileExtension>(
1489 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001490 }
1491
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001492 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1493 Opts.CodeCompletionAt =
Richard Smithbd55daf2012-11-01 04:30:05 +00001494 ParsedSourceLocation::FromString(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001495 if (Opts.CodeCompletionAt.FileName.empty())
1496 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001497 << A->getAsString(Args) << A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001498 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001499 Opts.DisableFree = Args.hasArg(OPT_disable_free);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001500
Daniel Dunbar37300482010-05-20 16:54:55 +00001501 Opts.OutputFile = Args.getLastArgValue(OPT_o);
1502 Opts.Plugins = Args.getAllArgValues(OPT_load);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001503 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001504 Opts.ShowHelp = Args.hasArg(OPT_help);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001505 Opts.ShowStats = Args.hasArg(OPT_print_stats);
1506 Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001507 Opts.ShowVersion = Args.hasArg(OPT_version);
Daniel Dunbar37300482010-05-20 16:54:55 +00001508 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1509 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
Nick Lewycky078a5e22010-08-13 17:31:00 +00001510 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
Argyrios Kyrtzidis24e9aff2012-01-26 02:40:48 +00001511 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1512 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1513 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
Richard Smith35f986d2014-08-11 22:11:07 +00001514 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
Richard Smith3a36ac12017-03-09 22:00:01 +00001515 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all);
Alexander Kornienko3db68ee2012-07-26 16:01:23 +00001516 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
Richard Smith6ea05822013-06-24 01:45:33 +00001517 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
Douglas Gregor137f1b92013-01-28 18:38:02 +00001518 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001519 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
Richard Smith4a89a062014-12-06 01:13:41 +00001520 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001521 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001522 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001523 StringRef Val = A->getValue();
1524 if (Val.find('=') == StringRef::npos)
1525 Opts.ModuleFiles.push_back(Val);
1526 }
Richard Smithfb1e7f72015-08-14 05:02:58 +00001527 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
Richard Smith919ce232015-11-24 04:22:21 +00001528 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
Pierre Gousseau533a8932016-07-13 14:21:11 +00001529 Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
Richard Smithe842a472014-10-22 02:05:46 +00001530
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001531 Opts.CodeCompleteOpts.IncludeMacros
1532 = Args.hasArg(OPT_code_completion_macros);
1533 Opts.CodeCompleteOpts.IncludeCodePatterns
1534 = Args.hasArg(OPT_code_completion_patterns);
1535 Opts.CodeCompleteOpts.IncludeGlobals
1536 = !Args.hasArg(OPT_no_code_completion_globals);
Eric Liufead6ae2017-12-13 10:26:49 +00001537 Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls
1538 = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001539 Opts.CodeCompleteOpts.IncludeBriefComments
1540 = Args.hasArg(OPT_code_completion_brief_comments);
Ivan Donchevskiib4670fc2018-05-25 12:56:26 +00001541 Opts.CodeCompleteOpts.IncludeFixIts
1542 = Args.hasArg(OPT_code_completion_with_fixits);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001543
Douglas Gregore9fc3772012-01-26 07:55:45 +00001544 Opts.OverrideRecordLayoutsFile
1545 = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
Artem Belevichb5bc9232015-09-22 17:23:22 +00001546 Opts.AuxTriple =
1547 llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple));
Nico Weber2ca4be92016-03-01 23:16:44 +00001548 Opts.FindPchSource = Args.getLastArgValue(OPT_find_pch_source_EQ);
Matthias Braunabb6eea2016-09-26 18:53:34 +00001549 Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
Artem Belevichb5bc9232015-09-22 17:23:22 +00001550
John McCalld70fb982011-06-15 23:25:17 +00001551 if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001552 OPT_arcmt_modify,
1553 OPT_arcmt_migrate)) {
John McCalld70fb982011-06-15 23:25:17 +00001554 switch (A->getOption().getID()) {
1555 default:
1556 llvm_unreachable("missed a case");
1557 case OPT_arcmt_check:
1558 Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1559 break;
1560 case OPT_arcmt_modify:
1561 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1562 break;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001563 case OPT_arcmt_migrate:
1564 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1565 break;
John McCalld70fb982011-06-15 23:25:17 +00001566 }
1567 }
Ted Kremenekf7639e12012-03-06 20:06:33 +00001568 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +00001569 Opts.ARCMTMigrateReportOut
1570 = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1571 Opts.ARCMTMigrateEmitARCErrors
1572 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
John McCalld70fb982011-06-15 23:25:17 +00001573
Ted Kremenekf7639e12012-03-06 20:06:33 +00001574 if (Args.hasArg(OPT_objcmt_migrate_literals))
1575 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1576 if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1577 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
Fariborz Jahaniana6556f72014-10-31 21:19:45 +00001578 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1579 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001580 if (Args.hasArg(OPT_objcmt_migrate_property))
1581 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +00001582 if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1583 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001584 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1585 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001586 if (Args.hasArg(OPT_objcmt_migrate_annotation))
1587 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
Fariborz Jahanian23417072013-11-05 22:28:30 +00001588 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1589 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001590 if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1591 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
1592 if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1593 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
1594 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1595 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001596 if (Args.hasArg(OPT_objcmt_atomic_property))
1597 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001598 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1599 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001600 if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1601 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001602 if (Args.hasArg(OPT_objcmt_migrate_all))
1603 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001604
Argyrios Kyrtzidisd5ba86b2013-12-10 18:36:53 +00001605 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001606
Ted Kremenekf7639e12012-03-06 20:06:33 +00001607 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1608 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1609 Diags.Report(diag::err_drv_argument_not_allowed_with)
1610 << "ARC migration" << "ObjC migration";
1611 }
1612
Richard Smith40c0efa2017-04-26 18:57:40 +00001613 InputKind DashX(InputKind::Unknown);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001614 if (const Arg *A = Args.getLastArg(OPT_x)) {
Richard Smith40c0efa2017-04-26 18:57:40 +00001615 StringRef XValue = A->getValue();
Richard Smithf74d9462017-04-28 01:49:42 +00001616
1617 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1618 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1619 bool Preprocessed = XValue.consume_back("-cpp-output");
1620 bool ModuleMap = XValue.consume_back("-module-map");
1621 IsHeaderFile =
1622 !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1623
1624 // Principal languages.
Richard Smith40c0efa2017-04-26 18:57:40 +00001625 DashX = llvm::StringSwitch<InputKind>(XValue)
Richard Smithf74d9462017-04-28 01:49:42 +00001626 .Case("c", InputKind::C)
1627 .Case("cl", InputKind::OpenCL)
1628 .Case("cuda", InputKind::CUDA)
Yaxun Liu887c5692018-04-25 01:10:37 +00001629 .Case("hip", InputKind::HIP)
Richard Smithf74d9462017-04-28 01:49:42 +00001630 .Case("c++", InputKind::CXX)
1631 .Case("objective-c", InputKind::ObjC)
1632 .Case("objective-c++", InputKind::ObjCXX)
1633 .Case("renderscript", InputKind::RenderScript)
1634 .Default(InputKind::Unknown);
1635
1636 // "objc[++]-cpp-output" is an acceptable synonym for
1637 // "objective-c[++]-cpp-output".
1638 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1639 DashX = llvm::StringSwitch<InputKind>(XValue)
1640 .Case("objc", InputKind::ObjC)
1641 .Case("objc++", InputKind::ObjCXX)
1642 .Default(InputKind::Unknown);
1643
1644 // Some special cases cannot be combined with suffixes.
1645 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1646 DashX = llvm::StringSwitch<InputKind>(XValue)
1647 .Case("cpp-output", InputKind(InputKind::C).getPreprocessed())
1648 .Case("assembler-with-cpp", InputKind::Asm)
1649 .Cases("ast", "pcm",
1650 InputKind(InputKind::Unknown, InputKind::Precompiled))
1651 .Case("ir", InputKind::LLVM_IR)
1652 .Default(InputKind::Unknown);
1653
Richard Smith40c0efa2017-04-26 18:57:40 +00001654 if (DashX.isUnknown())
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001655 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001656 << A->getAsString(Args) << A->getValue();
Richard Smith40c0efa2017-04-26 18:57:40 +00001657
Richard Smithf74d9462017-04-28 01:49:42 +00001658 if (Preprocessed)
Richard Smith40c0efa2017-04-26 18:57:40 +00001659 DashX = DashX.getPreprocessed();
Richard Smithf74d9462017-04-28 01:49:42 +00001660 if (ModuleMap)
1661 DashX = DashX.withFormat(InputKind::ModuleMap);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001662 }
1663
1664 // '-' is the default input if none is given.
Daniel Dunbar37300482010-05-20 16:54:55 +00001665 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001666 Opts.Inputs.clear();
1667 if (Inputs.empty())
1668 Inputs.push_back("-");
1669 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001670 InputKind IK = DashX;
Richard Smith40c0efa2017-04-26 18:57:40 +00001671 if (IK.isUnknown()) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001672 IK = FrontendOptions::getInputKindForExtension(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001673 StringRef(Inputs[i]).rsplit('.').second);
Richard Smith40c0efa2017-04-26 18:57:40 +00001674 // FIXME: Warn on this?
1675 if (IK.isUnknown())
1676 IK = InputKind::C;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001677 // FIXME: Remove this hack.
1678 if (i == 0)
1679 DashX = IK;
1680 }
Richard Smithf74d9462017-04-28 01:49:42 +00001681
1682 // The -emit-module action implicitly takes a module map.
1683 if (Opts.ProgramAction == frontend::GenerateModule &&
1684 IK.getFormat() == InputKind::Source)
1685 IK = IK.withFormat(InputKind::ModuleMap);
1686
Benjamin Kramer3204b152015-05-29 19:42:19 +00001687 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001688 }
1689
1690 return DashX;
1691}
1692
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001693std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1694 void *MainAddr) {
Alexey Samsonov6465d4f2014-12-29 21:28:15 +00001695 std::string ClangExecutable =
1696 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001697 StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001698
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001699 // Compute the path to the resource directory.
1700 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1701 SmallString<128> P(Dir);
Yaron Kerena9107412015-08-05 20:06:56 +00001702 if (ClangResourceDir != "")
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001703 llvm::sys::path::append(P, ClangResourceDir);
Yaron Kerena9107412015-08-05 20:06:56 +00001704 else
1705 llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX,
1706 "clang", CLANG_VERSION_STRING);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001707
1708 return P.str();
1709}
1710
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00001711static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1712 const std::string &WorkingDir) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001713 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001714 Opts.Verbose = Args.hasArg(OPT_v);
Francois Pichet698f0192011-10-10 20:34:10 +00001715 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
Daniel Dunbarb25bfde2011-10-11 18:20:10 +00001716 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
Douglas Gregor64b046f2010-03-24 20:13:48 +00001717 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
Bob Wilsonb02ea3d2011-06-21 21:12:29 +00001718 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001719 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
Daniel Dunbar37300482010-05-20 16:54:55 +00001720 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00001721
1722 // Canonicalize -fmodules-cache-path before storing it.
1723 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1724 if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1725 if (WorkingDir.empty())
1726 llvm::sys::fs::make_absolute(P);
1727 else
1728 llvm::sys::fs::make_absolute(WorkingDir, P);
1729 }
1730 llvm::sys::path::remove_dots(P);
1731 Opts.ModuleCachePath = P.str();
1732
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001733 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001734 // Only the -fmodule-file=<name>=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001735 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001736 StringRef Val = A->getValue();
1737 if (Val.find('=') != StringRef::npos)
1738 Opts.PrebuiltModuleFiles.insert(Val.split('='));
1739 }
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001740 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
Manman Ren11f2a472016-08-18 17:42:15 +00001741 Opts.AddPrebuiltModulePath(A->getValue());
Douglas Gregor1735f4e2011-09-13 23:15:45 +00001742 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001743 Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
Manman Ren47a44452016-07-26 17:12:17 +00001744 Opts.ModulesValidateDiagnosticOptions =
1745 !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
Richard Smith47972af2015-06-16 00:08:24 +00001746 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
Richard Smith9acb99e32014-12-10 03:09:48 +00001747 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
Reid Kleckner898229a2013-06-14 17:17:23 +00001748 Opts.ModuleCachePruneInterval =
1749 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1750 Opts.ModuleCachePruneAfter =
1751 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00001752 Opts.ModulesValidateOncePerBuildSession =
1753 Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1754 Opts.BuildSessionTimestamp =
1755 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
Ben Langmuirdcf73862014-03-12 00:06:17 +00001756 Opts.ModulesValidateSystemHeaders =
1757 Args.hasArg(OPT_fmodules_validate_system_headers);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00001758 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1759 Opts.ModuleFormat = A->getValue();
Ben Langmuirdcf73862014-03-12 00:06:17 +00001760
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001761 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
Sean Silva14facf32015-06-09 01:57:17 +00001762 StringRef MacroDef = A->getValue();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001763 Opts.ModulesIgnoreMacros.insert(
1764 llvm::CachedHashString(MacroDef.split('=').first));
Douglas Gregor5dc38992013-02-07 00:21:12 +00001765 }
1766
Douglas Gregor9f93e382011-07-28 04:45:53 +00001767 // Add -I..., -F..., and -index-header-map options in order.
1768 bool IsIndexHeaderMap = false;
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001769 bool IsSysrootSpecified =
1770 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001771 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
Sean Silva14facf32015-06-09 01:57:17 +00001772 if (A->getOption().matches(OPT_index_header_map)) {
Douglas Gregor9f93e382011-07-28 04:45:53 +00001773 // -index-header-map applies to the next -I or -F.
1774 IsIndexHeaderMap = true;
1775 continue;
1776 }
Sean Silva14facf32015-06-09 01:57:17 +00001777
1778 frontend::IncludeDirGroup Group =
1779 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1780
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001781 bool IsFramework = A->getOption().matches(OPT_F);
1782 std::string Path = A->getValue();
1783
1784 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1785 SmallString<32> Buffer;
1786 llvm::sys::path::append(Buffer, Opts.Sysroot,
1787 llvm::StringRef(A->getValue()).substr(1));
1788 Path = Buffer.str();
1789 }
1790
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001791 Opts.AddPath(Path, Group, IsFramework,
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001792 /*IgnoreSysroot*/ true);
Douglas Gregor9f93e382011-07-28 04:45:53 +00001793 IsIndexHeaderMap = false;
1794 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001795
Daniel Dunbarc9c57e92013-01-25 01:50:34 +00001796 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001797 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001798 for (const auto *A :
Sean Silva14facf32015-06-09 01:57:17 +00001799 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00001800 if (A->getOption().matches(OPT_iprefix))
Richard Smithbd55daf2012-11-01 04:30:05 +00001801 Prefix = A->getValue();
Daniel Dunbara442fd52010-06-11 22:00:13 +00001802 else if (A->getOption().matches(OPT_iwithprefix))
Sean Silva14facf32015-06-09 01:57:17 +00001803 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001804 else
Sean Silva14facf32015-06-09 01:57:17 +00001805 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001806 }
1807
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001808 for (const auto *A : Args.filtered(OPT_idirafter))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001809 Opts.AddPath(A->getValue(), frontend::After, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001810 for (const auto *A : Args.filtered(OPT_iquote))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001811 Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001812 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001813 Opts.AddPath(A->getValue(), frontend::System, false,
1814 !A->getOption().matches(OPT_iwithsysroot));
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001815 for (const auto *A : Args.filtered(OPT_iframework))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001816 Opts.AddPath(A->getValue(), frontend::System, true, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001817 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001818 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
1819 /*IgnoreSysRoot=*/false);
1820
1821 // Add the paths for the various language specific isystem flags.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001822 for (const auto *A : Args.filtered(OPT_c_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001823 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001824 for (const auto *A : Args.filtered(OPT_cxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001825 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001826 for (const auto *A : Args.filtered(OPT_objc_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001827 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001828 for (const auto *A : Args.filtered(OPT_objcxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001829 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1830
1831 // Add the internal paths from a driver that detects standard include paths.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001832 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001833 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1834 frontend::IncludeDirGroup Group = frontend::System;
1835 if (A->getOption().matches(OPT_internal_externc_isystem))
1836 Group = frontend::ExternCSystem;
1837 Opts.AddPath(A->getValue(), Group, false, true);
1838 }
1839
1840 // Add the path prefixes which are implicitly treated as being system headers.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001841 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001842 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1843 Opts.AddSystemHeaderPrefix(
1844 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1845
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001846 for (const auto *A : Args.filtered(OPT_ivfsoverlay))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001847 Opts.AddVFSOverlayFile(A->getValue());
1848}
1849
1850void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1851 const llvm::Triple &T,
1852 PreprocessorOptions &PPOpts,
1853 LangStandard::Kind LangStd) {
1854 // Set some properties which depend solely on the input kind; it would be nice
1855 // to move these to the language standard, and have the driver resolve the
1856 // input kind + language standard.
1857 //
1858 // FIXME: Perhaps a better model would be for a single source file to have
1859 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
1860 // simultaneously active?
1861 if (IK.getLanguage() == InputKind::Asm) {
1862 Opts.AsmPreprocessor = 1;
1863 } else if (IK.isObjectiveC()) {
1864 Opts.ObjC1 = Opts.ObjC2 = 1;
1865 }
1866
1867 if (LangStd == LangStandard::lang_unspecified) {
1868 // Based on the base language, pick one.
1869 switch (IK.getLanguage()) {
1870 case InputKind::Unknown:
1871 case InputKind::LLVM_IR:
1872 llvm_unreachable("Invalid input kind!");
1873 case InputKind::OpenCL:
1874 LangStd = LangStandard::lang_opencl10;
1875 break;
1876 case InputKind::CUDA:
1877 LangStd = LangStandard::lang_cuda;
1878 break;
1879 case InputKind::Asm:
1880 case InputKind::C:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001881#if defined(CLANG_DEFAULT_STD_C)
1882 LangStd = CLANG_DEFAULT_STD_C;
1883#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001884 // The PS4 uses C99 as the default C standard.
1885 if (T.isPS4())
1886 LangStd = LangStandard::lang_gnu99;
1887 else
1888 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001889#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001890 break;
1891 case InputKind::ObjC:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001892#if defined(CLANG_DEFAULT_STD_C)
1893 LangStd = CLANG_DEFAULT_STD_C;
1894#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001895 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001896#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001897 break;
1898 case InputKind::CXX:
1899 case InputKind::ObjCXX:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001900#if defined(CLANG_DEFAULT_STD_CXX)
1901 LangStd = CLANG_DEFAULT_STD_CXX;
1902#else
Tim Northover36bb6d52017-12-09 12:09:54 +00001903 LangStd = LangStandard::lang_gnucxx14;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001904#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001905 break;
1906 case InputKind::RenderScript:
1907 LangStd = LangStandard::lang_c99;
1908 break;
Yaxun Liu887c5692018-04-25 01:10:37 +00001909 case InputKind::HIP:
1910 LangStd = LangStandard::lang_hip;
1911 break;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001912 }
1913 }
1914
1915 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1916 Opts.LineComment = Std.hasLineComments();
1917 Opts.C99 = Std.isC99();
1918 Opts.C11 = Std.isC11();
1919 Opts.C17 = Std.isC17();
1920 Opts.CPlusPlus = Std.isCPlusPlus();
1921 Opts.CPlusPlus11 = Std.isCPlusPlus11();
1922 Opts.CPlusPlus14 = Std.isCPlusPlus14();
1923 Opts.CPlusPlus17 = Std.isCPlusPlus17();
1924 Opts.CPlusPlus2a = Std.isCPlusPlus2a();
1925 Opts.Digraphs = Std.hasDigraphs();
1926 Opts.GNUMode = Std.isGNUMode();
1927 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
1928 Opts.HexFloats = Std.hasHexFloats();
1929 Opts.ImplicitInt = Std.hasImplicitInt();
1930
1931 // Set OpenCL Version.
1932 Opts.OpenCL = Std.isOpenCL();
1933 if (LangStd == LangStandard::lang_opencl10)
1934 Opts.OpenCLVersion = 100;
1935 else if (LangStd == LangStandard::lang_opencl11)
1936 Opts.OpenCLVersion = 110;
1937 else if (LangStd == LangStandard::lang_opencl12)
1938 Opts.OpenCLVersion = 120;
1939 else if (LangStd == LangStandard::lang_opencl20)
1940 Opts.OpenCLVersion = 200;
Anastasia Stulovac645f612018-04-12 14:17:04 +00001941 else if (LangStd == LangStandard::lang_openclcpp)
1942 Opts.OpenCLCPlusPlusVersion = 100;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001943
1944 // OpenCL has some additional defaults.
1945 if (Opts.OpenCL) {
1946 Opts.AltiVec = 0;
1947 Opts.ZVector = 0;
1948 Opts.LaxVectorConversions = 0;
1949 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
1950 Opts.NativeHalfType = 1;
1951 Opts.NativeHalfArgsAndReturns = 1;
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00001952 Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001953 // Include default header file for OpenCL.
1954 if (Opts.IncludeDefaultHeader) {
1955 PPOpts.Includes.push_back("opencl-c.h");
1956 }
1957 }
1958
Yaxun Liu887c5692018-04-25 01:10:37 +00001959 Opts.HIP = IK.getLanguage() == InputKind::HIP;
1960 Opts.CUDA = IK.getLanguage() == InputKind::CUDA || Opts.HIP;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001961 if (Opts.CUDA)
1962 // Set default FP_CONTRACT to FAST.
1963 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
1964
1965 Opts.RenderScript = IK.getLanguage() == InputKind::RenderScript;
1966 if (Opts.RenderScript) {
1967 Opts.NativeHalfType = 1;
1968 Opts.NativeHalfArgsAndReturns = 1;
1969 }
1970
1971 // OpenCL and C++ both have bool, true, false keywords.
1972 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1973
1974 // OpenCL has half keyword
1975 Opts.Half = Opts.OpenCL;
1976
1977 // C++ has wchar_t keyword.
1978 Opts.WChar = Opts.CPlusPlus;
1979
1980 Opts.GNUKeywords = Opts.GNUMode;
1981 Opts.CXXOperatorNames = Opts.CPlusPlus;
1982
1983 Opts.AlignedAllocation = Opts.CPlusPlus17;
1984
1985 Opts.DollarIdents = !Opts.AsmPreprocessor;
1986}
1987
1988/// Attempt to parse a visibility value out of the given argument.
1989static Visibility parseVisibility(Arg *arg, ArgList &args,
1990 DiagnosticsEngine &diags) {
1991 StringRef value = arg->getValue();
1992 if (value == "default") {
1993 return DefaultVisibility;
1994 } else if (value == "hidden" || value == "internal") {
1995 return HiddenVisibility;
1996 } else if (value == "protected") {
1997 // FIXME: diagnose if target does not support protected visibility
1998 return ProtectedVisibility;
1999 }
2000
2001 diags.Report(diag::err_drv_invalid_value)
2002 << arg->getAsString(args) << value;
2003 return DefaultVisibility;
2004}
2005
2006/// Check if input file kind and language standard are compatible.
2007static bool IsInputCompatibleWithStandard(InputKind IK,
2008 const LangStandard &S) {
2009 switch (IK.getLanguage()) {
2010 case InputKind::Unknown:
2011 case InputKind::LLVM_IR:
2012 llvm_unreachable("should not parse language flags for this input");
2013
2014 case InputKind::C:
2015 case InputKind::ObjC:
2016 case InputKind::RenderScript:
2017 return S.getLanguage() == InputKind::C;
2018
2019 case InputKind::OpenCL:
2020 return S.getLanguage() == InputKind::OpenCL;
2021
2022 case InputKind::CXX:
2023 case InputKind::ObjCXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002024 return S.getLanguage() == InputKind::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002025
2026 case InputKind::CUDA:
Richard Smithb0fe7042017-04-26 23:44:33 +00002027 // FIXME: What -std= values should be permitted for CUDA compilations?
2028 return S.getLanguage() == InputKind::CUDA ||
2029 S.getLanguage() == InputKind::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002030
Yaxun Liu887c5692018-04-25 01:10:37 +00002031 case InputKind::HIP:
2032 return S.getLanguage() == InputKind::CXX ||
2033 S.getLanguage() == InputKind::HIP;
2034
Richard Smith40c0efa2017-04-26 18:57:40 +00002035 case InputKind::Asm:
2036 // Accept (and ignore) all -std= values.
2037 // FIXME: The -std= value is not ignored; it affects the tokenization
2038 // and preprocessing rules if we're preprocessing this asm input.
Richard Smith222b30b2017-02-14 23:41:38 +00002039 return true;
Richard Smithc91daf12017-02-14 22:44:20 +00002040 }
Richard Smith40c0efa2017-04-26 18:57:40 +00002041
2042 llvm_unreachable("unexpected input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002043}
2044
2045/// Get language name for given input kind.
2046static const StringRef GetInputKindName(InputKind IK) {
Richard Smith40c0efa2017-04-26 18:57:40 +00002047 switch (IK.getLanguage()) {
2048 case InputKind::C:
Richard Smithb0fe7042017-04-26 23:44:33 +00002049 return "C";
Richard Smith40c0efa2017-04-26 18:57:40 +00002050 case InputKind::ObjC:
Richard Smithb0fe7042017-04-26 23:44:33 +00002051 return "Objective-C";
Richard Smith40c0efa2017-04-26 18:57:40 +00002052 case InputKind::CXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002053 return "C++";
Richard Smith40c0efa2017-04-26 18:57:40 +00002054 case InputKind::ObjCXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002055 return "Objective-C++";
Richard Smith40c0efa2017-04-26 18:57:40 +00002056 case InputKind::OpenCL:
Richard Smithc91daf12017-02-14 22:44:20 +00002057 return "OpenCL";
Richard Smith40c0efa2017-04-26 18:57:40 +00002058 case InputKind::CUDA:
Richard Smithc91daf12017-02-14 22:44:20 +00002059 return "CUDA";
Richard Smithb0fe7042017-04-26 23:44:33 +00002060 case InputKind::RenderScript:
2061 return "RenderScript";
Yaxun Liu887c5692018-04-25 01:10:37 +00002062 case InputKind::HIP:
2063 return "HIP";
Richard Smithb0fe7042017-04-26 23:44:33 +00002064
2065 case InputKind::Asm:
2066 return "Asm";
2067 case InputKind::LLVM_IR:
2068 return "LLVM IR";
2069
2070 case InputKind::Unknown:
2071 break;
Richard Smithc91daf12017-02-14 22:44:20 +00002072 }
Richard Smithb0fe7042017-04-26 23:44:33 +00002073 llvm_unreachable("unknown input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002074}
2075
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002076static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002077 const TargetOptions &TargetOpts,
Yaxun Liu143f0832016-06-20 19:26:00 +00002078 PreprocessorOptions &PPOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00002079 DiagnosticsEngine &Diags) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002080 // FIXME: Cleanup per-file based stuff.
2081 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2082 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002083 LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
Richard Smithb0fe7042017-04-26 23:44:33 +00002084#define LANGSTANDARD(id, name, lang, desc, features) \
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002085 .Case(name, LangStandard::lang_##id)
Yaxun Liub5044fe2016-06-17 17:19:28 +00002086#define LANGSTANDARD_ALIAS(id, alias) \
2087 .Case(alias, LangStandard::lang_##id)
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002088#include "clang/Frontend/LangStandards.def"
2089 .Default(LangStandard::lang_unspecified);
Richard Smithc91daf12017-02-14 22:44:20 +00002090 if (LangStd == LangStandard::lang_unspecified) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002091 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00002092 << A->getAsString(Args) << A->getValue();
Richard Smithc91daf12017-02-14 22:44:20 +00002093 // Report supported standards with short description.
2094 for (unsigned KindValue = 0;
2095 KindValue != LangStandard::lang_unspecified;
2096 ++KindValue) {
2097 const LangStandard &Std = LangStandard::getLangStandardForKind(
2098 static_cast<LangStandard::Kind>(KindValue));
2099 if (IsInputCompatibleWithStandard(IK, Std)) {
Richard Smith8c8fb802017-04-27 01:17:05 +00002100 auto Diag = Diags.Report(diag::note_drv_use_standard);
2101 Diag << Std.getName() << Std.getDescription();
2102 unsigned NumAliases = 0;
2103#define LANGSTANDARD(id, name, lang, desc, features)
2104#define LANGSTANDARD_ALIAS(id, alias) \
2105 if (KindValue == LangStandard::lang_##id) ++NumAliases;
2106#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2107#include "clang/Frontend/LangStandards.def"
2108 Diag << NumAliases;
2109#define LANGSTANDARD(id, name, lang, desc, features)
2110#define LANGSTANDARD_ALIAS(id, alias) \
2111 if (KindValue == LangStandard::lang_##id) Diag << alias;
2112#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2113#include "clang/Frontend/LangStandards.def"
Richard Smithc91daf12017-02-14 22:44:20 +00002114 }
2115 }
2116 } else {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002117 // Valid standard, check to make sure language and standard are
2118 // compatible.
Chad Rosier24874a42011-05-02 19:24:53 +00002119 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
Richard Smithc91daf12017-02-14 22:44:20 +00002120 if (!IsInputCompatibleWithStandard(IK, Std)) {
2121 Diags.Report(diag::err_drv_argument_not_allowed_with)
2122 << A->getAsString(Args) << GetInputKindName(IK);
Chad Rosier24874a42011-05-02 19:24:53 +00002123 }
2124 }
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002125 }
2126
Oren Ben Simhon220671a2018-03-17 13:31:35 +00002127 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2128 StringRef Name = A->getValue();
2129 if (Name == "full" || Name == "branch") {
2130 Opts.CFProtectionBranch = 1;
2131 }
2132 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002133 // -cl-std only applies for OpenCL language standards.
2134 // Override the -std option in this case.
Peter Collingbournefafa6652010-12-04 01:51:40 +00002135 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002136 LangStandard::Kind OpenCLLangStd
Richard Smithc91daf12017-02-14 22:44:20 +00002137 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
Richard Smith8c8fb802017-04-27 01:17:05 +00002138 .Cases("cl", "CL", LangStandard::lang_opencl10)
Richard Smithc91daf12017-02-14 22:44:20 +00002139 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2140 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2141 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
Anastasia Stulovac645f612018-04-12 14:17:04 +00002142 .Case("c++", LangStandard::lang_openclcpp)
Richard Smithc91daf12017-02-14 22:44:20 +00002143 .Default(LangStandard::lang_unspecified);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002144
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002145 if (OpenCLLangStd == LangStandard::lang_unspecified) {
Peter Collingbournefafa6652010-12-04 01:51:40 +00002146 Diags.Report(diag::err_drv_invalid_value)
Richard Smithc91daf12017-02-14 22:44:20 +00002147 << A->getAsString(Args) << A->getValue();
Peter Collingbournefafa6652010-12-04 01:51:40 +00002148 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002149 else
2150 LangStd = OpenCLLangStd;
Peter Collingbournefafa6652010-12-04 01:51:40 +00002151 }
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002152
Yaxun Liu143f0832016-06-20 19:26:00 +00002153 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2154
Sunil Srivastavabf010802016-04-27 19:53:03 +00002155 llvm::Triple T(TargetOpts.Triple);
Yaxun Liu143f0832016-06-20 19:26:00 +00002156 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002157
Yaxun Liu02c39792016-07-13 21:21:05 +00002158 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2159 // This option should be deprecated for CL > 1.0 because
2160 // this option was added for compatibility with OpenCL 1.0.
2161 if (Args.getLastArg(OPT_cl_strict_aliasing)
2162 && Opts.OpenCLVersion > 100) {
Yaxun Liu02c39792016-07-13 21:21:05 +00002163 Diags.Report(diag::warn_option_invalid_ocl_version)
Sven van Haastregt35b61392018-05-08 13:47:43 +00002164 << Opts.getOpenCLVersionTuple().getAsString()
2165 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
Yaxun Liu02c39792016-07-13 21:21:05 +00002166 }
2167
Chandler Carruthe03aa552010-04-17 20:17:31 +00002168 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2169 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2170 // while a subset (the non-C++ GNU keywords) is provided by GCC's
2171 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2172 // name, as it doesn't seem a useful distinction.
2173 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002174 Opts.GNUKeywords);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002175
Erich Keaned46083c2017-05-25 16:24:49 +00002176 if (Args.hasArg(OPT_fno_operator_names))
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002177 Opts.CXXOperatorNames = 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002178
Reid Klecknerbbc01782014-12-03 21:53:36 +00002179 if (Args.hasArg(OPT_fcuda_is_device))
2180 Opts.CUDAIsDevice = 1;
2181
Justin Lebar1eac5942016-01-26 17:47:20 +00002182 if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2183 Opts.CUDAAllowVariadicFunctions = 1;
2184
Justin Lebarba122ab2016-03-30 23:30:21 +00002185 if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2186 Opts.CUDAHostDeviceConstexpr = 0;
2187
Justin Lebard3a44f62016-04-05 18:26:20 +00002188 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_flush_denormals_to_zero))
2189 Opts.CUDADeviceFlushDenormalsToZero = 1;
2190
Justin Lebar91f6f072016-05-23 20:19:56 +00002191 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2192 Opts.CUDADeviceApproxTranscendentals = 1;
2193
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00002194 Opts.CUDARelocatableDeviceCode = Args.hasArg(OPT_fcuda_rdc);
2195
John McCall31168b02011-06-15 23:02:42 +00002196 if (Opts.ObjC1) {
John McCall5fb5df92012-06-20 06:18:46 +00002197 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002198 StringRef value = arg->getValue();
John McCall5fb5df92012-06-20 06:18:46 +00002199 if (Opts.ObjCRuntime.tryParse(value))
2200 Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2201 }
2202
John McCall31168b02011-06-15 23:02:42 +00002203 if (Args.hasArg(OPT_fobjc_gc_only))
Douglas Gregor79a91412011-09-13 17:21:33 +00002204 Opts.setGC(LangOptions::GCOnly);
John McCall31168b02011-06-15 23:02:42 +00002205 else if (Args.hasArg(OPT_fobjc_gc))
Douglas Gregor79a91412011-09-13 17:21:33 +00002206 Opts.setGC(LangOptions::HybridGC);
John McCall31168b02011-06-15 23:02:42 +00002207 else if (Args.hasArg(OPT_fobjc_arc)) {
2208 Opts.ObjCAutoRefCount = 1;
John McCall3deb1ad2012-08-21 02:47:43 +00002209 if (!Opts.ObjCRuntime.allowsARC())
2210 Diags.Report(diag::err_arc_unsupported_on_runtime);
John McCall460ce582015-10-22 18:38:17 +00002211 }
John McCall31168b02011-06-15 23:02:42 +00002212
John McCall460ce582015-10-22 18:38:17 +00002213 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2214 // whether the feature is actually enabled. This is predominantly
2215 // determined by -fobjc-runtime, but we allow it to be overridden
2216 // from the command line for testing purposes.
2217 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2218 Opts.ObjCWeakRuntime = 1;
2219 else
2220 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2221
2222 // ObjCWeak determines whether __weak is actually enabled.
John McCallfbe5ed72015-11-05 19:19:56 +00002223 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2224 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2225 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2226 assert(!Opts.ObjCWeak);
2227 } else if (Opts.getGC() != LangOptions::NonGC) {
John McCall460ce582015-10-22 18:38:17 +00002228 Diags.Report(diag::err_objc_weak_with_gc);
John McCallfbe5ed72015-11-05 19:19:56 +00002229 } else if (!Opts.ObjCWeakRuntime) {
John McCall460ce582015-10-22 18:38:17 +00002230 Diags.Report(diag::err_objc_weak_unsupported);
John McCallfbe5ed72015-11-05 19:19:56 +00002231 } else {
2232 Opts.ObjCWeak = 1;
John McCall460ce582015-10-22 18:38:17 +00002233 }
John McCallfbe5ed72015-11-05 19:19:56 +00002234 } else if (Opts.ObjCAutoRefCount) {
2235 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
John McCall3deb1ad2012-08-21 02:47:43 +00002236 }
John McCall24fc0de2011-07-06 00:26:06 +00002237
John McCall31168b02011-06-15 23:02:42 +00002238 if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2239 Opts.ObjCInferRelatedResultType = 0;
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002240
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00002241 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2242 Opts.ObjCSubscriptingLegacyRuntime =
2243 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
John McCall31168b02011-06-15 23:02:42 +00002244 }
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002245
Peter Collingbourne470d9422015-05-13 22:07:22 +00002246 if (Args.hasArg(OPT_fgnu89_inline)) {
2247 if (Opts.CPlusPlus)
Richard Smithc91daf12017-02-14 22:44:20 +00002248 Diags.Report(diag::err_drv_argument_not_allowed_with)
2249 << "-fgnu89-inline" << GetInputKindName(IK);
Peter Collingbourne470d9422015-05-13 22:07:22 +00002250 else
2251 Opts.GNUInline = 1;
2252 }
Rafael Espindolafb2af642011-06-02 16:13:27 +00002253
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00002254 if (Args.hasArg(OPT_fapple_kext)) {
2255 if (!Opts.CPlusPlus)
2256 Diags.Report(diag::warn_c_kext);
2257 else
2258 Opts.AppleKext = 1;
2259 }
2260
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002261 if (Args.hasArg(OPT_print_ivar_layout))
2262 Opts.ObjCGCBitmapPrint = 1;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002263 if (Args.hasArg(OPT_fno_constant_cfstrings))
2264 Opts.NoConstantCFStrings = 1;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002265
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00002266 if (Args.hasArg(OPT_fzvector))
2267 Opts.ZVector = 1;
2268
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002269 if (Args.hasArg(OPT_pthread))
2270 Opts.POSIXThreads = 1;
2271
John McCallb4a99d32013-02-19 01:57:35 +00002272 // The value-visibility mode defaults to "default".
2273 if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2274 Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2275 } else {
2276 Opts.setValueVisibilityMode(DefaultVisibility);
2277 }
2278
2279 // The type-visibility mode defaults to the value-visibility mode.
2280 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2281 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2282 } else {
2283 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2284 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002285
Douglas Gregor08329632010-06-15 17:05:35 +00002286 if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2287 Opts.InlineVisibilityHidden = 1;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002288
David Chisnalldd84ef12010-09-17 18:29:54 +00002289 if (Args.hasArg(OPT_ftrapv)) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002290 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
David Chisnalldd84ef12010-09-17 18:29:54 +00002291 // Set the handler, if one is specified.
2292 Opts.OverflowHandler =
2293 Args.getLastArgValue(OPT_ftrapv_handler);
2294 }
Chris Lattner51924e512010-06-26 21:25:03 +00002295 else if (Args.hasArg(OPT_fwrapv))
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002296 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002297
Nico Weberb62ba512014-12-22 18:35:03 +00002298 Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2299 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2300 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
David Majnemerc371ff02015-03-22 08:39:22 +00002301 Opts.MSCompatibilityVersion = 0;
2302 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2303 VersionTuple VT;
2304 if (VT.tryParse(A->getValue()))
2305 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2306 << A->getValue();
2307 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2308 VT.getMinor().getValueOr(0) * 100000 +
2309 VT.getSubminor().getValueOr(0);
2310 }
Nico Weberb62ba512014-12-22 18:35:03 +00002311
2312 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
2313 // is specified, or -std is set to a conforming mode.
2314 // Trigraphs are disabled by default in c++1z onwards.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002315 Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
Nico Weber00721502014-12-23 22:32:37 +00002316 Opts.Trigraphs =
2317 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002318
Daniel Dunbar15cef0e2009-12-16 20:10:18 +00002319 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2320 OPT_fno_dollars_in_identifiers,
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002321 Opts.DollarIdents);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002322 Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002323 Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
Dawn Perchik68bb1b42010-09-02 23:59:25 +00002324 Opts.Borland = Args.hasArg(OPT_fborland_extensions);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002325 Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
Chandler Carruthb009b142011-04-23 06:30:43 +00002326 Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2327 Opts.ConstStrings);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002328 if (Args.hasArg(OPT_fno_lax_vector_conversions))
Anders Carlssonfcd764a2010-02-06 23:23:06 +00002329 Opts.LaxVectorConversions = 0;
2330 if (Args.hasArg(OPT_fno_threadsafe_statics))
Anders Carlsson5d40c6f2010-02-11 08:02:13 +00002331 Opts.ThreadsafeStatics = 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002332 Opts.Exceptions = Args.hasArg(OPT_fexceptions);
Anders Carlsson3320e152011-02-22 01:52:06 +00002333 Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
Anders Carlsson33e56a02011-02-23 03:16:42 +00002334 Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
Martell Malonec950c652017-11-29 07:25:12 +00002335
Leonard Chanf921d852018-06-04 16:07:52 +00002336 // -ffixed-point
2337 Opts.FixedPoint =
2338 Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2339 !Opts.CPlusPlus;
2340
Martell Malonec950c652017-11-29 07:25:12 +00002341 // Handle exception personalities
2342 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
2343 options::OPT_fseh_exceptions,
2344 options::OPT_fdwarf_exceptions);
2345 if (A) {
2346 const Option &Opt = A->getOption();
2347 Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2348 Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2349 Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2350 }
2351
David Majnemer960813e2016-02-20 09:23:47 +00002352 Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
Daniel Dunbar1057f862011-03-18 21:23:38 +00002353 Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
Anders Carlsson33e56a02011-02-23 03:16:42 +00002354
Yunzhong Gaobacf7e42016-01-26 20:15:02 +00002355 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
David Majnemerf6072342014-07-01 22:24:56 +00002356 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
Yaxun Liu18e3fd32016-06-14 21:43:01 +00002357 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
Anastasia Stulovac645f612018-04-12 14:17:04 +00002358 && Opts.OpenCLVersion == 200);
John McCall7959fee2011-09-09 20:41:01 +00002359 Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
Gor Nishanov4ffb4342016-10-02 03:31:58 +00002360 Opts.CoroutinesTS = Args.hasArg(OPT_fcoroutines_ts);
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002361
Aaron Ballman606093a2017-10-15 15:01:42 +00002362 // Enable [[]] attributes in C++11 by default.
2363 Opts.DoubleSquareBracketAttributes =
2364 Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2365 OPT_fno_double_square_bracket_attributes, Opts.CPlusPlus11);
2366
Richard Smithc7bf3802016-07-23 02:32:21 +00002367 Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2368 Opts.Modules = Args.hasArg(OPT_fmodules) || Opts.ModulesTS;
Daniel Jasper962b38e2014-04-11 11:47:45 +00002369 Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2370 Opts.ModulesDeclUse =
2371 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
Richard Smithee977932015-05-01 21:22:17 +00002372 Opts.ModulesLocalVisibility =
Richard Smithc7bf3802016-07-23 02:32:21 +00002373 Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS;
David Blaikief63556d2017-04-12 20:58:33 +00002374 Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2375 Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
John Thompson2255f2c2014-04-23 12:57:01 +00002376 Opts.ModulesSearchAll = Opts.Modules &&
2377 !Args.hasArg(OPT_fno_modules_search_all) &&
2378 Args.hasArg(OPT_fmodules_search_all);
Richard Smith3d23c422014-05-07 02:25:43 +00002379 Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
Manuel Klimekd2e8b042015-02-20 11:44:41 +00002380 Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
David Tweed2da64382013-09-09 09:17:24 +00002381 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
Abramo Bagnara73bf7f52012-09-05 17:30:57 +00002382 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
Richard Smith3a8244d2018-05-01 05:02:45 +00002383 Opts.Char8 = Args.hasArg(OPT_fchar8__t);
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002384 if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2385 Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2386 .Case("char", 1)
2387 .Case("short", 2)
2388 .Case("int", 4)
2389 .Default(0);
2390 if (Opts.WCharSize == 0)
2391 Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2392 }
2393 Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00002394 Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002395 Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2396 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00002397 if (!Opts.NoBuiltin)
2398 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
Eli Benderskyaefa5e22013-07-23 00:13:01 +00002399 Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
Richard Smith26b86ea2016-12-31 21:41:23 +00002400 Opts.RelaxedTemplateTemplateArgs =
2401 Args.hasArg(OPT_frelaxed_template_template_args);
Reid Kleckner7ffc3fb2015-03-20 00:31:07 +00002402 Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
Richard Smith59139022016-09-30 22:41:36 +00002403 Opts.AlignedAllocation =
2404 Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2405 Opts.AlignedAllocation);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002406 Opts.AlignedAllocationUnavailable =
2407 Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
Richard Smith59139022016-09-30 22:41:36 +00002408 Opts.NewAlignOverride =
2409 getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2410 if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2411 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2412 Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2413 << A->getValue();
2414 Opts.NewAlignOverride = 0;
2415 }
Faisal Vali24d59d12015-05-22 01:11:10 +00002416 Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002417 Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
John McCall3155f572010-04-09 19:03:51 +00002418 Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002419 Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
David Tweed2da64382013-09-09 09:17:24 +00002420 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
Reid Kleckner898229a2013-06-14 17:17:23 +00002421 Opts.InstantiationDepth =
Richard Smithe55b4732016-08-17 21:41:45 +00002422 getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
Richard Smith79c927b2013-11-06 19:31:51 +00002423 Opts.ArrowDepth =
2424 getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00002425 Opts.ConstexprCallDepth =
2426 getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2427 Opts.ConstexprStepLimit =
2428 getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2429 Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
Francois Pichet1c229c02011-04-22 22:18:13 +00002430 Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
Reid Kleckner898229a2013-06-14 17:17:23 +00002431 Opts.NumLargeByValueCopy =
2432 getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
Douglas Gregordbe39272011-02-01 15:15:22 +00002433 Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
Daniel Dunbar37300482010-05-20 16:54:55 +00002434 Opts.ObjCConstantStringClass =
2435 Args.getLastArgValue(OPT_fconstant_string_class);
Ted Kremenek1d56c9e2010-12-23 21:35:43 +00002436 Opts.ObjCDefaultSynthProperties =
Rafael Espindolaea1ba0a2013-09-27 20:21:48 +00002437 !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00002438 Opts.EncodeExtendedBlockSig =
2439 Args.hasArg(OPT_fencode_extended_block_signature);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002440 Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
Reid Kleckner898229a2013-06-14 17:17:23 +00002441 Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00002442 Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
Reid Kleckner8195f692016-05-04 02:58:24 +00002443 Opts.AlignDouble = Args.hasArg(OPT_malign_double);
Reid Kleckner898229a2013-06-14 17:17:23 +00002444 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002445 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002446 Opts.Static = Args.hasArg(OPT_static_define);
Douglas Gregore9fc3772012-01-26 07:55:45 +00002447 Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002448 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
Douglas Gregore9fc3772012-01-26 07:55:45 +00002449 || Args.hasArg(OPT_fdump_record_layouts);
Anders Carlsson11e51402010-04-17 20:15:18 +00002450 Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002451 Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
Daniel Dunbar9302f602010-04-15 15:06:22 +00002452 Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002453 Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
Peter Collingbourne61d6a752010-12-04 01:51:23 +00002454 Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
Tony Linthicum76329bf2011-12-12 21:14:55 +00002455 Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002456 Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
John McCall39439732011-04-09 22:50:59 +00002457 Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
John McCall3f4138c2011-07-13 17:56:40 +00002458 Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
Sean Callanan1ce3a6b2012-02-04 01:29:37 +00002459 Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
Ted Kremenekf7639e12012-03-06 20:06:33 +00002460 Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
Eli Friedman055c9702011-11-02 01:53:16 +00002461 Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002462 Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ);
2463 Opts.CurrentModule = Opts.ModuleName;
Bob Wilsonb111ec92015-03-02 19:01:14 +00002464 Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
Ben Langmuir532d2102015-02-02 21:56:15 +00002465 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002466 llvm::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end());
Pirama Arumuga Nainare9bcddd2015-05-14 23:44:18 +00002467 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00002468 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2469 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2470 // is enabled.
2471 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2472 | Opts.NativeHalfArgsAndReturns;
Steven Wucb0d13f2015-01-16 23:05:28 +00002473 Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
Ben Langmuirb537a3a2014-07-23 15:30:23 +00002474
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002475 // __declspec is enabled by default for the PS4 by the driver, and also
2476 // enabled for Microsoft Extensions or Borland Extensions, here.
2477 //
2478 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
Justin Lebar2dfbe9a2016-10-08 22:16:08 +00002479 // CUDA extension. However, it is required for supporting
2480 // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2481 // been rewritten in terms of something more generic, remove the Opts.CUDA
2482 // term here.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002483 Opts.DeclSpecKeyword =
2484 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2485 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2486
David Tweed31d09b02013-09-13 12:04:22 +00002487 if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2488 switch (llvm::StringSwitch<unsigned>(A->getValue())
2489 .Case("target", LangOptions::ASMM_Target)
2490 .Case("no", LangOptions::ASMM_Off)
2491 .Case("yes", LangOptions::ASMM_On)
2492 .Default(255)) {
2493 default:
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002494 Diags.Report(diag::err_drv_invalid_value)
David Tweed31d09b02013-09-13 12:04:22 +00002495 << "-faddress-space-map-mangling=" << A->getValue();
2496 break;
2497 case LangOptions::ASMM_Target:
2498 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2499 break;
2500 case LangOptions::ASMM_On:
2501 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2502 break;
2503 case LangOptions::ASMM_Off:
2504 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2505 break;
2506 }
2507 }
2508
David Majnemer86c318f2014-02-11 21:05:00 +00002509 if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2510 LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
2511 llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2512 A->getValue())
2513 .Case("single",
2514 LangOptions::PPTMK_FullGeneralitySingleInheritance)
2515 .Case("multiple",
2516 LangOptions::PPTMK_FullGeneralityMultipleInheritance)
2517 .Case("virtual",
2518 LangOptions::PPTMK_FullGeneralityVirtualInheritance)
2519 .Default(LangOptions::PPTMK_BestCase);
2520 if (InheritanceModel == LangOptions::PPTMK_BestCase)
2521 Diags.Report(diag::err_drv_invalid_value)
2522 << "-fms-memptr-rep=" << A->getValue();
2523
2524 Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2525 }
2526
Alexey Bataeva7547182016-05-18 09:06:38 +00002527 // Check for MS default calling conventions being specified.
2528 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2529 LangOptions::DefaultCallingConvention DefaultCC =
Erich Keanea957ffb2017-11-02 21:08:00 +00002530 llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
Alexey Bataeva7547182016-05-18 09:06:38 +00002531 .Case("cdecl", LangOptions::DCC_CDecl)
2532 .Case("fastcall", LangOptions::DCC_FastCall)
2533 .Case("stdcall", LangOptions::DCC_StdCall)
2534 .Case("vectorcall", LangOptions::DCC_VectorCall)
Erich Keanea957ffb2017-11-02 21:08:00 +00002535 .Case("regcall", LangOptions::DCC_RegCall)
Alexey Bataeva7547182016-05-18 09:06:38 +00002536 .Default(LangOptions::DCC_None);
2537 if (DefaultCC == LangOptions::DCC_None)
2538 Diags.Report(diag::err_drv_invalid_value)
2539 << "-fdefault-calling-conv=" << A->getValue();
2540
2541 llvm::Triple T(TargetOpts.Triple);
2542 llvm::Triple::ArchType Arch = T.getArch();
2543 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
Reid Kleckner4b2f3262017-05-31 15:39:28 +00002544 DefaultCC == LangOptions::DCC_StdCall) &&
2545 Arch != llvm::Triple::x86;
Erich Keanea957ffb2017-11-02 21:08:00 +00002546 emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
2547 DefaultCC == LangOptions::DCC_RegCall) &&
Alexey Bataeva7547182016-05-18 09:06:38 +00002548 !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2549 if (emitError)
2550 Diags.Report(diag::err_drv_argument_not_allowed_with)
2551 << A->getSpelling() << T.getTriple();
2552 else
2553 Opts.setDefaultCallingConv(DefaultCC);
2554 }
2555
2556 // -mrtd option
2557 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2558 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2559 Diags.Report(diag::err_drv_argument_not_allowed_with)
2560 << A->getSpelling() << "-fdefault-calling-conv";
2561 else {
2562 llvm::Triple T(TargetOpts.Triple);
2563 if (T.getArch() != llvm::Triple::x86)
2564 Diags.Report(diag::err_drv_argument_not_allowed_with)
2565 << A->getSpelling() << T.getTriple();
2566 else
2567 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2568 }
2569 }
2570
Alexey Bataevdb390212015-05-20 04:24:19 +00002571 // Check if -fopenmp is specified.
Alexey Bataev18c48522016-05-27 04:13:39 +00002572 Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 1 : 0;
Alexey Bataeve927ca72017-12-29 17:36:15 +00002573 // Check if -fopenmp-simd is specified.
Alexey Bataev66f95772018-05-21 16:40:32 +00002574 bool IsSimdSpecified =
2575 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2576 /*Default=*/false);
2577 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
Samuel Antaof8b50122015-07-13 22:54:53 +00002578 Opts.OpenMPUseTLS =
2579 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002580 Opts.OpenMPIsDevice =
2581 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2582
Alexey Bataeve927ca72017-12-29 17:36:15 +00002583 if (Opts.OpenMP || Opts.OpenMPSimd) {
2584 if (int Version =
2585 getLastArgIntValue(Args, OPT_fopenmp_version_EQ,
Alexey Bataev66f95772018-05-21 16:40:32 +00002586 IsSimdSpecified ? 45 : Opts.OpenMP, Diags))
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002587 Opts.OpenMP = Version;
Alexey Bataev66f95772018-05-21 16:40:32 +00002588 else if (IsSimdSpecified)
Alexey Bataeve927ca72017-12-29 17:36:15 +00002589 Opts.OpenMP = 45;
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002590 // Provide diagnostic when a given target is not expected to be an OpenMP
2591 // device or host.
2592 if (!Opts.OpenMPIsDevice) {
2593 switch (T.getArch()) {
2594 default:
2595 break;
2596 // Add unsupported host targets here:
2597 case llvm::Triple::nvptx:
2598 case llvm::Triple::nvptx64:
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002599 Diags.Report(diag::err_drv_omp_host_target_not_supported)
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002600 << TargetOpts.Triple;
2601 break;
2602 }
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002603 }
2604 }
2605
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002606 // Set the flag to prevent the implementation from emitting device exception
2607 // handling code for those requiring so.
Alexey Bataev1ab34572018-05-02 16:52:07 +00002608 Opts.OpenMPHostCXXExceptions = Opts.Exceptions && Opts.CXXExceptions;
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00002609 if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) {
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002610 Opts.Exceptions = 0;
2611 Opts.CXXExceptions = 0;
2612 }
2613
Samuel Antaoee8fb302016-01-06 13:42:12 +00002614 // Get the OpenMP target triples if any.
Samuel Antao1168d63c2016-06-30 21:22:08 +00002615 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002616
2617 for (unsigned i = 0; i < A->getNumValues(); ++i) {
2618 llvm::Triple TT(A->getValue(i));
2619
Gheorghe-Teodor Berceaef5e1062017-08-07 21:11:10 +00002620 if (TT.getArch() == llvm::Triple::UnknownArch ||
2621 !(TT.getArch() == llvm::Triple::ppc ||
2622 TT.getArch() == llvm::Triple::ppc64 ||
2623 TT.getArch() == llvm::Triple::ppc64le ||
2624 TT.getArch() == llvm::Triple::nvptx ||
2625 TT.getArch() == llvm::Triple::nvptx64 ||
2626 TT.getArch() == llvm::Triple::x86 ||
2627 TT.getArch() == llvm::Triple::x86_64))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002628 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002629 else
2630 Opts.OMPTargetTriples.push_back(TT);
2631 }
2632 }
2633
2634 // Get OpenMP host file path if any and report if a non existent file is
2635 // found
Samuel Antao1168d63c2016-06-30 21:22:08 +00002636 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002637 Opts.OMPHostIRFile = A->getValue();
2638 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002639 Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
Samuel Antaoee8fb302016-01-06 13:42:12 +00002640 << Opts.OMPHostIRFile;
2641 }
Douglas Gregor15171282013-01-15 06:45:29 +00002642
Carlo Bertolli79712092018-02-28 20:48:35 +00002643 // set CUDA mode for OpenMP target NVPTX if specified in options
2644 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() &&
2645 Args.hasArg(options::OPT_fopenmp_cuda_mode);
2646
Chandler Carruth61fbf622011-04-23 09:27:53 +00002647 // Record whether the __DEPRECATED define was requested.
2648 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2649 OPT_fno_deprecated_macro,
2650 Opts.Deprecated);
2651
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002652 // FIXME: Eliminate this dependency.
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00002653 unsigned Opt = getOptimizationLevel(Args, IK, Diags),
Chad Rosierf2d39642013-04-10 21:30:03 +00002654 OptSize = getOptimizationLevelSize(Args);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002655 Opts.Optimize = Opt != 0;
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00002656 Opts.OptimizeSize = OptSize != 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002657
2658 // This is the __NO_INLINE__ define, which just depends on things like the
2659 // optimization level and -fno-inline, not actually whether the backend has
2660 // inlining enabled.
Chandler Carruthfcd33142016-12-23 01:24:49 +00002661 Opts.NoInlineDefine = !Opts.Optimize;
2662 if (Arg *InlineArg = Args.getLastArg(
2663 options::OPT_finline_functions, options::OPT_finline_hint_functions,
2664 options::OPT_fno_inline_functions, options::OPT_fno_inline))
2665 if (InlineArg->getOption().matches(options::OPT_fno_inline))
2666 Opts.NoInlineDefine = true;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002667
Pekka Jaaskelainen37014502014-12-10 16:41:14 +00002668 Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
2669 Args.hasArg(OPT_cl_fast_relaxed_math);
2670 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
2671 Args.hasArg(OPT_cl_finite_math_only) ||
2672 Args.hasArg(OPT_cl_fast_relaxed_math);
Alexandros Lamprineasf5a8e6c2015-10-02 14:56:37 +00002673 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
2674 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
2675 Args.hasArg(OPT_cl_fast_relaxed_math);
Chandler Carruth306bd2c2012-01-02 14:19:45 +00002676
Adam Nemet049a31d2017-03-29 21:54:24 +00002677 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2678 StringRef Val = A->getValue();
2679 if (Val == "fast")
2680 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2681 else if (Val == "on")
2682 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2683 else if (Val == "off")
2684 Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
2685 else
2686 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2687 }
2688
Ted Kremenekb47e6bc2012-09-13 06:41:18 +00002689 Opts.RetainCommentsFromSystemHeaders =
2690 Args.hasArg(OPT_fretain_comments_from_system_headers);
2691
Reid Kleckner898229a2013-06-14 17:17:23 +00002692 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002693 switch (SSP) {
2694 default:
2695 Diags.Report(diag::err_drv_invalid_value)
2696 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2697 break;
Douglas Gregor79a91412011-09-13 17:21:33 +00002698 case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2699 case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
Josh Mageee0fc1a82014-02-11 01:35:14 +00002700 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
2701 case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002702 }
Richard Smith52be6192012-11-05 22:04:41 +00002703
2704 // Parse -fsanitize= arguments.
Alexey Samsonov88459522015-01-12 22:39:12 +00002705 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2706 Diags, Opts.Sanitize);
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00002707 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
Alexey Samsonova0416102014-11-11 01:26:14 +00002708 Opts.SanitizeAddressFieldPadding =
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00002709 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
Alexey Samsonova511cdd2015-02-04 17:40:08 +00002710 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
Dean Michael Berris835832d2017-03-30 00:29:36 +00002711
Dean Michael Berris504fc222017-03-30 22:46:45 +00002712 // -fxray-instrument
Dean Michael Berris835832d2017-03-30 00:29:36 +00002713 Opts.XRayInstrument =
2714 Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
Dean Michael Berris504fc222017-03-30 22:46:45 +00002715
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +00002716 // -fxray-always-emit-customevents
2717 Opts.XRayAlwaysEmitCustomEvents =
2718 Args.hasFlag(OPT_fxray_always_emit_customevents,
2719 OPT_fnoxray_always_emit_customevents, false);
2720
Keith Wyssf437e352018-04-17 21:32:43 +00002721 // -fxray-always-emit-typedevents
2722 Opts.XRayAlwaysEmitTypedEvents =
2723 Args.hasFlag(OPT_fxray_always_emit_typedevents,
2724 OPT_fnoxray_always_emit_customevents, false);
2725
Dean Michael Berris504fc222017-03-30 22:46:45 +00002726 // -fxray-{always,never}-instrument= filenames.
Dean Michael Berris835832d2017-03-30 00:29:36 +00002727 Opts.XRayAlwaysInstrumentFiles =
2728 Args.getAllArgValues(OPT_fxray_always_instrument);
2729 Opts.XRayNeverInstrumentFiles =
2730 Args.getAllArgValues(OPT_fxray_never_instrument);
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +00002731 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
Alex Lorenz1be800c52017-04-19 08:58:56 +00002732
2733 // -fallow-editor-placeholders
2734 Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002735
2736 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
2737 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
2738
2739 StringRef Ver = A->getValue();
2740 std::pair<StringRef, StringRef> VerParts = Ver.split('.');
2741 unsigned Major, Minor = 0;
2742
2743 // Check the version number is valid: either 3.x (0 <= x <= 9) or
2744 // y or y.0 (4 <= y <= current version).
2745 if (!VerParts.first.startswith("0") &&
2746 !VerParts.first.getAsInteger(10, Major) &&
2747 3 <= Major && Major <= CLANG_VERSION_MAJOR &&
2748 (Major == 3 ? VerParts.second.size() == 1 &&
2749 !VerParts.second.getAsInteger(10, Minor)
2750 : VerParts.first.size() == Ver.size() ||
2751 VerParts.second == "0")) {
2752 // Got a valid version number.
2753 if (Major == 3 && Minor <= 8)
2754 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
2755 else if (Major <= 4)
2756 Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
Richard Smith880057c2018-04-02 18:29:44 +00002757 else if (Major <= 6)
2758 Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002759 } else if (Ver != "latest") {
2760 Diags.Report(diag::err_drv_invalid_value)
2761 << A->getAsString(Args) << A->getValue();
2762 }
2763 }
Peter Collingbourne54d13b42018-05-30 03:40:04 +00002764
2765 Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002766}
2767
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002768static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
2769 switch (Action) {
2770 case frontend::ASTDeclList:
2771 case frontend::ASTDump:
2772 case frontend::ASTPrint:
2773 case frontend::ASTView:
2774 case frontend::EmitAssembly:
2775 case frontend::EmitBC:
2776 case frontend::EmitHTML:
2777 case frontend::EmitLLVM:
2778 case frontend::EmitLLVMOnly:
2779 case frontend::EmitCodeGenOnly:
2780 case frontend::EmitObj:
2781 case frontend::FixIt:
2782 case frontend::GenerateModule:
2783 case frontend::GenerateModuleInterface:
2784 case frontend::GeneratePCH:
2785 case frontend::GeneratePTH:
2786 case frontend::ParseSyntaxOnly:
2787 case frontend::ModuleFileInfo:
2788 case frontend::VerifyPCH:
2789 case frontend::PluginAction:
2790 case frontend::PrintDeclContext:
2791 case frontend::RewriteObjC:
2792 case frontend::RewriteTest:
2793 case frontend::RunAnalysis:
Gabor Horvath207e7b12018-02-10 14:04:45 +00002794 case frontend::TemplightDump:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002795 case frontend::MigrateSource:
2796 return false;
2797
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00002798 case frontend::DumpCompilerOptions:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002799 case frontend::DumpRawTokens:
2800 case frontend::DumpTokens:
2801 case frontend::InitOnly:
2802 case frontend::PrintPreamble:
2803 case frontend::PrintPreprocessedInput:
2804 case frontend::RewriteMacros:
2805 case frontend::RunPreprocessorOnly:
2806 return true;
2807 }
2808 llvm_unreachable("invalid frontend action");
2809}
2810
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002811static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002812 DiagnosticsEngine &Diags,
2813 frontend::ActionKind Action) {
Daniel Dunbar37300482010-05-20 16:54:55 +00002814 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
2815 Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002816 if (const Arg *A = Args.getLastArg(OPT_token_cache))
Richard Smithbd55daf2012-11-01 04:30:05 +00002817 Opts.TokenCache = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002818 else
2819 Opts.TokenCache = Opts.ImplicitPTHInclude;
2820 Opts.UsePredefines = !Args.hasArg(OPT_undef);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00002821 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
Douglas Gregorce3a8292010-07-27 00:27:13 +00002822 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
Argyrios Kyrtzidis7b5d9102017-02-27 02:06:18 +00002823 Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +00002824
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +00002825 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002826 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
Richard Smithbd55daf2012-11-01 04:30:05 +00002827 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
Douglas Gregorce3a8292010-07-27 00:27:13 +00002828
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002829 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002830 StringRef Value(A->getValue());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002831 size_t Comma = Value.find(',');
2832 unsigned Bytes = 0;
2833 unsigned EndOfLine = 0;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002834
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002835 if (Comma == StringRef::npos ||
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002836 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2837 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2838 Diags.Report(diag::err_drv_preamble_format);
2839 else {
2840 Opts.PrecompiledPreambleBytes.first = Bytes;
2841 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2842 }
2843 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002844
Alexander Ivchenko0fb8c872018-05-18 11:56:21 +00002845 // Add the __CET__ macro if a CFProtection option is set.
2846 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2847 StringRef Name = A->getValue();
2848 if (Name == "branch")
2849 Opts.addMacroDef("__CET__=1");
2850 else if (Name == "return")
2851 Opts.addMacroDef("__CET__=2");
2852 else if (Name == "full")
2853 Opts.addMacroDef("__CET__=3");
2854 }
2855
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002856 // Add macros from the command line.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002857 for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
Sean Silva14facf32015-06-09 01:57:17 +00002858 if (A->getOption().matches(OPT_D))
2859 Opts.addMacroDef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002860 else
Sean Silva14facf32015-06-09 01:57:17 +00002861 Opts.addMacroUndef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002862 }
2863
Daniel Dunbar37300482010-05-20 16:54:55 +00002864 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002865
2866 // Add the ordered list of -includes.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002867 for (const auto *A : Args.filtered(OPT_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00002868 Opts.Includes.emplace_back(A->getValue());
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002869
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002870 for (const auto *A : Args.filtered(OPT_chain_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00002871 Opts.ChainedIncludes.emplace_back(A->getValue());
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002872
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002873 for (const auto *A : Args.filtered(OPT_remap_file)) {
Sean Silva14facf32015-06-09 01:57:17 +00002874 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002875
2876 if (Split.second.empty()) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00002877 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002878 continue;
2879 }
2880
2881 Opts.addRemappedFile(Split.first, Split.second);
2882 }
Sean Silva14facf32015-06-09 01:57:17 +00002883
John McCall31168b02011-06-15 23:02:42 +00002884 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002885 StringRef Name = A->getValue();
John McCall31168b02011-06-15 23:02:42 +00002886 unsigned Library = llvm::StringSwitch<unsigned>(Name)
2887 .Case("libc++", ARCXX_libcxx)
2888 .Case("libstdc++", ARCXX_libstdcxx)
2889 .Case("none", ARCXX_nolib)
2890 .Default(~0U);
2891 if (Library == ~0U)
2892 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2893 else
2894 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
2895 }
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002896
2897 // Always avoid lexing editor placeholders when we're just running the
2898 // preprocessor as we never want to emit the
2899 // "editor placeholder in source file" error in PP only mode.
2900 if (isStrictlyPreprocessorAction(Action))
2901 Opts.LexEditorPlaceholders = false;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002902}
2903
2904static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
Jordan Rose17441582013-01-30 01:52:57 +00002905 ArgList &Args,
2906 frontend::ActionKind Action) {
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002907 if (isStrictlyPreprocessorAction(Action))
Jordan Rose17441582013-01-30 01:52:57 +00002908 Opts.ShowCPP = !Args.hasArg(OPT_dM);
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002909 else
2910 Opts.ShowCPP = 0;
Jordan Rose17441582013-01-30 01:52:57 +00002911
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002912 Opts.ShowComments = Args.hasArg(OPT_C);
Daniel Dunbard4352752010-08-24 22:44:13 +00002913 Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002914 Opts.ShowMacroComments = Args.hasArg(OPT_CC);
Daniel Dunbard4352752010-08-24 22:44:13 +00002915 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +00002916 Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
David Blaikiee993e4c2012-06-14 17:36:09 +00002917 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
Richard Smith86a3ef52017-06-09 21:24:02 +00002918 Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
Reid Kleckner1df0fea2015-02-26 00:17:25 +00002919 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002920}
2921
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002922static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2923 DiagnosticsEngine &Diags) {
Daniel Dunbar37300482010-05-20 16:54:55 +00002924 Opts.ABI = Args.getLastArgValue(OPT_target_abi);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002925 if (Arg *A = Args.getLastArg(OPT_meabi)) {
2926 StringRef Value = A->getValue();
2927 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
2928 .Case("default", llvm::EABI::Default)
2929 .Case("4", llvm::EABI::EABI4)
2930 .Case("5", llvm::EABI::EABI5)
2931 .Case("gnu", llvm::EABI::GNU)
2932 .Default(llvm::EABI::Unknown);
2933 if (EABIVersion == llvm::EABI::Unknown)
2934 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2935 << Value;
2936 else
Yuka Takahashidc771502017-07-01 07:57:23 +00002937 Opts.EABIVersion = EABIVersion;
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002938 }
Daniel Dunbar37300482010-05-20 16:54:55 +00002939 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
Rafael Espindolaeb265472013-08-21 21:59:03 +00002940 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
Douglas Gregorcb177f12012-10-16 23:40:58 +00002941 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
Daniel Dunbara1d107c2010-08-11 23:07:42 +00002942 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
Petr Hosekf92ca012018-05-25 20:39:37 +00002943 Opts.Triple = Args.getLastArgValue(OPT_triple);
Sebastian Pop8188c8a2011-11-01 21:33:06 +00002944 // Use the default target triple if unspecified.
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002945 if (Opts.Triple.empty())
Sebastian Pop8188c8a2011-11-01 21:33:06 +00002946 Opts.Triple = llvm::sys::getDefaultTargetTriple();
Petr Hosekf92ca012018-05-25 20:39:37 +00002947 Opts.Triple = llvm::Triple::normalize(Opts.Triple);
Alexey Bader0ea07532016-11-01 15:50:52 +00002948 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00002949 Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
Artem Belevich679dafe2018-05-09 23:10:09 +00002950 Opts.NVPTXUseShortPointers = Args.hasFlag(
2951 options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
Hans Wennborg50501fb2014-01-13 19:48:18 +00002952}
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002953
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002954bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
Chris Lattner5159f612010-11-23 08:35:12 +00002955 const char *const *ArgBegin,
2956 const char *const *ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00002957 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002958 bool Success = true;
2959
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002960 // Parse the arguments.
David Blaikie0aaa7622017-01-13 17:34:15 +00002961 std::unique_ptr<OptTable> Opts = createDriverOptTable();
Hans Wennborgd1ddb9a2013-08-02 20:16:22 +00002962 const unsigned IncludedFlagsBitmask = options::CC1Option;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002963 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +00002964 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +00002965 Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
David Blaikie69a1d8c2015-06-22 22:07:27 +00002966 MissingArgCount, IncludedFlagsBitmask);
Wei Mi811ff922016-04-08 17:42:32 +00002967 LangOptions &LangOpts = *Res.getLangOpts();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002968
2969 // Check for missing argument error.
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002970 if (MissingArgCount) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002971 Diags.Report(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +00002972 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002973 Success = false;
2974 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002975
2976 // Issue errors on unknown arguments.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002977 for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +00002978 auto ArgString = A->getAsString(Args);
2979 std::string Nearest;
2980 if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
2981 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
2982 else
2983 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
2984 << ArgString << Nearest;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002985 Success = false;
2986 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002987
David Blaikie69a1d8c2015-06-22 22:07:27 +00002988 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
2989 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
2990 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00002991 Success &=
2992 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
2993 false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
Wei Mi811ff922016-04-08 17:42:32 +00002994 ParseCommentArgs(LangOpts.CommentOpts, Args);
David Blaikie69a1d8c2015-06-22 22:07:27 +00002995 ParseFileSystemArgs(Res.getFileSystemOpts(), Args);
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +00002996 // FIXME: We shouldn't have to pass the DashX option around here
Erik Verbruggene0bde752016-10-27 14:17:10 +00002997 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
2998 LangOpts.IsHeaderFile);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002999 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003000 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003001 Res.getTargetOpts(), Res.getFrontendOpts());
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00003002 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
3003 Res.getFileSystemOpts().WorkingDir);
Richard Smith40c0efa2017-04-26 18:57:40 +00003004 if (DashX.getFormat() == InputKind::Precompiled ||
3005 DashX.getLanguage() == InputKind::LLVM_IR) {
Steven Wu546a1962015-07-17 20:09:56 +00003006 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3007 // PassManager in BackendUtil.cpp. They need to be initializd no matter
3008 // what the input type is.
3009 if (Args.hasArg(OPT_fobjc_arc))
Wei Mi811ff922016-04-08 17:42:32 +00003010 LangOpts.ObjCAutoRefCount = 1;
3011 // PIClevel and PIELevel are needed during code generation and this should be
3012 // set regardless of the input type.
3013 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
Rafael Espindolac9d336e2016-06-23 15:07:32 +00003014 LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
Steven Wu546a1962015-07-17 20:09:56 +00003015 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
Wei Mi811ff922016-04-08 17:42:32 +00003016 Diags, LangOpts.Sanitize);
Steven Wu546a1962015-07-17 20:09:56 +00003017 } else {
3018 // Other LangOpts are only initialzed when the input is not AST or LLVM IR.
Richard Smith40c0efa2017-04-26 18:57:40 +00003019 // FIXME: Should we really be calling this for an InputKind::Asm input?
Yaxun Liu143f0832016-06-20 19:26:00 +00003020 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
Richard Smith40c0efa2017-04-26 18:57:40 +00003021 Res.getPreprocessorOpts(), Diags);
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003022 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
Wei Mi811ff922016-04-08 17:42:32 +00003023 LangOpts.ObjCExceptions = 1;
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003024 }
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003025
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003026 LangOpts.FunctionAlignment =
3027 getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3028
Artem Belevich31c3bad2016-05-19 18:44:45 +00003029 if (LangOpts.CUDA) {
3030 // During CUDA device-side compilation, the aux triple is the
3031 // triple used for host compilation.
3032 if (LangOpts.CUDAIsDevice)
3033 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
Justin Lebar76945b22016-04-29 23:05:19 +00003034 }
3035
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003036 // Set the triple of the host for OpenMP device compile.
3037 if (LangOpts.OpenMPIsDevice)
3038 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3039
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003040 // FIXME: Override value name discarding when asan or msan is used because the
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003041 // backend passes depend on the name of the alloca in order to print out
3042 // names.
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003043 Res.getCodeGenOpts().DiscardValueNames &=
Wei Mi811ff922016-04-08 17:42:32 +00003044 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3045 !LangOpts.Sanitize.has(SanitizerKind::Memory);
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003046
Brian Gesiakf0ef1372018-01-09 21:26:47 +00003047 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003048 Res.getFrontendOpts().ProgramAction);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003049 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
Jordan Rose17441582013-01-30 01:52:57 +00003050 Res.getFrontendOpts().ProgramAction);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003051
3052 // Turn on -Wspir-compat for SPIR target.
3053 llvm::Triple T(Res.getTargetOpts().Triple);
3054 auto Arch = T.getArch();
3055 if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64) {
3056 Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3057 }
Wei Mi9b3d6272017-10-16 16:50:27 +00003058
3059 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3060 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3061 !Res.getLangOpts()->Sanitize.empty()) {
3062 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3063 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3064 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003065 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003066}
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003067
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003068std::string CompilerInvocation::getModuleHash() const {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003069 // Note: For QoI reasons, the things we use as a hash here should all be
3070 // dumped via the -module-info flag.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003071 using llvm::hash_code;
3072 using llvm::hash_value;
3073 using llvm::hash_combine;
3074
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003075 // Start the signature with the compiler version.
Douglas Gregordc779ab2012-11-05 23:30:26 +00003076 // FIXME: We'd rather use something more cryptographically sound than
Douglas Gregor7fd08492012-11-05 19:45:09 +00003077 // CityHash, but this will do for now.
3078 hash_code code = hash_value(getClangFullRepositoryVersion());
3079
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003080 // Extend the signature with the language options
3081#define LANGOPT(Name, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003082 code = hash_combine(code, LangOpts->Name);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003083#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003084 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003085#define BENIGN_LANGOPT(Name, Bits, Default, Description)
3086#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3087#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +00003088
3089 for (StringRef Feature : LangOpts->ModuleFeatures)
3090 code = hash_combine(code, Feature);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00003091
Douglas Gregor7fd08492012-11-05 19:45:09 +00003092 // Extend the signature with the target options.
3093 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
Argyrios Kyrtzidisfe6b8802014-04-29 18:45:01 +00003094 TargetOpts->ABI);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003095 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3096 code = hash_combine(code, FeatureAsWritten);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003097
Douglas Gregora739d9a2011-09-14 15:55:12 +00003098 // Extend the signature with preprocessor options.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003099 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
Douglas Gregor5dc38992013-02-07 00:21:12 +00003100 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
Douglas Gregor7fd08492012-11-05 19:45:09 +00003101 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3102
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003103 for (const auto &I : getPreprocessorOpts().Macros) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003104 // If we're supposed to ignore this macro for the purposes of modules,
3105 // don't put it into the hash.
3106 if (!hsOpts.ModulesIgnoreMacros.empty()) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003107 // Check whether we're ignoring this macro.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003108 StringRef MacroDef = I.first;
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003109 if (hsOpts.ModulesIgnoreMacros.count(
3110 llvm::CachedHashString(MacroDef.split('=').first)))
Douglas Gregor5dc38992013-02-07 00:21:12 +00003111 continue;
3112 }
3113
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003114 code = hash_combine(code, I.first, I.second);
Douglas Gregor71129d52011-10-17 14:55:37 +00003115 }
Douglas Gregor7fd08492012-11-05 19:45:09 +00003116
Adrian Prantl793038d32016-01-12 21:01:56 +00003117 // Extend the signature with the sysroot and other header search options.
3118 code = hash_combine(code, hsOpts.Sysroot,
3119 hsOpts.ModuleFormat,
3120 hsOpts.UseDebugInfo,
3121 hsOpts.UseBuiltinIncludes,
Douglas Gregor7fd08492012-11-05 19:45:09 +00003122 hsOpts.UseStandardSystemIncludes,
3123 hsOpts.UseStandardCXXIncludes,
Manman Ren47a44452016-07-26 17:12:17 +00003124 hsOpts.UseLibcxx,
3125 hsOpts.ModulesValidateDiagnosticOptions);
Argyrios Kyrtzidisd113788e2014-05-04 05:27:24 +00003126 code = hash_combine(code, hsOpts.ResourceDir);
Douglas Gregor7fd08492012-11-05 19:45:09 +00003127
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00003128 // Extend the signature with the user build path.
3129 code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3130
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003131 // Extend the signature with the module file extensions.
3132 const FrontendOptions &frontendOpts = getFrontendOpts();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003133 for (const auto &ext : frontendOpts.ModuleFileExtensions) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003134 code = ext->hashExtension(code);
3135 }
3136
Vedant Kumar85a83c22017-06-01 20:01:01 +00003137 // Extend the signature with the enabled sanitizers, if at least one is
3138 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3139 SanitizerSet SanHash = LangOpts->Sanitize;
3140 SanHash.clear(getPPTransparentSanitizers());
3141 if (!SanHash.empty())
3142 code = hash_combine(code, SanHash.Mask);
3143
Douglas Gregor7fd08492012-11-05 19:45:09 +00003144 return llvm::APInt(64, code).toString(36, /*Signed=*/false);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003145}
Reid Kleckner898229a2013-06-14 17:17:23 +00003146
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003147template<typename IntTy>
3148static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
3149 IntTy Default,
3150 DiagnosticsEngine *Diags) {
3151 IntTy Res = Default;
Reid Kleckner898229a2013-06-14 17:17:23 +00003152 if (Arg *A = Args.getLastArg(Id)) {
3153 if (StringRef(A->getValue()).getAsInteger(10, Res)) {
3154 if (Diags)
3155 Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
3156 << A->getValue();
3157 }
3158 }
3159 return Res;
3160}
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003161
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003162namespace clang {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003163
3164// Declared in clang/Frontend/Utils.h.
3165int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
3166 DiagnosticsEngine *Diags) {
3167 return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
3168}
3169
3170uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
3171 uint64_t Default,
3172 DiagnosticsEngine *Diags) {
3173 return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
3174}
3175
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003176void BuryPointer(const void *Ptr) {
3177 // This function may be called only a small fixed amount of times per each
3178 // invocation, otherwise we do actually have a leak which we want to report.
3179 // If this function is called more than kGraveYardMaxSize times, the pointers
3180 // will not be properly buried and a leak detector will report a leak, which
3181 // is what we want in such case.
3182 static const size_t kGraveYardMaxSize = 16;
Chandler Carruth2588aa72013-12-28 02:50:00 +00003183 LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
Benjamin Kramer4527fb22014-03-02 17:08:31 +00003184 static std::atomic<unsigned> GraveYardSize;
3185 unsigned Idx = GraveYardSize++;
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003186 if (Idx >= kGraveYardMaxSize)
3187 return;
3188 GraveYard[Idx] = Ptr;
3189}
Ben Langmuir8832c062014-04-15 18:16:25 +00003190
3191IntrusiveRefCntPtr<vfs::FileSystem>
3192createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3193 DiagnosticsEngine &Diags) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003194 return createVFSFromCompilerInvocation(CI, Diags, vfs::getRealFileSystem());
3195}
Ben Langmuir8832c062014-04-15 18:16:25 +00003196
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003197IntrusiveRefCntPtr<vfs::FileSystem>
3198createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3199 DiagnosticsEngine &Diags,
3200 IntrusiveRefCntPtr<vfs::FileSystem> BaseFS) {
3201 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3202 return BaseFS;
3203
3204 IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay(
3205 new vfs::OverlayFileSystem(BaseFS));
Ben Langmuir8832c062014-04-15 18:16:25 +00003206 // earlier vfs files are on the bottom
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003207 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003208 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003209 BaseFS->getBufferForFile(File);
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003210 if (!Buffer) {
Ben Langmuir8832c062014-04-15 18:16:25 +00003211 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
Ben Langmuir005c2e52018-03-23 17:37:27 +00003212 continue;
Ben Langmuir8832c062014-04-15 18:16:25 +00003213 }
3214
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00003215 IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
3216 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File);
Ben Langmuir005c2e52018-03-23 17:37:27 +00003217 if (FS)
3218 Overlay->pushOverlay(FS);
3219 else
Ben Langmuir8832c062014-04-15 18:16:25 +00003220 Diags.Report(diag::err_invalid_vfs_overlay) << File;
Ben Langmuir8832c062014-04-15 18:16:25 +00003221 }
3222 return Overlay;
Reid Kleckner898229a2013-06-14 17:17:23 +00003223}
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003224
3225} // namespace clang