17330f729Sjoerg //===- CompilerInvocation.cpp ---------------------------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg
97330f729Sjoerg #include "clang/Frontend/CompilerInvocation.h"
107330f729Sjoerg #include "TestModuleFileExtension.h"
117330f729Sjoerg #include "clang/Basic/Builtins.h"
127330f729Sjoerg #include "clang/Basic/CharInfo.h"
137330f729Sjoerg #include "clang/Basic/CodeGenOptions.h"
147330f729Sjoerg #include "clang/Basic/CommentOptions.h"
157330f729Sjoerg #include "clang/Basic/DebugInfoOptions.h"
167330f729Sjoerg #include "clang/Basic/Diagnostic.h"
17*e038c9c4Sjoerg #include "clang/Basic/DiagnosticDriver.h"
187330f729Sjoerg #include "clang/Basic/DiagnosticOptions.h"
197330f729Sjoerg #include "clang/Basic/FileSystemOptions.h"
207330f729Sjoerg #include "clang/Basic/LLVM.h"
217330f729Sjoerg #include "clang/Basic/LangOptions.h"
227330f729Sjoerg #include "clang/Basic/LangStandard.h"
237330f729Sjoerg #include "clang/Basic/ObjCRuntime.h"
247330f729Sjoerg #include "clang/Basic/Sanitizers.h"
257330f729Sjoerg #include "clang/Basic/SourceLocation.h"
267330f729Sjoerg #include "clang/Basic/TargetOptions.h"
277330f729Sjoerg #include "clang/Basic/Version.h"
287330f729Sjoerg #include "clang/Basic/Visibility.h"
297330f729Sjoerg #include "clang/Basic/XRayInstr.h"
307330f729Sjoerg #include "clang/Config/config.h"
317330f729Sjoerg #include "clang/Driver/Driver.h"
327330f729Sjoerg #include "clang/Driver/DriverDiagnostic.h"
337330f729Sjoerg #include "clang/Driver/Options.h"
347330f729Sjoerg #include "clang/Frontend/CommandLineSourceLoc.h"
357330f729Sjoerg #include "clang/Frontend/DependencyOutputOptions.h"
367330f729Sjoerg #include "clang/Frontend/FrontendDiagnostic.h"
377330f729Sjoerg #include "clang/Frontend/FrontendOptions.h"
387330f729Sjoerg #include "clang/Frontend/FrontendPluginRegistry.h"
397330f729Sjoerg #include "clang/Frontend/MigratorOptions.h"
407330f729Sjoerg #include "clang/Frontend/PreprocessorOutputOptions.h"
41*e038c9c4Sjoerg #include "clang/Frontend/TextDiagnosticBuffer.h"
427330f729Sjoerg #include "clang/Frontend/Utils.h"
437330f729Sjoerg #include "clang/Lex/HeaderSearchOptions.h"
447330f729Sjoerg #include "clang/Lex/PreprocessorOptions.h"
457330f729Sjoerg #include "clang/Sema/CodeCompleteOptions.h"
46*e038c9c4Sjoerg #include "clang/Serialization/ASTBitCodes.h"
477330f729Sjoerg #include "clang/Serialization/ModuleFileExtension.h"
487330f729Sjoerg #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
497330f729Sjoerg #include "llvm/ADT/APInt.h"
507330f729Sjoerg #include "llvm/ADT/ArrayRef.h"
517330f729Sjoerg #include "llvm/ADT/CachedHashString.h"
52*e038c9c4Sjoerg #include "llvm/ADT/DenseSet.h"
53*e038c9c4Sjoerg #include "llvm/ADT/FloatingPointMode.h"
547330f729Sjoerg #include "llvm/ADT/Hashing.h"
557330f729Sjoerg #include "llvm/ADT/None.h"
567330f729Sjoerg #include "llvm/ADT/Optional.h"
57*e038c9c4Sjoerg #include "llvm/ADT/STLExtras.h"
587330f729Sjoerg #include "llvm/ADT/SmallString.h"
597330f729Sjoerg #include "llvm/ADT/SmallVector.h"
607330f729Sjoerg #include "llvm/ADT/StringRef.h"
617330f729Sjoerg #include "llvm/ADT/StringSwitch.h"
627330f729Sjoerg #include "llvm/ADT/Triple.h"
637330f729Sjoerg #include "llvm/ADT/Twine.h"
64*e038c9c4Sjoerg #include "llvm/Config/llvm-config.h"
657330f729Sjoerg #include "llvm/IR/DebugInfoMetadata.h"
667330f729Sjoerg #include "llvm/Linker/Linker.h"
677330f729Sjoerg #include "llvm/MC/MCTargetOptions.h"
687330f729Sjoerg #include "llvm/Option/Arg.h"
697330f729Sjoerg #include "llvm/Option/ArgList.h"
707330f729Sjoerg #include "llvm/Option/OptSpecifier.h"
717330f729Sjoerg #include "llvm/Option/OptTable.h"
727330f729Sjoerg #include "llvm/Option/Option.h"
737330f729Sjoerg #include "llvm/ProfileData/InstrProfReader.h"
74*e038c9c4Sjoerg #include "llvm/Remarks/HotnessThresholdParser.h"
757330f729Sjoerg #include "llvm/Support/CodeGen.h"
767330f729Sjoerg #include "llvm/Support/Compiler.h"
777330f729Sjoerg #include "llvm/Support/Error.h"
787330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
797330f729Sjoerg #include "llvm/Support/ErrorOr.h"
807330f729Sjoerg #include "llvm/Support/FileSystem.h"
817330f729Sjoerg #include "llvm/Support/Host.h"
827330f729Sjoerg #include "llvm/Support/MathExtras.h"
837330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
847330f729Sjoerg #include "llvm/Support/Path.h"
857330f729Sjoerg #include "llvm/Support/Process.h"
867330f729Sjoerg #include "llvm/Support/Regex.h"
877330f729Sjoerg #include "llvm/Support/VersionTuple.h"
887330f729Sjoerg #include "llvm/Support/VirtualFileSystem.h"
897330f729Sjoerg #include "llvm/Support/raw_ostream.h"
907330f729Sjoerg #include "llvm/Target/TargetOptions.h"
917330f729Sjoerg #include <algorithm>
927330f729Sjoerg #include <atomic>
937330f729Sjoerg #include <cassert>
947330f729Sjoerg #include <cstddef>
957330f729Sjoerg #include <cstring>
967330f729Sjoerg #include <memory>
977330f729Sjoerg #include <string>
987330f729Sjoerg #include <tuple>
99*e038c9c4Sjoerg #include <type_traits>
1007330f729Sjoerg #include <utility>
1017330f729Sjoerg #include <vector>
1027330f729Sjoerg
1037330f729Sjoerg using namespace clang;
1047330f729Sjoerg using namespace driver;
1057330f729Sjoerg using namespace options;
1067330f729Sjoerg using namespace llvm::opt;
1077330f729Sjoerg
1087330f729Sjoerg //===----------------------------------------------------------------------===//
1097330f729Sjoerg // Initialization.
1107330f729Sjoerg //===----------------------------------------------------------------------===//
1117330f729Sjoerg
CompilerInvocationRefBase()112*e038c9c4Sjoerg CompilerInvocationRefBase::CompilerInvocationRefBase()
1137330f729Sjoerg : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
1147330f729Sjoerg DiagnosticOpts(new DiagnosticOptions()),
1157330f729Sjoerg HeaderSearchOpts(new HeaderSearchOptions()),
116*e038c9c4Sjoerg PreprocessorOpts(new PreprocessorOptions()),
117*e038c9c4Sjoerg AnalyzerOpts(new AnalyzerOptions()) {}
1187330f729Sjoerg
CompilerInvocationRefBase(const CompilerInvocationRefBase & X)119*e038c9c4Sjoerg CompilerInvocationRefBase::CompilerInvocationRefBase(
120*e038c9c4Sjoerg const CompilerInvocationRefBase &X)
1217330f729Sjoerg : LangOpts(new LangOptions(*X.getLangOpts())),
1227330f729Sjoerg TargetOpts(new TargetOptions(X.getTargetOpts())),
1237330f729Sjoerg DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
1247330f729Sjoerg HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
125*e038c9c4Sjoerg PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())),
126*e038c9c4Sjoerg AnalyzerOpts(new AnalyzerOptions(*X.getAnalyzerOpts())) {}
1277330f729Sjoerg
128*e038c9c4Sjoerg CompilerInvocationRefBase::CompilerInvocationRefBase(
129*e038c9c4Sjoerg CompilerInvocationRefBase &&X) = default;
130*e038c9c4Sjoerg
131*e038c9c4Sjoerg CompilerInvocationRefBase &
operator =(CompilerInvocationRefBase X)132*e038c9c4Sjoerg CompilerInvocationRefBase::operator=(CompilerInvocationRefBase X) {
133*e038c9c4Sjoerg LangOpts.swap(X.LangOpts);
134*e038c9c4Sjoerg TargetOpts.swap(X.TargetOpts);
135*e038c9c4Sjoerg DiagnosticOpts.swap(X.DiagnosticOpts);
136*e038c9c4Sjoerg HeaderSearchOpts.swap(X.HeaderSearchOpts);
137*e038c9c4Sjoerg PreprocessorOpts.swap(X.PreprocessorOpts);
138*e038c9c4Sjoerg AnalyzerOpts.swap(X.AnalyzerOpts);
139*e038c9c4Sjoerg return *this;
140*e038c9c4Sjoerg }
141*e038c9c4Sjoerg
142*e038c9c4Sjoerg CompilerInvocationRefBase &
143*e038c9c4Sjoerg CompilerInvocationRefBase::operator=(CompilerInvocationRefBase &&X) = default;
144*e038c9c4Sjoerg
145*e038c9c4Sjoerg CompilerInvocationRefBase::~CompilerInvocationRefBase() = default;
146*e038c9c4Sjoerg
147*e038c9c4Sjoerg //===----------------------------------------------------------------------===//
148*e038c9c4Sjoerg // Normalizers
149*e038c9c4Sjoerg //===----------------------------------------------------------------------===//
150*e038c9c4Sjoerg
151*e038c9c4Sjoerg #define SIMPLE_ENUM_VALUE_TABLE
152*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
153*e038c9c4Sjoerg #undef SIMPLE_ENUM_VALUE_TABLE
154*e038c9c4Sjoerg
normalizeSimpleFlag(OptSpecifier Opt,unsigned TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)155*e038c9c4Sjoerg static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
156*e038c9c4Sjoerg unsigned TableIndex,
157*e038c9c4Sjoerg const ArgList &Args,
158*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
159*e038c9c4Sjoerg if (Args.hasArg(Opt))
160*e038c9c4Sjoerg return true;
161*e038c9c4Sjoerg return None;
162*e038c9c4Sjoerg }
163*e038c9c4Sjoerg
normalizeSimpleNegativeFlag(OptSpecifier Opt,unsigned,const ArgList & Args,DiagnosticsEngine &)164*e038c9c4Sjoerg static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
165*e038c9c4Sjoerg const ArgList &Args,
166*e038c9c4Sjoerg DiagnosticsEngine &) {
167*e038c9c4Sjoerg if (Args.hasArg(Opt))
168*e038c9c4Sjoerg return false;
169*e038c9c4Sjoerg return None;
170*e038c9c4Sjoerg }
171*e038c9c4Sjoerg
172*e038c9c4Sjoerg /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
173*e038c9c4Sjoerg /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
174*e038c9c4Sjoerg /// unnecessary template instantiations and just ignore it with a variadic
175*e038c9c4Sjoerg /// argument.
denormalizeSimpleFlag(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator,Option::OptionClass,unsigned,...)176*e038c9c4Sjoerg static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
177*e038c9c4Sjoerg const char *Spelling,
178*e038c9c4Sjoerg CompilerInvocation::StringAllocator,
179*e038c9c4Sjoerg Option::OptionClass, unsigned, /*T*/...) {
180*e038c9c4Sjoerg Args.push_back(Spelling);
181*e038c9c4Sjoerg }
182*e038c9c4Sjoerg
is_uint64_t_convertible()183*e038c9c4Sjoerg template <typename T> static constexpr bool is_uint64_t_convertible() {
184*e038c9c4Sjoerg return !std::is_same<T, uint64_t>::value &&
185*e038c9c4Sjoerg llvm::is_integral_or_enum<T>::value;
186*e038c9c4Sjoerg }
187*e038c9c4Sjoerg
188*e038c9c4Sjoerg template <typename T,
189*e038c9c4Sjoerg std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
makeFlagToValueNormalizer(T Value)190*e038c9c4Sjoerg static auto makeFlagToValueNormalizer(T Value) {
191*e038c9c4Sjoerg return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
192*e038c9c4Sjoerg DiagnosticsEngine &) -> Optional<T> {
193*e038c9c4Sjoerg if (Args.hasArg(Opt))
194*e038c9c4Sjoerg return Value;
195*e038c9c4Sjoerg return None;
196*e038c9c4Sjoerg };
197*e038c9c4Sjoerg }
198*e038c9c4Sjoerg
199*e038c9c4Sjoerg template <typename T,
200*e038c9c4Sjoerg std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
makeFlagToValueNormalizer(T Value)201*e038c9c4Sjoerg static auto makeFlagToValueNormalizer(T Value) {
202*e038c9c4Sjoerg return makeFlagToValueNormalizer(uint64_t(Value));
203*e038c9c4Sjoerg }
204*e038c9c4Sjoerg
makeBooleanOptionNormalizer(bool Value,bool OtherValue,OptSpecifier OtherOpt)205*e038c9c4Sjoerg static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
206*e038c9c4Sjoerg OptSpecifier OtherOpt) {
207*e038c9c4Sjoerg return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
208*e038c9c4Sjoerg const ArgList &Args,
209*e038c9c4Sjoerg DiagnosticsEngine &) -> Optional<bool> {
210*e038c9c4Sjoerg if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
211*e038c9c4Sjoerg return A->getOption().matches(Opt) ? Value : OtherValue;
212*e038c9c4Sjoerg }
213*e038c9c4Sjoerg return None;
214*e038c9c4Sjoerg };
215*e038c9c4Sjoerg }
216*e038c9c4Sjoerg
makeBooleanOptionDenormalizer(bool Value)217*e038c9c4Sjoerg static auto makeBooleanOptionDenormalizer(bool Value) {
218*e038c9c4Sjoerg return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
219*e038c9c4Sjoerg CompilerInvocation::StringAllocator, Option::OptionClass,
220*e038c9c4Sjoerg unsigned, bool KeyPath) {
221*e038c9c4Sjoerg if (KeyPath == Value)
222*e038c9c4Sjoerg Args.push_back(Spelling);
223*e038c9c4Sjoerg };
224*e038c9c4Sjoerg }
225*e038c9c4Sjoerg
denormalizeStringImpl(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned,const Twine & Value)226*e038c9c4Sjoerg static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
227*e038c9c4Sjoerg const char *Spelling,
228*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
229*e038c9c4Sjoerg Option::OptionClass OptClass, unsigned,
230*e038c9c4Sjoerg const Twine &Value) {
231*e038c9c4Sjoerg switch (OptClass) {
232*e038c9c4Sjoerg case Option::SeparateClass:
233*e038c9c4Sjoerg case Option::JoinedOrSeparateClass:
234*e038c9c4Sjoerg case Option::JoinedAndSeparateClass:
235*e038c9c4Sjoerg Args.push_back(Spelling);
236*e038c9c4Sjoerg Args.push_back(SA(Value));
237*e038c9c4Sjoerg break;
238*e038c9c4Sjoerg case Option::JoinedClass:
239*e038c9c4Sjoerg case Option::CommaJoinedClass:
240*e038c9c4Sjoerg Args.push_back(SA(Twine(Spelling) + Value));
241*e038c9c4Sjoerg break;
242*e038c9c4Sjoerg default:
243*e038c9c4Sjoerg llvm_unreachable("Cannot denormalize an option with option class "
244*e038c9c4Sjoerg "incompatible with string denormalization.");
245*e038c9c4Sjoerg }
246*e038c9c4Sjoerg }
247*e038c9c4Sjoerg
248*e038c9c4Sjoerg template <typename T>
249*e038c9c4Sjoerg static void
denormalizeString(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,T Value)250*e038c9c4Sjoerg denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
251*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
252*e038c9c4Sjoerg Option::OptionClass OptClass, unsigned TableIndex, T Value) {
253*e038c9c4Sjoerg denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
254*e038c9c4Sjoerg }
255*e038c9c4Sjoerg
256*e038c9c4Sjoerg static Optional<SimpleEnumValue>
findValueTableByName(const SimpleEnumValueTable & Table,StringRef Name)257*e038c9c4Sjoerg findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
258*e038c9c4Sjoerg for (int I = 0, E = Table.Size; I != E; ++I)
259*e038c9c4Sjoerg if (Name == Table.Table[I].Name)
260*e038c9c4Sjoerg return Table.Table[I];
261*e038c9c4Sjoerg
262*e038c9c4Sjoerg return None;
263*e038c9c4Sjoerg }
264*e038c9c4Sjoerg
265*e038c9c4Sjoerg static Optional<SimpleEnumValue>
findValueTableByValue(const SimpleEnumValueTable & Table,unsigned Value)266*e038c9c4Sjoerg findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
267*e038c9c4Sjoerg for (int I = 0, E = Table.Size; I != E; ++I)
268*e038c9c4Sjoerg if (Value == Table.Table[I].Value)
269*e038c9c4Sjoerg return Table.Table[I];
270*e038c9c4Sjoerg
271*e038c9c4Sjoerg return None;
272*e038c9c4Sjoerg }
273*e038c9c4Sjoerg
normalizeSimpleEnum(OptSpecifier Opt,unsigned TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)274*e038c9c4Sjoerg static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
275*e038c9c4Sjoerg unsigned TableIndex,
276*e038c9c4Sjoerg const ArgList &Args,
277*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
278*e038c9c4Sjoerg assert(TableIndex < SimpleEnumValueTablesSize);
279*e038c9c4Sjoerg const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
280*e038c9c4Sjoerg
281*e038c9c4Sjoerg auto *Arg = Args.getLastArg(Opt);
282*e038c9c4Sjoerg if (!Arg)
283*e038c9c4Sjoerg return None;
284*e038c9c4Sjoerg
285*e038c9c4Sjoerg StringRef ArgValue = Arg->getValue();
286*e038c9c4Sjoerg if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
287*e038c9c4Sjoerg return MaybeEnumVal->Value;
288*e038c9c4Sjoerg
289*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_value)
290*e038c9c4Sjoerg << Arg->getAsString(Args) << ArgValue;
291*e038c9c4Sjoerg return None;
292*e038c9c4Sjoerg }
293*e038c9c4Sjoerg
denormalizeSimpleEnumImpl(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,unsigned Value)294*e038c9c4Sjoerg static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
295*e038c9c4Sjoerg const char *Spelling,
296*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
297*e038c9c4Sjoerg Option::OptionClass OptClass,
298*e038c9c4Sjoerg unsigned TableIndex, unsigned Value) {
299*e038c9c4Sjoerg assert(TableIndex < SimpleEnumValueTablesSize);
300*e038c9c4Sjoerg const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
301*e038c9c4Sjoerg if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
302*e038c9c4Sjoerg denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
303*e038c9c4Sjoerg MaybeEnumVal->Name);
304*e038c9c4Sjoerg } else {
305*e038c9c4Sjoerg llvm_unreachable("The simple enum value was not correctly defined in "
306*e038c9c4Sjoerg "the tablegen option description");
307*e038c9c4Sjoerg }
308*e038c9c4Sjoerg }
309*e038c9c4Sjoerg
310*e038c9c4Sjoerg template <typename T>
denormalizeSimpleEnum(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,T Value)311*e038c9c4Sjoerg static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
312*e038c9c4Sjoerg const char *Spelling,
313*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
314*e038c9c4Sjoerg Option::OptionClass OptClass,
315*e038c9c4Sjoerg unsigned TableIndex, T Value) {
316*e038c9c4Sjoerg return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
317*e038c9c4Sjoerg static_cast<unsigned>(Value));
318*e038c9c4Sjoerg }
319*e038c9c4Sjoerg
normalizeString(OptSpecifier Opt,int TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)320*e038c9c4Sjoerg static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
321*e038c9c4Sjoerg const ArgList &Args,
322*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
323*e038c9c4Sjoerg auto *Arg = Args.getLastArg(Opt);
324*e038c9c4Sjoerg if (!Arg)
325*e038c9c4Sjoerg return None;
326*e038c9c4Sjoerg return std::string(Arg->getValue());
327*e038c9c4Sjoerg }
328*e038c9c4Sjoerg
329*e038c9c4Sjoerg template <typename IntTy>
normalizeStringIntegral(OptSpecifier Opt,int,const ArgList & Args,DiagnosticsEngine & Diags)330*e038c9c4Sjoerg static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
331*e038c9c4Sjoerg const ArgList &Args,
332*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
333*e038c9c4Sjoerg auto *Arg = Args.getLastArg(Opt);
334*e038c9c4Sjoerg if (!Arg)
335*e038c9c4Sjoerg return None;
336*e038c9c4Sjoerg IntTy Res;
337*e038c9c4Sjoerg if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
338*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_int_value)
339*e038c9c4Sjoerg << Arg->getAsString(Args) << Arg->getValue();
340*e038c9c4Sjoerg return None;
341*e038c9c4Sjoerg }
342*e038c9c4Sjoerg return Res;
343*e038c9c4Sjoerg }
344*e038c9c4Sjoerg
345*e038c9c4Sjoerg static Optional<std::vector<std::string>>
normalizeStringVector(OptSpecifier Opt,int,const ArgList & Args,DiagnosticsEngine &)346*e038c9c4Sjoerg normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
347*e038c9c4Sjoerg DiagnosticsEngine &) {
348*e038c9c4Sjoerg return Args.getAllArgValues(Opt);
349*e038c9c4Sjoerg }
350*e038c9c4Sjoerg
denormalizeStringVector(SmallVectorImpl<const char * > & Args,const char * Spelling,CompilerInvocation::StringAllocator SA,Option::OptionClass OptClass,unsigned TableIndex,const std::vector<std::string> & Values)351*e038c9c4Sjoerg static void denormalizeStringVector(SmallVectorImpl<const char *> &Args,
352*e038c9c4Sjoerg const char *Spelling,
353*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
354*e038c9c4Sjoerg Option::OptionClass OptClass,
355*e038c9c4Sjoerg unsigned TableIndex,
356*e038c9c4Sjoerg const std::vector<std::string> &Values) {
357*e038c9c4Sjoerg switch (OptClass) {
358*e038c9c4Sjoerg case Option::CommaJoinedClass: {
359*e038c9c4Sjoerg std::string CommaJoinedValue;
360*e038c9c4Sjoerg if (!Values.empty()) {
361*e038c9c4Sjoerg CommaJoinedValue.append(Values.front());
362*e038c9c4Sjoerg for (const std::string &Value : llvm::drop_begin(Values, 1)) {
363*e038c9c4Sjoerg CommaJoinedValue.append(",");
364*e038c9c4Sjoerg CommaJoinedValue.append(Value);
365*e038c9c4Sjoerg }
366*e038c9c4Sjoerg }
367*e038c9c4Sjoerg denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
368*e038c9c4Sjoerg TableIndex, CommaJoinedValue);
369*e038c9c4Sjoerg break;
370*e038c9c4Sjoerg }
371*e038c9c4Sjoerg case Option::JoinedClass:
372*e038c9c4Sjoerg case Option::SeparateClass:
373*e038c9c4Sjoerg case Option::JoinedOrSeparateClass:
374*e038c9c4Sjoerg for (const std::string &Value : Values)
375*e038c9c4Sjoerg denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
376*e038c9c4Sjoerg break;
377*e038c9c4Sjoerg default:
378*e038c9c4Sjoerg llvm_unreachable("Cannot denormalize an option with option class "
379*e038c9c4Sjoerg "incompatible with string vector denormalization.");
380*e038c9c4Sjoerg }
381*e038c9c4Sjoerg }
382*e038c9c4Sjoerg
normalizeTriple(OptSpecifier Opt,int TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)383*e038c9c4Sjoerg static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
384*e038c9c4Sjoerg const ArgList &Args,
385*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
386*e038c9c4Sjoerg auto *Arg = Args.getLastArg(Opt);
387*e038c9c4Sjoerg if (!Arg)
388*e038c9c4Sjoerg return None;
389*e038c9c4Sjoerg return llvm::Triple::normalize(Arg->getValue());
390*e038c9c4Sjoerg }
391*e038c9c4Sjoerg
392*e038c9c4Sjoerg template <typename T, typename U>
mergeForwardValue(T KeyPath,U Value)393*e038c9c4Sjoerg static T mergeForwardValue(T KeyPath, U Value) {
394*e038c9c4Sjoerg return static_cast<T>(Value);
395*e038c9c4Sjoerg }
396*e038c9c4Sjoerg
mergeMaskValue(T KeyPath,U Value)397*e038c9c4Sjoerg template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
398*e038c9c4Sjoerg return KeyPath | Value;
399*e038c9c4Sjoerg }
400*e038c9c4Sjoerg
extractForwardValue(T KeyPath)401*e038c9c4Sjoerg template <typename T> static T extractForwardValue(T KeyPath) {
402*e038c9c4Sjoerg return KeyPath;
403*e038c9c4Sjoerg }
404*e038c9c4Sjoerg
405*e038c9c4Sjoerg template <typename T, typename U, U Value>
extractMaskValue(T KeyPath)406*e038c9c4Sjoerg static T extractMaskValue(T KeyPath) {
407*e038c9c4Sjoerg return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
408*e038c9c4Sjoerg }
409*e038c9c4Sjoerg
410*e038c9c4Sjoerg #define PARSE_OPTION_WITH_MARSHALLING( \
411*e038c9c4Sjoerg ARGS, DIAGS, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
412*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX) \
413*e038c9c4Sjoerg if ((FLAGS)&options::CC1Option) { \
414*e038c9c4Sjoerg KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
415*e038c9c4Sjoerg if (IMPLIED_CHECK) \
416*e038c9c4Sjoerg KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
417*e038c9c4Sjoerg if (SHOULD_PARSE) \
418*e038c9c4Sjoerg if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
419*e038c9c4Sjoerg KEYPATH = \
420*e038c9c4Sjoerg MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
421*e038c9c4Sjoerg }
422*e038c9c4Sjoerg
423*e038c9c4Sjoerg // Capture the extracted value as a lambda argument to avoid potential issues
424*e038c9c4Sjoerg // with lifetime extension of the reference.
425*e038c9c4Sjoerg #define GENERATE_OPTION_WITH_MARSHALLING( \
426*e038c9c4Sjoerg ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, \
427*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, \
428*e038c9c4Sjoerg TABLE_INDEX) \
429*e038c9c4Sjoerg if ((FLAGS)&options::CC1Option) { \
430*e038c9c4Sjoerg [&](const auto &Extracted) { \
431*e038c9c4Sjoerg if (ALWAYS_EMIT || \
432*e038c9c4Sjoerg (Extracted != \
433*e038c9c4Sjoerg static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
434*e038c9c4Sjoerg : (DEFAULT_VALUE)))) \
435*e038c9c4Sjoerg DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class, \
436*e038c9c4Sjoerg TABLE_INDEX, Extracted); \
437*e038c9c4Sjoerg }(EXTRACTOR(KEYPATH)); \
438*e038c9c4Sjoerg }
439*e038c9c4Sjoerg
440*e038c9c4Sjoerg static const StringRef GetInputKindName(InputKind IK);
441*e038c9c4Sjoerg
FixupInvocation(CompilerInvocation & Invocation,DiagnosticsEngine & Diags,const ArgList & Args,InputKind IK)442*e038c9c4Sjoerg static bool FixupInvocation(CompilerInvocation &Invocation,
443*e038c9c4Sjoerg DiagnosticsEngine &Diags, const ArgList &Args,
444*e038c9c4Sjoerg InputKind IK) {
445*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
446*e038c9c4Sjoerg
447*e038c9c4Sjoerg LangOptions &LangOpts = *Invocation.getLangOpts();
448*e038c9c4Sjoerg CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
449*e038c9c4Sjoerg TargetOptions &TargetOpts = Invocation.getTargetOpts();
450*e038c9c4Sjoerg FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
451*e038c9c4Sjoerg CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
452*e038c9c4Sjoerg CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
453*e038c9c4Sjoerg CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
454*e038c9c4Sjoerg CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
455*e038c9c4Sjoerg FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
456*e038c9c4Sjoerg
457*e038c9c4Sjoerg LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
458*e038c9c4Sjoerg LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
459*e038c9c4Sjoerg LangOpts.CurrentModule = LangOpts.ModuleName;
460*e038c9c4Sjoerg
461*e038c9c4Sjoerg llvm::Triple T(TargetOpts.Triple);
462*e038c9c4Sjoerg llvm::Triple::ArchType Arch = T.getArch();
463*e038c9c4Sjoerg
464*e038c9c4Sjoerg CodeGenOpts.CodeModel = TargetOpts.CodeModel;
465*e038c9c4Sjoerg
466*e038c9c4Sjoerg if (LangOpts.getExceptionHandling() !=
467*e038c9c4Sjoerg LangOptions::ExceptionHandlingKind::None &&
468*e038c9c4Sjoerg T.isWindowsMSVCEnvironment())
469*e038c9c4Sjoerg Diags.Report(diag::err_fe_invalid_exception_model)
470*e038c9c4Sjoerg << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
471*e038c9c4Sjoerg
472*e038c9c4Sjoerg if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
473*e038c9c4Sjoerg Diags.Report(diag::warn_c_kext);
474*e038c9c4Sjoerg
475*e038c9c4Sjoerg if (Args.hasArg(OPT_fconcepts_ts))
476*e038c9c4Sjoerg Diags.Report(diag::warn_fe_concepts_ts_flag);
477*e038c9c4Sjoerg
478*e038c9c4Sjoerg if (LangOpts.NewAlignOverride &&
479*e038c9c4Sjoerg !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
480*e038c9c4Sjoerg Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
481*e038c9c4Sjoerg Diags.Report(diag::err_fe_invalid_alignment)
482*e038c9c4Sjoerg << A->getAsString(Args) << A->getValue();
483*e038c9c4Sjoerg LangOpts.NewAlignOverride = 0;
484*e038c9c4Sjoerg }
485*e038c9c4Sjoerg
486*e038c9c4Sjoerg // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
487*e038c9c4Sjoerg if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
488*e038c9c4Sjoerg Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
489*e038c9c4Sjoerg << "-fsycl-is-host";
490*e038c9c4Sjoerg
491*e038c9c4Sjoerg if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
492*e038c9c4Sjoerg Diags.Report(diag::err_drv_argument_not_allowed_with)
493*e038c9c4Sjoerg << "-fgnu89-inline" << GetInputKindName(IK);
494*e038c9c4Sjoerg
495*e038c9c4Sjoerg if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
496*e038c9c4Sjoerg Diags.Report(diag::warn_ignored_hip_only_option)
497*e038c9c4Sjoerg << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
498*e038c9c4Sjoerg
499*e038c9c4Sjoerg if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
500*e038c9c4Sjoerg Diags.Report(diag::warn_ignored_hip_only_option)
501*e038c9c4Sjoerg << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
502*e038c9c4Sjoerg
503*e038c9c4Sjoerg // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
504*e038c9c4Sjoerg // This option should be deprecated for CL > 1.0 because
505*e038c9c4Sjoerg // this option was added for compatibility with OpenCL 1.0.
506*e038c9c4Sjoerg if (Args.getLastArg(OPT_cl_strict_aliasing) && LangOpts.OpenCLVersion > 100)
507*e038c9c4Sjoerg Diags.Report(diag::warn_option_invalid_ocl_version)
508*e038c9c4Sjoerg << LangOpts.getOpenCLVersionTuple().getAsString()
509*e038c9c4Sjoerg << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
510*e038c9c4Sjoerg
511*e038c9c4Sjoerg if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
512*e038c9c4Sjoerg auto DefaultCC = LangOpts.getDefaultCallingConv();
513*e038c9c4Sjoerg
514*e038c9c4Sjoerg bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
515*e038c9c4Sjoerg DefaultCC == LangOptions::DCC_StdCall) &&
516*e038c9c4Sjoerg Arch != llvm::Triple::x86;
517*e038c9c4Sjoerg emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
518*e038c9c4Sjoerg DefaultCC == LangOptions::DCC_RegCall) &&
519*e038c9c4Sjoerg !T.isX86();
520*e038c9c4Sjoerg if (emitError)
521*e038c9c4Sjoerg Diags.Report(diag::err_drv_argument_not_allowed_with)
522*e038c9c4Sjoerg << A->getSpelling() << T.getTriple();
523*e038c9c4Sjoerg }
524*e038c9c4Sjoerg
525*e038c9c4Sjoerg if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
526*e038c9c4Sjoerg Diags.Report(diag::err_drv_argument_only_allowed_with)
527*e038c9c4Sjoerg << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
528*e038c9c4Sjoerg << "-fno-legacy-pass-manager";
529*e038c9c4Sjoerg
530*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
531*e038c9c4Sjoerg }
5327330f729Sjoerg
5337330f729Sjoerg //===----------------------------------------------------------------------===//
5347330f729Sjoerg // Deserialization (from args)
5357330f729Sjoerg //===----------------------------------------------------------------------===//
5367330f729Sjoerg
getOptimizationLevel(ArgList & Args,InputKind IK,DiagnosticsEngine & Diags)5377330f729Sjoerg static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
5387330f729Sjoerg DiagnosticsEngine &Diags) {
5397330f729Sjoerg unsigned DefaultOpt = llvm::CodeGenOpt::None;
540*e038c9c4Sjoerg if ((IK.getLanguage() == Language::OpenCL ||
541*e038c9c4Sjoerg IK.getLanguage() == Language::OpenCLCXX) &&
542*e038c9c4Sjoerg !Args.hasArg(OPT_cl_opt_disable))
5437330f729Sjoerg DefaultOpt = llvm::CodeGenOpt::Default;
5447330f729Sjoerg
5457330f729Sjoerg if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5467330f729Sjoerg if (A->getOption().matches(options::OPT_O0))
5477330f729Sjoerg return llvm::CodeGenOpt::None;
5487330f729Sjoerg
5497330f729Sjoerg if (A->getOption().matches(options::OPT_Ofast))
5507330f729Sjoerg return llvm::CodeGenOpt::Aggressive;
5517330f729Sjoerg
5527330f729Sjoerg assert(A->getOption().matches(options::OPT_O));
5537330f729Sjoerg
5547330f729Sjoerg StringRef S(A->getValue());
555*e038c9c4Sjoerg if (S == "s" || S == "z")
5567330f729Sjoerg return llvm::CodeGenOpt::Default;
5577330f729Sjoerg
5587330f729Sjoerg if (S == "g")
5597330f729Sjoerg return llvm::CodeGenOpt::Less;
5607330f729Sjoerg
5617330f729Sjoerg return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
5627330f729Sjoerg }
5637330f729Sjoerg
5647330f729Sjoerg return DefaultOpt;
5657330f729Sjoerg }
5667330f729Sjoerg
getOptimizationLevelSize(ArgList & Args)5677330f729Sjoerg static unsigned getOptimizationLevelSize(ArgList &Args) {
5687330f729Sjoerg if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5697330f729Sjoerg if (A->getOption().matches(options::OPT_O)) {
5707330f729Sjoerg switch (A->getValue()[0]) {
5717330f729Sjoerg default:
5727330f729Sjoerg return 0;
5737330f729Sjoerg case 's':
5747330f729Sjoerg return 1;
5757330f729Sjoerg case 'z':
5767330f729Sjoerg return 2;
5777330f729Sjoerg }
5787330f729Sjoerg }
5797330f729Sjoerg }
5807330f729Sjoerg return 0;
5817330f729Sjoerg }
5827330f729Sjoerg
GenerateArg(SmallVectorImpl<const char * > & Args,llvm::opt::OptSpecifier OptSpecifier,CompilerInvocation::StringAllocator SA)583*e038c9c4Sjoerg static void GenerateArg(SmallVectorImpl<const char *> &Args,
584*e038c9c4Sjoerg llvm::opt::OptSpecifier OptSpecifier,
585*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
586*e038c9c4Sjoerg Option Opt = getDriverOptTable().getOption(OptSpecifier);
587*e038c9c4Sjoerg denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
588*e038c9c4Sjoerg Option::OptionClass::FlagClass, 0);
589*e038c9c4Sjoerg }
590*e038c9c4Sjoerg
GenerateArg(SmallVectorImpl<const char * > & Args,llvm::opt::OptSpecifier OptSpecifier,const Twine & Value,CompilerInvocation::StringAllocator SA)591*e038c9c4Sjoerg static void GenerateArg(SmallVectorImpl<const char *> &Args,
592*e038c9c4Sjoerg llvm::opt::OptSpecifier OptSpecifier,
593*e038c9c4Sjoerg const Twine &Value,
594*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
595*e038c9c4Sjoerg Option Opt = getDriverOptTable().getOption(OptSpecifier);
596*e038c9c4Sjoerg denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
597*e038c9c4Sjoerg Opt.getKind(), 0, Value);
598*e038c9c4Sjoerg }
599*e038c9c4Sjoerg
600*e038c9c4Sjoerg // Parse command line arguments into CompilerInvocation.
601*e038c9c4Sjoerg using ParseFn =
602*e038c9c4Sjoerg llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
603*e038c9c4Sjoerg DiagnosticsEngine &, const char *)>;
604*e038c9c4Sjoerg
605*e038c9c4Sjoerg // Generate command line arguments from CompilerInvocation.
606*e038c9c4Sjoerg using GenerateFn = llvm::function_ref<void(
607*e038c9c4Sjoerg CompilerInvocation &, SmallVectorImpl<const char *> &,
608*e038c9c4Sjoerg CompilerInvocation::StringAllocator)>;
609*e038c9c4Sjoerg
610*e038c9c4Sjoerg // May perform round-trip of command line arguments. By default, the round-trip
611*e038c9c4Sjoerg // is enabled if CLANG_ROUND_TRIP_CC1_ARGS was defined during build. This can be
612*e038c9c4Sjoerg // overwritten at run-time via the "-round-trip-args" and "-no-round-trip-args"
613*e038c9c4Sjoerg // command line flags.
614*e038c9c4Sjoerg // During round-trip, the command line arguments are parsed into a dummy
615*e038c9c4Sjoerg // instance of CompilerInvocation which is used to generate the command line
616*e038c9c4Sjoerg // arguments again. The real CompilerInvocation instance is then created by
617*e038c9c4Sjoerg // parsing the generated arguments, not the original ones.
RoundTrip(ParseFn Parse,GenerateFn Generate,CompilerInvocation & RealInvocation,CompilerInvocation & DummyInvocation,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0)618*e038c9c4Sjoerg static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
619*e038c9c4Sjoerg CompilerInvocation &RealInvocation,
620*e038c9c4Sjoerg CompilerInvocation &DummyInvocation,
621*e038c9c4Sjoerg ArrayRef<const char *> CommandLineArgs,
622*e038c9c4Sjoerg DiagnosticsEngine &Diags, const char *Argv0) {
623*e038c9c4Sjoerg // FIXME: Switch to '#ifndef NDEBUG' when possible.
624*e038c9c4Sjoerg #ifdef CLANG_ROUND_TRIP_CC1_ARGS
625*e038c9c4Sjoerg bool DoRoundTripDefault = true;
626*e038c9c4Sjoerg #else
627*e038c9c4Sjoerg bool DoRoundTripDefault = false;
628*e038c9c4Sjoerg #endif
629*e038c9c4Sjoerg
630*e038c9c4Sjoerg bool DoRoundTrip = DoRoundTripDefault;
631*e038c9c4Sjoerg for (const auto *Arg : CommandLineArgs) {
632*e038c9c4Sjoerg if (Arg == StringRef("-round-trip-args"))
633*e038c9c4Sjoerg DoRoundTrip = true;
634*e038c9c4Sjoerg if (Arg == StringRef("-no-round-trip-args"))
635*e038c9c4Sjoerg DoRoundTrip = false;
636*e038c9c4Sjoerg }
637*e038c9c4Sjoerg
638*e038c9c4Sjoerg // If round-trip was not requested, simply run the parser with the real
639*e038c9c4Sjoerg // invocation diagnostics.
640*e038c9c4Sjoerg if (!DoRoundTrip)
641*e038c9c4Sjoerg return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
642*e038c9c4Sjoerg
643*e038c9c4Sjoerg // Serializes quoted (and potentially escaped) arguments.
644*e038c9c4Sjoerg auto SerializeArgs = [](ArrayRef<const char *> Args) {
645*e038c9c4Sjoerg std::string Buffer;
646*e038c9c4Sjoerg llvm::raw_string_ostream OS(Buffer);
647*e038c9c4Sjoerg for (const char *Arg : Args) {
648*e038c9c4Sjoerg llvm::sys::printArg(OS, Arg, /*Quote=*/true);
649*e038c9c4Sjoerg OS << ' ';
650*e038c9c4Sjoerg }
651*e038c9c4Sjoerg OS.flush();
652*e038c9c4Sjoerg return Buffer;
653*e038c9c4Sjoerg };
654*e038c9c4Sjoerg
655*e038c9c4Sjoerg // Setup a dummy DiagnosticsEngine.
656*e038c9c4Sjoerg DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
657*e038c9c4Sjoerg DummyDiags.setClient(new TextDiagnosticBuffer());
658*e038c9c4Sjoerg
659*e038c9c4Sjoerg // Run the first parse on the original arguments with the dummy invocation and
660*e038c9c4Sjoerg // diagnostics.
661*e038c9c4Sjoerg if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
662*e038c9c4Sjoerg DummyDiags.getNumWarnings() != 0) {
663*e038c9c4Sjoerg // If the first parse did not succeed, it must be user mistake (invalid
664*e038c9c4Sjoerg // command line arguments). We won't be able to generate arguments that
665*e038c9c4Sjoerg // would reproduce the same result. Let's fail again with the real
666*e038c9c4Sjoerg // invocation and diagnostics, so all side-effects of parsing are visible.
667*e038c9c4Sjoerg unsigned NumWarningsBefore = Diags.getNumWarnings();
668*e038c9c4Sjoerg auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
669*e038c9c4Sjoerg if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
670*e038c9c4Sjoerg return Success;
671*e038c9c4Sjoerg
672*e038c9c4Sjoerg // Parse with original options and diagnostics succeeded even though it
673*e038c9c4Sjoerg // shouldn't have. Something is off.
674*e038c9c4Sjoerg Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
675*e038c9c4Sjoerg Diags.Report(diag::note_cc1_round_trip_original)
676*e038c9c4Sjoerg << SerializeArgs(CommandLineArgs);
677*e038c9c4Sjoerg return false;
678*e038c9c4Sjoerg }
679*e038c9c4Sjoerg
680*e038c9c4Sjoerg // Setup string allocator.
681*e038c9c4Sjoerg llvm::BumpPtrAllocator Alloc;
682*e038c9c4Sjoerg llvm::StringSaver StringPool(Alloc);
683*e038c9c4Sjoerg auto SA = [&StringPool](const Twine &Arg) {
684*e038c9c4Sjoerg return StringPool.save(Arg).data();
685*e038c9c4Sjoerg };
686*e038c9c4Sjoerg
687*e038c9c4Sjoerg // Generate arguments from the dummy invocation. If Generate is the
688*e038c9c4Sjoerg // inverse of Parse, the newly generated arguments must have the same
689*e038c9c4Sjoerg // semantics as the original.
690*e038c9c4Sjoerg SmallVector<const char *> GeneratedArgs1;
691*e038c9c4Sjoerg Generate(DummyInvocation, GeneratedArgs1, SA);
692*e038c9c4Sjoerg
693*e038c9c4Sjoerg // Run the second parse, now on the generated arguments, and with the real
694*e038c9c4Sjoerg // invocation and diagnostics. The result is what we will end up using for the
695*e038c9c4Sjoerg // rest of compilation, so if Generate is not inverse of Parse, something down
696*e038c9c4Sjoerg // the line will break.
697*e038c9c4Sjoerg bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0);
698*e038c9c4Sjoerg
699*e038c9c4Sjoerg // The first parse on original arguments succeeded, but second parse of
700*e038c9c4Sjoerg // generated arguments failed. Something must be wrong with the generator.
701*e038c9c4Sjoerg if (!Success2) {
702*e038c9c4Sjoerg Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
703*e038c9c4Sjoerg Diags.Report(diag::note_cc1_round_trip_generated)
704*e038c9c4Sjoerg << 1 << SerializeArgs(GeneratedArgs1);
705*e038c9c4Sjoerg return false;
706*e038c9c4Sjoerg }
707*e038c9c4Sjoerg
708*e038c9c4Sjoerg // Generate arguments again, this time from the options we will end up using
709*e038c9c4Sjoerg // for the rest of the compilation.
710*e038c9c4Sjoerg SmallVector<const char *> GeneratedArgs2;
711*e038c9c4Sjoerg Generate(RealInvocation, GeneratedArgs2, SA);
712*e038c9c4Sjoerg
713*e038c9c4Sjoerg // Compares two lists of generated arguments.
714*e038c9c4Sjoerg auto Equal = [](const ArrayRef<const char *> A,
715*e038c9c4Sjoerg const ArrayRef<const char *> B) {
716*e038c9c4Sjoerg return std::equal(A.begin(), A.end(), B.begin(), B.end(),
717*e038c9c4Sjoerg [](const char *AElem, const char *BElem) {
718*e038c9c4Sjoerg return StringRef(AElem) == StringRef(BElem);
719*e038c9c4Sjoerg });
720*e038c9c4Sjoerg };
721*e038c9c4Sjoerg
722*e038c9c4Sjoerg // If we generated different arguments from what we assume are two
723*e038c9c4Sjoerg // semantically equivalent CompilerInvocations, the Generate function may
724*e038c9c4Sjoerg // be non-deterministic.
725*e038c9c4Sjoerg if (!Equal(GeneratedArgs1, GeneratedArgs2)) {
726*e038c9c4Sjoerg Diags.Report(diag::err_cc1_round_trip_mismatch);
727*e038c9c4Sjoerg Diags.Report(diag::note_cc1_round_trip_generated)
728*e038c9c4Sjoerg << 1 << SerializeArgs(GeneratedArgs1);
729*e038c9c4Sjoerg Diags.Report(diag::note_cc1_round_trip_generated)
730*e038c9c4Sjoerg << 2 << SerializeArgs(GeneratedArgs2);
731*e038c9c4Sjoerg return false;
732*e038c9c4Sjoerg }
733*e038c9c4Sjoerg
734*e038c9c4Sjoerg Diags.Report(diag::remark_cc1_round_trip_generated)
735*e038c9c4Sjoerg << 1 << SerializeArgs(GeneratedArgs1);
736*e038c9c4Sjoerg Diags.Report(diag::remark_cc1_round_trip_generated)
737*e038c9c4Sjoerg << 2 << SerializeArgs(GeneratedArgs2);
738*e038c9c4Sjoerg
739*e038c9c4Sjoerg return Success2;
740*e038c9c4Sjoerg }
741*e038c9c4Sjoerg
addDiagnosticArgs(ArgList & Args,OptSpecifier Group,OptSpecifier GroupWithValue,std::vector<std::string> & Diagnostics)7427330f729Sjoerg static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
7437330f729Sjoerg OptSpecifier GroupWithValue,
7447330f729Sjoerg std::vector<std::string> &Diagnostics) {
7457330f729Sjoerg for (auto *A : Args.filtered(Group)) {
7467330f729Sjoerg if (A->getOption().getKind() == Option::FlagClass) {
7477330f729Sjoerg // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
748*e038c9c4Sjoerg // its name (minus the "W" or "R" at the beginning) to the diagnostics.
749*e038c9c4Sjoerg Diagnostics.push_back(
750*e038c9c4Sjoerg std::string(A->getOption().getName().drop_front(1)));
7517330f729Sjoerg } else if (A->getOption().matches(GroupWithValue)) {
752*e038c9c4Sjoerg // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
753*e038c9c4Sjoerg // group. Add only the group name to the diagnostics.
754*e038c9c4Sjoerg Diagnostics.push_back(
755*e038c9c4Sjoerg std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
7567330f729Sjoerg } else {
7577330f729Sjoerg // Otherwise, add its value (for OPT_W_Joined and similar).
758*e038c9c4Sjoerg Diagnostics.push_back(A->getValue());
7597330f729Sjoerg }
7607330f729Sjoerg }
7617330f729Sjoerg }
7627330f729Sjoerg
7637330f729Sjoerg // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
7647330f729Sjoerg // it won't verify the input.
7657330f729Sjoerg static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
7667330f729Sjoerg DiagnosticsEngine *Diags);
7677330f729Sjoerg
getAllNoBuiltinFuncValues(ArgList & Args,std::vector<std::string> & Funcs)7687330f729Sjoerg static void getAllNoBuiltinFuncValues(ArgList &Args,
7697330f729Sjoerg std::vector<std::string> &Funcs) {
770*e038c9c4Sjoerg std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
771*e038c9c4Sjoerg auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
772*e038c9c4Sjoerg return Builtin::Context::isBuiltinFunc(FuncName);
773*e038c9c4Sjoerg });
774*e038c9c4Sjoerg Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
775*e038c9c4Sjoerg }
776*e038c9c4Sjoerg
GenerateAnalyzerArgs(AnalyzerOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)777*e038c9c4Sjoerg static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
778*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
779*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
780*e038c9c4Sjoerg const AnalyzerOptions *AnalyzerOpts = &Opts;
781*e038c9c4Sjoerg
782*e038c9c4Sjoerg #define ANALYZER_OPTION_WITH_MARSHALLING( \
783*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
784*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
785*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
786*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
787*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
788*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
789*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
790*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
791*e038c9c4Sjoerg #undef ANALYZER_OPTION_WITH_MARSHALLING
792*e038c9c4Sjoerg
793*e038c9c4Sjoerg if (Opts.AnalysisStoreOpt != RegionStoreModel) {
794*e038c9c4Sjoerg switch (Opts.AnalysisStoreOpt) {
795*e038c9c4Sjoerg #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
796*e038c9c4Sjoerg case NAME##Model: \
797*e038c9c4Sjoerg GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA); \
798*e038c9c4Sjoerg break;
799*e038c9c4Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
800*e038c9c4Sjoerg default:
801*e038c9c4Sjoerg llvm_unreachable("Tried to generate unknown analysis store.");
8027330f729Sjoerg }
8037330f729Sjoerg }
804*e038c9c4Sjoerg
805*e038c9c4Sjoerg if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
806*e038c9c4Sjoerg switch (Opts.AnalysisConstraintsOpt) {
807*e038c9c4Sjoerg #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
808*e038c9c4Sjoerg case NAME##Model: \
809*e038c9c4Sjoerg GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA); \
810*e038c9c4Sjoerg break;
811*e038c9c4Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
812*e038c9c4Sjoerg default:
813*e038c9c4Sjoerg llvm_unreachable("Tried to generate unknown analysis constraint.");
814*e038c9c4Sjoerg }
815*e038c9c4Sjoerg }
816*e038c9c4Sjoerg
817*e038c9c4Sjoerg if (Opts.AnalysisDiagOpt != PD_HTML) {
818*e038c9c4Sjoerg switch (Opts.AnalysisDiagOpt) {
819*e038c9c4Sjoerg #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
820*e038c9c4Sjoerg case PD_##NAME: \
821*e038c9c4Sjoerg GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA); \
822*e038c9c4Sjoerg break;
823*e038c9c4Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
824*e038c9c4Sjoerg default:
825*e038c9c4Sjoerg llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
826*e038c9c4Sjoerg }
827*e038c9c4Sjoerg }
828*e038c9c4Sjoerg
829*e038c9c4Sjoerg if (Opts.AnalysisPurgeOpt != PurgeStmt) {
830*e038c9c4Sjoerg switch (Opts.AnalysisPurgeOpt) {
831*e038c9c4Sjoerg #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
832*e038c9c4Sjoerg case NAME: \
833*e038c9c4Sjoerg GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA); \
834*e038c9c4Sjoerg break;
835*e038c9c4Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
836*e038c9c4Sjoerg default:
837*e038c9c4Sjoerg llvm_unreachable("Tried to generate unknown analysis purge mode.");
838*e038c9c4Sjoerg }
839*e038c9c4Sjoerg }
840*e038c9c4Sjoerg
841*e038c9c4Sjoerg if (Opts.InliningMode != NoRedundancy) {
842*e038c9c4Sjoerg switch (Opts.InliningMode) {
843*e038c9c4Sjoerg #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
844*e038c9c4Sjoerg case NAME: \
845*e038c9c4Sjoerg GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA); \
846*e038c9c4Sjoerg break;
847*e038c9c4Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
848*e038c9c4Sjoerg default:
849*e038c9c4Sjoerg llvm_unreachable("Tried to generate unknown analysis inlining mode.");
850*e038c9c4Sjoerg }
851*e038c9c4Sjoerg }
852*e038c9c4Sjoerg
853*e038c9c4Sjoerg for (const auto &CP : Opts.CheckersAndPackages) {
854*e038c9c4Sjoerg OptSpecifier Opt =
855*e038c9c4Sjoerg CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
856*e038c9c4Sjoerg GenerateArg(Args, Opt, CP.first, SA);
857*e038c9c4Sjoerg }
858*e038c9c4Sjoerg
859*e038c9c4Sjoerg AnalyzerOptions ConfigOpts;
860*e038c9c4Sjoerg parseAnalyzerConfigs(ConfigOpts, nullptr);
861*e038c9c4Sjoerg
862*e038c9c4Sjoerg for (const auto &C : Opts.Config) {
863*e038c9c4Sjoerg // Don't generate anything that came from parseAnalyzerConfigs. It would be
864*e038c9c4Sjoerg // redundant and may not be valid on the command line.
865*e038c9c4Sjoerg auto Entry = ConfigOpts.Config.find(C.getKey());
866*e038c9c4Sjoerg if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
867*e038c9c4Sjoerg continue;
868*e038c9c4Sjoerg
869*e038c9c4Sjoerg GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA);
870*e038c9c4Sjoerg }
871*e038c9c4Sjoerg
872*e038c9c4Sjoerg // Nothing to generate for FullCompilerInvocation.
8737330f729Sjoerg }
8747330f729Sjoerg
ParseAnalyzerArgs(AnalyzerOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)8757330f729Sjoerg static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
8767330f729Sjoerg DiagnosticsEngine &Diags) {
877*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
878*e038c9c4Sjoerg
879*e038c9c4Sjoerg AnalyzerOptions *AnalyzerOpts = &Opts;
880*e038c9c4Sjoerg
881*e038c9c4Sjoerg #define ANALYZER_OPTION_WITH_MARSHALLING( \
882*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
883*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
884*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
885*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
886*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
887*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
888*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
889*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
890*e038c9c4Sjoerg #undef ANALYZER_OPTION_WITH_MARSHALLING
891*e038c9c4Sjoerg
8927330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
8937330f729Sjoerg StringRef Name = A->getValue();
8947330f729Sjoerg AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
8957330f729Sjoerg #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
8967330f729Sjoerg .Case(CMDFLAG, NAME##Model)
8977330f729Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
8987330f729Sjoerg .Default(NumStores);
8997330f729Sjoerg if (Value == NumStores) {
9007330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
9017330f729Sjoerg << A->getAsString(Args) << Name;
9027330f729Sjoerg } else {
9037330f729Sjoerg Opts.AnalysisStoreOpt = Value;
9047330f729Sjoerg }
9057330f729Sjoerg }
9067330f729Sjoerg
9077330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
9087330f729Sjoerg StringRef Name = A->getValue();
9097330f729Sjoerg AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
9107330f729Sjoerg #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
9117330f729Sjoerg .Case(CMDFLAG, NAME##Model)
9127330f729Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
9137330f729Sjoerg .Default(NumConstraints);
9147330f729Sjoerg if (Value == NumConstraints) {
9157330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
9167330f729Sjoerg << A->getAsString(Args) << Name;
9177330f729Sjoerg } else {
9187330f729Sjoerg Opts.AnalysisConstraintsOpt = Value;
9197330f729Sjoerg }
9207330f729Sjoerg }
9217330f729Sjoerg
9227330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
9237330f729Sjoerg StringRef Name = A->getValue();
9247330f729Sjoerg AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
9257330f729Sjoerg #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
9267330f729Sjoerg .Case(CMDFLAG, PD_##NAME)
9277330f729Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
9287330f729Sjoerg .Default(NUM_ANALYSIS_DIAG_CLIENTS);
9297330f729Sjoerg if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
9307330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
9317330f729Sjoerg << A->getAsString(Args) << Name;
9327330f729Sjoerg } else {
9337330f729Sjoerg Opts.AnalysisDiagOpt = Value;
9347330f729Sjoerg }
9357330f729Sjoerg }
9367330f729Sjoerg
9377330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
9387330f729Sjoerg StringRef Name = A->getValue();
9397330f729Sjoerg AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
9407330f729Sjoerg #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
9417330f729Sjoerg .Case(CMDFLAG, NAME)
9427330f729Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
9437330f729Sjoerg .Default(NumPurgeModes);
9447330f729Sjoerg if (Value == NumPurgeModes) {
9457330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
9467330f729Sjoerg << A->getAsString(Args) << Name;
9477330f729Sjoerg } else {
9487330f729Sjoerg Opts.AnalysisPurgeOpt = Value;
9497330f729Sjoerg }
9507330f729Sjoerg }
9517330f729Sjoerg
9527330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
9537330f729Sjoerg StringRef Name = A->getValue();
9547330f729Sjoerg AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
9557330f729Sjoerg #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
9567330f729Sjoerg .Case(CMDFLAG, NAME)
9577330f729Sjoerg #include "clang/StaticAnalyzer/Core/Analyses.def"
9587330f729Sjoerg .Default(NumInliningModes);
9597330f729Sjoerg if (Value == NumInliningModes) {
9607330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
9617330f729Sjoerg << A->getAsString(Args) << Name;
9627330f729Sjoerg } else {
9637330f729Sjoerg Opts.InliningMode = Value;
9647330f729Sjoerg }
9657330f729Sjoerg }
9667330f729Sjoerg
9677330f729Sjoerg Opts.CheckersAndPackages.clear();
9687330f729Sjoerg for (const Arg *A :
9697330f729Sjoerg Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
9707330f729Sjoerg A->claim();
9717330f729Sjoerg bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
9727330f729Sjoerg // We can have a list of comma separated checker names, e.g:
9737330f729Sjoerg // '-analyzer-checker=cocoa,unix'
9747330f729Sjoerg StringRef CheckerAndPackageList = A->getValue();
9757330f729Sjoerg SmallVector<StringRef, 16> CheckersAndPackages;
9767330f729Sjoerg CheckerAndPackageList.split(CheckersAndPackages, ",");
977*e038c9c4Sjoerg for (const StringRef &CheckerOrPackage : CheckersAndPackages)
978*e038c9c4Sjoerg Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
979*e038c9c4Sjoerg IsEnabled);
9807330f729Sjoerg }
9817330f729Sjoerg
9827330f729Sjoerg // Go through the analyzer configuration options.
9837330f729Sjoerg for (const auto *A : Args.filtered(OPT_analyzer_config)) {
9847330f729Sjoerg
9857330f729Sjoerg // We can have a list of comma separated config names, e.g:
9867330f729Sjoerg // '-analyzer-config key1=val1,key2=val2'
9877330f729Sjoerg StringRef configList = A->getValue();
9887330f729Sjoerg SmallVector<StringRef, 4> configVals;
9897330f729Sjoerg configList.split(configVals, ",");
9907330f729Sjoerg for (const auto &configVal : configVals) {
9917330f729Sjoerg StringRef key, val;
9927330f729Sjoerg std::tie(key, val) = configVal.split("=");
9937330f729Sjoerg if (val.empty()) {
9947330f729Sjoerg Diags.Report(SourceLocation(),
9957330f729Sjoerg diag::err_analyzer_config_no_value) << configVal;
9967330f729Sjoerg break;
9977330f729Sjoerg }
9987330f729Sjoerg if (val.find('=') != StringRef::npos) {
9997330f729Sjoerg Diags.Report(SourceLocation(),
10007330f729Sjoerg diag::err_analyzer_config_multiple_values)
10017330f729Sjoerg << configVal;
10027330f729Sjoerg break;
10037330f729Sjoerg }
10047330f729Sjoerg
10057330f729Sjoerg // TODO: Check checker options too, possibly in CheckerRegistry.
10067330f729Sjoerg // Leave unknown non-checker configs unclaimed.
10077330f729Sjoerg if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
10087330f729Sjoerg if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
10097330f729Sjoerg Diags.Report(diag::err_analyzer_config_unknown) << key;
10107330f729Sjoerg continue;
10117330f729Sjoerg }
10127330f729Sjoerg
10137330f729Sjoerg A->claim();
1014*e038c9c4Sjoerg Opts.Config[key] = std::string(val);
10157330f729Sjoerg }
10167330f729Sjoerg }
10177330f729Sjoerg
10187330f729Sjoerg if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
10197330f729Sjoerg parseAnalyzerConfigs(Opts, &Diags);
10207330f729Sjoerg else
10217330f729Sjoerg parseAnalyzerConfigs(Opts, nullptr);
10227330f729Sjoerg
10237330f729Sjoerg llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
10247330f729Sjoerg for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
10257330f729Sjoerg if (i != 0)
10267330f729Sjoerg os << " ";
10277330f729Sjoerg os << Args.getArgString(i);
10287330f729Sjoerg }
10297330f729Sjoerg os.flush();
10307330f729Sjoerg
1031*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
10327330f729Sjoerg }
10337330f729Sjoerg
getStringOption(AnalyzerOptions::ConfigTable & Config,StringRef OptionName,StringRef DefaultVal)10347330f729Sjoerg static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
10357330f729Sjoerg StringRef OptionName, StringRef DefaultVal) {
1036*e038c9c4Sjoerg return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
10377330f729Sjoerg }
10387330f729Sjoerg
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,StringRef & OptionField,StringRef Name,StringRef DefaultVal)10397330f729Sjoerg static void initOption(AnalyzerOptions::ConfigTable &Config,
10407330f729Sjoerg DiagnosticsEngine *Diags,
10417330f729Sjoerg StringRef &OptionField, StringRef Name,
10427330f729Sjoerg StringRef DefaultVal) {
10437330f729Sjoerg // String options may be known to invalid (e.g. if the expected string is a
10447330f729Sjoerg // file name, but the file does not exist), those will have to be checked in
10457330f729Sjoerg // parseConfigs.
10467330f729Sjoerg OptionField = getStringOption(Config, Name, DefaultVal);
10477330f729Sjoerg }
10487330f729Sjoerg
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,bool & OptionField,StringRef Name,bool DefaultVal)10497330f729Sjoerg static void initOption(AnalyzerOptions::ConfigTable &Config,
10507330f729Sjoerg DiagnosticsEngine *Diags,
10517330f729Sjoerg bool &OptionField, StringRef Name, bool DefaultVal) {
10527330f729Sjoerg auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
10537330f729Sjoerg getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
10547330f729Sjoerg .Case("true", true)
10557330f729Sjoerg .Case("false", false)
10567330f729Sjoerg .Default(None);
10577330f729Sjoerg
10587330f729Sjoerg if (!PossiblyInvalidVal) {
10597330f729Sjoerg if (Diags)
10607330f729Sjoerg Diags->Report(diag::err_analyzer_config_invalid_input)
10617330f729Sjoerg << Name << "a boolean";
10627330f729Sjoerg else
10637330f729Sjoerg OptionField = DefaultVal;
10647330f729Sjoerg } else
10657330f729Sjoerg OptionField = PossiblyInvalidVal.getValue();
10667330f729Sjoerg }
10677330f729Sjoerg
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,unsigned & OptionField,StringRef Name,unsigned DefaultVal)10687330f729Sjoerg static void initOption(AnalyzerOptions::ConfigTable &Config,
10697330f729Sjoerg DiagnosticsEngine *Diags,
10707330f729Sjoerg unsigned &OptionField, StringRef Name,
10717330f729Sjoerg unsigned DefaultVal) {
10727330f729Sjoerg
10737330f729Sjoerg OptionField = DefaultVal;
10747330f729Sjoerg bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
10757330f729Sjoerg .getAsInteger(0, OptionField);
10767330f729Sjoerg if (Diags && HasFailed)
10777330f729Sjoerg Diags->Report(diag::err_analyzer_config_invalid_input)
10787330f729Sjoerg << Name << "an unsigned";
10797330f729Sjoerg }
10807330f729Sjoerg
parseAnalyzerConfigs(AnalyzerOptions & AnOpts,DiagnosticsEngine * Diags)10817330f729Sjoerg static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
10827330f729Sjoerg DiagnosticsEngine *Diags) {
10837330f729Sjoerg // TODO: There's no need to store the entire configtable, it'd be plenty
10847330f729Sjoerg // enough tostore checker options.
10857330f729Sjoerg
10867330f729Sjoerg #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
10877330f729Sjoerg initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
10887330f729Sjoerg
10897330f729Sjoerg #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
10907330f729Sjoerg SHALLOW_VAL, DEEP_VAL) \
10917330f729Sjoerg switch (AnOpts.getUserMode()) { \
10927330f729Sjoerg case UMK_Shallow: \
10937330f729Sjoerg initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \
10947330f729Sjoerg break; \
10957330f729Sjoerg case UMK_Deep: \
10967330f729Sjoerg initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \
10977330f729Sjoerg break; \
10987330f729Sjoerg } \
10997330f729Sjoerg
11007330f729Sjoerg #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
11017330f729Sjoerg #undef ANALYZER_OPTION
11027330f729Sjoerg #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
11037330f729Sjoerg
11047330f729Sjoerg // At this point, AnalyzerOptions is configured. Let's validate some options.
11057330f729Sjoerg
11067330f729Sjoerg // FIXME: Here we try to validate the silenced checkers or packages are valid.
11077330f729Sjoerg // The current approach only validates the registered checkers which does not
11087330f729Sjoerg // contain the runtime enabled checkers and optimally we would validate both.
11097330f729Sjoerg if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
11107330f729Sjoerg std::vector<StringRef> Checkers =
11117330f729Sjoerg AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
11127330f729Sjoerg std::vector<StringRef> Packages =
11137330f729Sjoerg AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
11147330f729Sjoerg
11157330f729Sjoerg SmallVector<StringRef, 16> CheckersAndPackages;
11167330f729Sjoerg AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
11177330f729Sjoerg
1118*e038c9c4Sjoerg for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
11197330f729Sjoerg if (Diags) {
11207330f729Sjoerg bool IsChecker = CheckerOrPackage.contains('.');
11217330f729Sjoerg bool IsValidName =
11227330f729Sjoerg IsChecker
11237330f729Sjoerg ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end()
11247330f729Sjoerg : llvm::find(Packages, CheckerOrPackage) != Packages.end();
11257330f729Sjoerg
11267330f729Sjoerg if (!IsValidName)
11277330f729Sjoerg Diags->Report(diag::err_unknown_analyzer_checker_or_package)
11287330f729Sjoerg << CheckerOrPackage;
11297330f729Sjoerg }
11307330f729Sjoerg
11317330f729Sjoerg AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
11327330f729Sjoerg }
11337330f729Sjoerg }
11347330f729Sjoerg
11357330f729Sjoerg if (!Diags)
11367330f729Sjoerg return;
11377330f729Sjoerg
11387330f729Sjoerg if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
11397330f729Sjoerg Diags->Report(diag::err_analyzer_config_invalid_input)
11407330f729Sjoerg << "track-conditions-debug" << "'track-conditions' to also be enabled";
11417330f729Sjoerg
11427330f729Sjoerg if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
11437330f729Sjoerg Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
11447330f729Sjoerg << "a filename";
11457330f729Sjoerg
11467330f729Sjoerg if (!AnOpts.ModelPath.empty() &&
11477330f729Sjoerg !llvm::sys::fs::is_directory(AnOpts.ModelPath))
11487330f729Sjoerg Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
11497330f729Sjoerg << "a filename";
11507330f729Sjoerg }
11517330f729Sjoerg
1152*e038c9c4Sjoerg /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1153*e038c9c4Sjoerg static void
GenerateOptimizationRemark(SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,OptSpecifier OptEQ,StringRef Name,const CodeGenOptions::OptRemark & Remark)1154*e038c9c4Sjoerg GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args,
1155*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
1156*e038c9c4Sjoerg OptSpecifier OptEQ, StringRef Name,
1157*e038c9c4Sjoerg const CodeGenOptions::OptRemark &Remark) {
1158*e038c9c4Sjoerg if (Remark.hasValidPattern()) {
1159*e038c9c4Sjoerg GenerateArg(Args, OptEQ, Remark.Pattern, SA);
1160*e038c9c4Sjoerg } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1161*e038c9c4Sjoerg GenerateArg(Args, OPT_R_Joined, Name, SA);
1162*e038c9c4Sjoerg } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1163*e038c9c4Sjoerg GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
1164*e038c9c4Sjoerg }
11657330f729Sjoerg }
11667330f729Sjoerg
1167*e038c9c4Sjoerg /// Parse a remark command line argument. It may be missing, disabled/enabled by
1168*e038c9c4Sjoerg /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1169*e038c9c4Sjoerg /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1170*e038c9c4Sjoerg static CodeGenOptions::OptRemark
ParseOptimizationRemark(DiagnosticsEngine & Diags,ArgList & Args,OptSpecifier OptEQ,StringRef Name)1171*e038c9c4Sjoerg ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1172*e038c9c4Sjoerg OptSpecifier OptEQ, StringRef Name) {
1173*e038c9c4Sjoerg CodeGenOptions::OptRemark Result;
11747330f729Sjoerg
1175*e038c9c4Sjoerg auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A) {
1176*e038c9c4Sjoerg Result.Pattern = A->getValue();
11777330f729Sjoerg
11787330f729Sjoerg std::string RegexError;
1179*e038c9c4Sjoerg Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1180*e038c9c4Sjoerg if (!Result.Regex->isValid(RegexError)) {
11817330f729Sjoerg Diags.Report(diag::err_drv_optimization_remark_pattern)
1182*e038c9c4Sjoerg << RegexError << A->getAsString(Args);
1183*e038c9c4Sjoerg return false;
11847330f729Sjoerg }
1185*e038c9c4Sjoerg
1186*e038c9c4Sjoerg return true;
1187*e038c9c4Sjoerg };
1188*e038c9c4Sjoerg
1189*e038c9c4Sjoerg for (Arg *A : Args) {
1190*e038c9c4Sjoerg if (A->getOption().matches(OPT_R_Joined)) {
1191*e038c9c4Sjoerg StringRef Value = A->getValue();
1192*e038c9c4Sjoerg
1193*e038c9c4Sjoerg if (Value == Name)
1194*e038c9c4Sjoerg Result.Kind = CodeGenOptions::RK_Enabled;
1195*e038c9c4Sjoerg else if (Value == "everything")
1196*e038c9c4Sjoerg Result.Kind = CodeGenOptions::RK_EnabledEverything;
1197*e038c9c4Sjoerg else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1198*e038c9c4Sjoerg Result.Kind = CodeGenOptions::RK_Disabled;
1199*e038c9c4Sjoerg else if (Value == "no-everything")
1200*e038c9c4Sjoerg Result.Kind = CodeGenOptions::RK_DisabledEverything;
1201*e038c9c4Sjoerg } else if (A->getOption().matches(OptEQ)) {
1202*e038c9c4Sjoerg Result.Kind = CodeGenOptions::RK_WithPattern;
1203*e038c9c4Sjoerg if (!InitializeResultPattern(A))
1204*e038c9c4Sjoerg return CodeGenOptions::OptRemark();
1205*e038c9c4Sjoerg }
1206*e038c9c4Sjoerg }
1207*e038c9c4Sjoerg
1208*e038c9c4Sjoerg if (Result.Kind == CodeGenOptions::RK_Disabled ||
1209*e038c9c4Sjoerg Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1210*e038c9c4Sjoerg Result.Pattern = "";
1211*e038c9c4Sjoerg Result.Regex = nullptr;
1212*e038c9c4Sjoerg }
1213*e038c9c4Sjoerg
1214*e038c9c4Sjoerg return Result;
12157330f729Sjoerg }
12167330f729Sjoerg
parseDiagnosticLevelMask(StringRef FlagName,const std::vector<std::string> & Levels,DiagnosticsEngine & Diags,DiagnosticLevelMask & M)12177330f729Sjoerg static bool parseDiagnosticLevelMask(StringRef FlagName,
12187330f729Sjoerg const std::vector<std::string> &Levels,
1219*e038c9c4Sjoerg DiagnosticsEngine &Diags,
12207330f729Sjoerg DiagnosticLevelMask &M) {
12217330f729Sjoerg bool Success = true;
12227330f729Sjoerg for (const auto &Level : Levels) {
12237330f729Sjoerg DiagnosticLevelMask const PM =
12247330f729Sjoerg llvm::StringSwitch<DiagnosticLevelMask>(Level)
12257330f729Sjoerg .Case("note", DiagnosticLevelMask::Note)
12267330f729Sjoerg .Case("remark", DiagnosticLevelMask::Remark)
12277330f729Sjoerg .Case("warning", DiagnosticLevelMask::Warning)
12287330f729Sjoerg .Case("error", DiagnosticLevelMask::Error)
12297330f729Sjoerg .Default(DiagnosticLevelMask::None);
12307330f729Sjoerg if (PM == DiagnosticLevelMask::None) {
12317330f729Sjoerg Success = false;
1232*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
12337330f729Sjoerg }
12347330f729Sjoerg M = M | PM;
12357330f729Sjoerg }
12367330f729Sjoerg return Success;
12377330f729Sjoerg }
12387330f729Sjoerg
parseSanitizerKinds(StringRef FlagName,const std::vector<std::string> & Sanitizers,DiagnosticsEngine & Diags,SanitizerSet & S)12397330f729Sjoerg static void parseSanitizerKinds(StringRef FlagName,
12407330f729Sjoerg const std::vector<std::string> &Sanitizers,
12417330f729Sjoerg DiagnosticsEngine &Diags, SanitizerSet &S) {
12427330f729Sjoerg for (const auto &Sanitizer : Sanitizers) {
12437330f729Sjoerg SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
12447330f729Sjoerg if (K == SanitizerMask())
12457330f729Sjoerg Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
12467330f729Sjoerg else
12477330f729Sjoerg S.set(K, true);
12487330f729Sjoerg }
12497330f729Sjoerg }
12507330f729Sjoerg
serializeSanitizerKinds(SanitizerSet S)1251*e038c9c4Sjoerg static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1252*e038c9c4Sjoerg SmallVector<StringRef, 4> Values;
1253*e038c9c4Sjoerg serializeSanitizerSet(S, Values);
1254*e038c9c4Sjoerg return Values;
1255*e038c9c4Sjoerg }
1256*e038c9c4Sjoerg
parseXRayInstrumentationBundle(StringRef FlagName,StringRef Bundle,ArgList & Args,DiagnosticsEngine & D,XRayInstrSet & S)12577330f729Sjoerg static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
12587330f729Sjoerg ArgList &Args, DiagnosticsEngine &D,
12597330f729Sjoerg XRayInstrSet &S) {
12607330f729Sjoerg llvm::SmallVector<StringRef, 2> BundleParts;
12617330f729Sjoerg llvm::SplitString(Bundle, BundleParts, ",");
1262*e038c9c4Sjoerg for (const auto &B : BundleParts) {
12637330f729Sjoerg auto Mask = parseXRayInstrValue(B);
12647330f729Sjoerg if (Mask == XRayInstrKind::None)
12657330f729Sjoerg if (B != "none")
12667330f729Sjoerg D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
12677330f729Sjoerg else
12687330f729Sjoerg S.Mask = Mask;
12697330f729Sjoerg else if (Mask == XRayInstrKind::All)
12707330f729Sjoerg S.Mask = Mask;
12717330f729Sjoerg else
12727330f729Sjoerg S.set(Mask, true);
12737330f729Sjoerg }
12747330f729Sjoerg }
12757330f729Sjoerg
serializeXRayInstrumentationBundle(const XRayInstrSet & S)1276*e038c9c4Sjoerg static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1277*e038c9c4Sjoerg llvm::SmallVector<StringRef, 2> BundleParts;
1278*e038c9c4Sjoerg serializeXRayInstrValue(S, BundleParts);
1279*e038c9c4Sjoerg std::string Buffer;
1280*e038c9c4Sjoerg llvm::raw_string_ostream OS(Buffer);
1281*e038c9c4Sjoerg llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1282*e038c9c4Sjoerg return OS.str();
12837330f729Sjoerg }
12847330f729Sjoerg
12857330f729Sjoerg // Set the profile kind using fprofile-instrument-use-path.
setPGOUseInstrumentor(CodeGenOptions & Opts,const Twine & ProfileName)12867330f729Sjoerg static void setPGOUseInstrumentor(CodeGenOptions &Opts,
12877330f729Sjoerg const Twine &ProfileName) {
12887330f729Sjoerg auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
12897330f729Sjoerg // In error, return silently and let Clang PGOUse report the error message.
12907330f729Sjoerg if (auto E = ReaderOrErr.takeError()) {
12917330f729Sjoerg llvm::consumeError(std::move(E));
12927330f729Sjoerg Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
12937330f729Sjoerg return;
12947330f729Sjoerg }
12957330f729Sjoerg std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
12967330f729Sjoerg std::move(ReaderOrErr.get());
12977330f729Sjoerg if (PGOReader->isIRLevelProfile()) {
12987330f729Sjoerg if (PGOReader->hasCSIRLevelProfile())
12997330f729Sjoerg Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
13007330f729Sjoerg else
13017330f729Sjoerg Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
13027330f729Sjoerg } else
13037330f729Sjoerg Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
13047330f729Sjoerg }
13057330f729Sjoerg
GenerateCodeGenArgs(const CodeGenOptions & Opts,SmallVectorImpl<const char * > & Args,StringAllocator SA,const llvm::Triple & T,const std::string & OutputFile,const LangOptions * LangOpts)1306*e038c9c4Sjoerg void CompilerInvocation::GenerateCodeGenArgs(
1307*e038c9c4Sjoerg const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
1308*e038c9c4Sjoerg StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
1309*e038c9c4Sjoerg const LangOptions *LangOpts) {
1310*e038c9c4Sjoerg const CodeGenOptions &CodeGenOpts = Opts;
1311*e038c9c4Sjoerg
1312*e038c9c4Sjoerg if (Opts.OptimizationLevel == 0)
1313*e038c9c4Sjoerg GenerateArg(Args, OPT_O0, SA);
1314*e038c9c4Sjoerg else
1315*e038c9c4Sjoerg GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
1316*e038c9c4Sjoerg
1317*e038c9c4Sjoerg #define CODEGEN_OPTION_WITH_MARSHALLING( \
1318*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
1319*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
1320*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
1321*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
1322*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
1323*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
1324*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
1325*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
1326*e038c9c4Sjoerg #undef CODEGEN_OPTION_WITH_MARSHALLING
1327*e038c9c4Sjoerg
1328*e038c9c4Sjoerg if (Opts.OptimizationLevel > 0) {
1329*e038c9c4Sjoerg if (Opts.Inlining == CodeGenOptions::NormalInlining)
1330*e038c9c4Sjoerg GenerateArg(Args, OPT_finline_functions, SA);
1331*e038c9c4Sjoerg else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1332*e038c9c4Sjoerg GenerateArg(Args, OPT_finline_hint_functions, SA);
1333*e038c9c4Sjoerg else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1334*e038c9c4Sjoerg GenerateArg(Args, OPT_fno_inline, SA);
1335*e038c9c4Sjoerg }
1336*e038c9c4Sjoerg
1337*e038c9c4Sjoerg if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1338*e038c9c4Sjoerg GenerateArg(Args, OPT_fdirect_access_external_data, SA);
1339*e038c9c4Sjoerg else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1340*e038c9c4Sjoerg GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
1341*e038c9c4Sjoerg
1342*e038c9c4Sjoerg Optional<StringRef> DebugInfoVal;
1343*e038c9c4Sjoerg switch (Opts.DebugInfo) {
1344*e038c9c4Sjoerg case codegenoptions::DebugLineTablesOnly:
1345*e038c9c4Sjoerg DebugInfoVal = "line-tables-only";
1346*e038c9c4Sjoerg break;
1347*e038c9c4Sjoerg case codegenoptions::DebugDirectivesOnly:
1348*e038c9c4Sjoerg DebugInfoVal = "line-directives-only";
1349*e038c9c4Sjoerg break;
1350*e038c9c4Sjoerg case codegenoptions::DebugInfoConstructor:
1351*e038c9c4Sjoerg DebugInfoVal = "constructor";
1352*e038c9c4Sjoerg break;
1353*e038c9c4Sjoerg case codegenoptions::LimitedDebugInfo:
1354*e038c9c4Sjoerg DebugInfoVal = "limited";
1355*e038c9c4Sjoerg break;
1356*e038c9c4Sjoerg case codegenoptions::FullDebugInfo:
1357*e038c9c4Sjoerg DebugInfoVal = "standalone";
1358*e038c9c4Sjoerg break;
1359*e038c9c4Sjoerg case codegenoptions::UnusedTypeInfo:
1360*e038c9c4Sjoerg DebugInfoVal = "unused-types";
1361*e038c9c4Sjoerg break;
1362*e038c9c4Sjoerg case codegenoptions::NoDebugInfo: // default value
1363*e038c9c4Sjoerg DebugInfoVal = None;
1364*e038c9c4Sjoerg break;
1365*e038c9c4Sjoerg case codegenoptions::LocTrackingOnly: // implied value
1366*e038c9c4Sjoerg DebugInfoVal = None;
1367*e038c9c4Sjoerg break;
1368*e038c9c4Sjoerg }
1369*e038c9c4Sjoerg if (DebugInfoVal)
1370*e038c9c4Sjoerg GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
1371*e038c9c4Sjoerg
1372*e038c9c4Sjoerg if (Opts.DebugInfo == codegenoptions::DebugInfoConstructor)
1373*e038c9c4Sjoerg GenerateArg(Args, OPT_fuse_ctor_homing, SA);
1374*e038c9c4Sjoerg
1375*e038c9c4Sjoerg for (const auto &Prefix : Opts.DebugPrefixMap)
1376*e038c9c4Sjoerg GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
1377*e038c9c4Sjoerg Prefix.first + "=" + Prefix.second, SA);
1378*e038c9c4Sjoerg
1379*e038c9c4Sjoerg for (const auto &Prefix : Opts.CoveragePrefixMap)
1380*e038c9c4Sjoerg GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
1381*e038c9c4Sjoerg Prefix.first + "=" + Prefix.second, SA);
1382*e038c9c4Sjoerg
1383*e038c9c4Sjoerg if (Opts.NewStructPathTBAA)
1384*e038c9c4Sjoerg GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
1385*e038c9c4Sjoerg
1386*e038c9c4Sjoerg if (Opts.OptimizeSize == 1)
1387*e038c9c4Sjoerg GenerateArg(Args, OPT_O, "s", SA);
1388*e038c9c4Sjoerg else if (Opts.OptimizeSize == 2)
1389*e038c9c4Sjoerg GenerateArg(Args, OPT_O, "z", SA);
1390*e038c9c4Sjoerg
1391*e038c9c4Sjoerg // SimplifyLibCalls is set only in the absence of -fno-builtin and
1392*e038c9c4Sjoerg // -ffreestanding. We'll consider that when generating them.
1393*e038c9c4Sjoerg
1394*e038c9c4Sjoerg // NoBuiltinFuncs are generated by LangOptions.
1395*e038c9c4Sjoerg
1396*e038c9c4Sjoerg if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1397*e038c9c4Sjoerg GenerateArg(Args, OPT_funroll_loops, SA);
1398*e038c9c4Sjoerg else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1399*e038c9c4Sjoerg GenerateArg(Args, OPT_fno_unroll_loops, SA);
1400*e038c9c4Sjoerg
1401*e038c9c4Sjoerg if (!Opts.BinutilsVersion.empty())
1402*e038c9c4Sjoerg GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
1403*e038c9c4Sjoerg
1404*e038c9c4Sjoerg if (Opts.DebugNameTable ==
1405*e038c9c4Sjoerg static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1406*e038c9c4Sjoerg GenerateArg(Args, OPT_ggnu_pubnames, SA);
1407*e038c9c4Sjoerg else if (Opts.DebugNameTable ==
1408*e038c9c4Sjoerg static_cast<unsigned>(
1409*e038c9c4Sjoerg llvm::DICompileUnit::DebugNameTableKind::Default))
1410*e038c9c4Sjoerg GenerateArg(Args, OPT_gpubnames, SA);
1411*e038c9c4Sjoerg
1412*e038c9c4Sjoerg // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1413*e038c9c4Sjoerg // it or PGOUseInstrumentor.
1414*e038c9c4Sjoerg
1415*e038c9c4Sjoerg if (Opts.TimePasses) {
1416*e038c9c4Sjoerg if (Opts.TimePassesPerRun)
1417*e038c9c4Sjoerg GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
1418*e038c9c4Sjoerg else
1419*e038c9c4Sjoerg GenerateArg(Args, OPT_ftime_report, SA);
1420*e038c9c4Sjoerg }
1421*e038c9c4Sjoerg
1422*e038c9c4Sjoerg if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1423*e038c9c4Sjoerg GenerateArg(Args, OPT_flto, SA);
1424*e038c9c4Sjoerg
1425*e038c9c4Sjoerg if (Opts.PrepareForThinLTO)
1426*e038c9c4Sjoerg GenerateArg(Args, OPT_flto_EQ, "thin", SA);
1427*e038c9c4Sjoerg
1428*e038c9c4Sjoerg if (!Opts.ThinLTOIndexFile.empty())
1429*e038c9c4Sjoerg GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
1430*e038c9c4Sjoerg
1431*e038c9c4Sjoerg if (Opts.SaveTempsFilePrefix == OutputFile)
1432*e038c9c4Sjoerg GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
1433*e038c9c4Sjoerg
1434*e038c9c4Sjoerg StringRef MemProfileBasename("memprof.profraw");
1435*e038c9c4Sjoerg if (!Opts.MemoryProfileOutput.empty()) {
1436*e038c9c4Sjoerg if (Opts.MemoryProfileOutput == MemProfileBasename) {
1437*e038c9c4Sjoerg GenerateArg(Args, OPT_fmemory_profile, SA);
1438*e038c9c4Sjoerg } else {
1439*e038c9c4Sjoerg size_t ArgLength =
1440*e038c9c4Sjoerg Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1441*e038c9c4Sjoerg GenerateArg(Args, OPT_fmemory_profile_EQ,
1442*e038c9c4Sjoerg Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
1443*e038c9c4Sjoerg }
1444*e038c9c4Sjoerg }
1445*e038c9c4Sjoerg
1446*e038c9c4Sjoerg if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1447*e038c9c4Sjoerg GenerateArg(Args, OPT_coverage_version_EQ,
1448*e038c9c4Sjoerg StringRef(Opts.CoverageVersion, 4), SA);
1449*e038c9c4Sjoerg
1450*e038c9c4Sjoerg // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1451*e038c9c4Sjoerg // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1452*e038c9c4Sjoerg // won't be generated.)
1453*e038c9c4Sjoerg
1454*e038c9c4Sjoerg if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1455*e038c9c4Sjoerg std::string InstrBundle =
1456*e038c9c4Sjoerg serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
1457*e038c9c4Sjoerg if (!InstrBundle.empty())
1458*e038c9c4Sjoerg GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
1459*e038c9c4Sjoerg }
1460*e038c9c4Sjoerg
1461*e038c9c4Sjoerg if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1462*e038c9c4Sjoerg GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
1463*e038c9c4Sjoerg else if (Opts.CFProtectionReturn)
1464*e038c9c4Sjoerg GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
1465*e038c9c4Sjoerg else if (Opts.CFProtectionBranch)
1466*e038c9c4Sjoerg GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
1467*e038c9c4Sjoerg
1468*e038c9c4Sjoerg for (const auto &F : Opts.LinkBitcodeFiles) {
1469*e038c9c4Sjoerg bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1470*e038c9c4Sjoerg F.PropagateAttrs && F.Internalize;
1471*e038c9c4Sjoerg GenerateArg(Args,
1472*e038c9c4Sjoerg Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1473*e038c9c4Sjoerg F.Filename, SA);
1474*e038c9c4Sjoerg }
1475*e038c9c4Sjoerg
1476*e038c9c4Sjoerg // TODO: Consider removing marshalling annotations from f[no_]emulated_tls.
1477*e038c9c4Sjoerg // That would make it easy to generate the option only **once** if it was
1478*e038c9c4Sjoerg // explicitly set to non-default value.
1479*e038c9c4Sjoerg if (Opts.ExplicitEmulatedTLS) {
1480*e038c9c4Sjoerg GenerateArg(
1481*e038c9c4Sjoerg Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA);
1482*e038c9c4Sjoerg }
1483*e038c9c4Sjoerg
1484*e038c9c4Sjoerg if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1485*e038c9c4Sjoerg GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
1486*e038c9c4Sjoerg
1487*e038c9c4Sjoerg if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())
1488*e038c9c4Sjoerg GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
1489*e038c9c4Sjoerg SA);
1490*e038c9c4Sjoerg
1491*e038c9c4Sjoerg if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1492*e038c9c4Sjoerg OptSpecifier Opt =
1493*e038c9c4Sjoerg T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1494*e038c9c4Sjoerg GenerateArg(Args, Opt, SA);
1495*e038c9c4Sjoerg } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1496*e038c9c4Sjoerg OptSpecifier Opt =
1497*e038c9c4Sjoerg T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1498*e038c9c4Sjoerg GenerateArg(Args, Opt, SA);
1499*e038c9c4Sjoerg }
1500*e038c9c4Sjoerg
1501*e038c9c4Sjoerg if (Opts.EnableAIXExtendedAltivecABI)
1502*e038c9c4Sjoerg GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
1503*e038c9c4Sjoerg
1504*e038c9c4Sjoerg if (!Opts.OptRecordPasses.empty())
1505*e038c9c4Sjoerg GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
1506*e038c9c4Sjoerg
1507*e038c9c4Sjoerg if (!Opts.OptRecordFormat.empty())
1508*e038c9c4Sjoerg GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
1509*e038c9c4Sjoerg
1510*e038c9c4Sjoerg GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
1511*e038c9c4Sjoerg Opts.OptimizationRemark);
1512*e038c9c4Sjoerg
1513*e038c9c4Sjoerg GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
1514*e038c9c4Sjoerg Opts.OptimizationRemarkMissed);
1515*e038c9c4Sjoerg
1516*e038c9c4Sjoerg GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
1517*e038c9c4Sjoerg Opts.OptimizationRemarkAnalysis);
1518*e038c9c4Sjoerg
1519*e038c9c4Sjoerg GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
1520*e038c9c4Sjoerg Opts.DiagnosticsHotnessThreshold
1521*e038c9c4Sjoerg ? Twine(*Opts.DiagnosticsHotnessThreshold)
1522*e038c9c4Sjoerg : "auto",
1523*e038c9c4Sjoerg SA);
1524*e038c9c4Sjoerg
1525*e038c9c4Sjoerg for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1526*e038c9c4Sjoerg GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
1527*e038c9c4Sjoerg
1528*e038c9c4Sjoerg for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1529*e038c9c4Sjoerg GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
1530*e038c9c4Sjoerg
1531*e038c9c4Sjoerg if (!Opts.EmitVersionIdentMetadata)
1532*e038c9c4Sjoerg GenerateArg(Args, OPT_Qn, SA);
1533*e038c9c4Sjoerg
1534*e038c9c4Sjoerg switch (Opts.FiniteLoops) {
1535*e038c9c4Sjoerg case CodeGenOptions::FiniteLoopsKind::Language:
1536*e038c9c4Sjoerg break;
1537*e038c9c4Sjoerg case CodeGenOptions::FiniteLoopsKind::Always:
1538*e038c9c4Sjoerg GenerateArg(Args, OPT_ffinite_loops, SA);
1539*e038c9c4Sjoerg break;
1540*e038c9c4Sjoerg case CodeGenOptions::FiniteLoopsKind::Never:
1541*e038c9c4Sjoerg GenerateArg(Args, OPT_fno_finite_loops, SA);
1542*e038c9c4Sjoerg break;
1543*e038c9c4Sjoerg }
1544*e038c9c4Sjoerg }
1545*e038c9c4Sjoerg
ParseCodeGenArgs(CodeGenOptions & Opts,ArgList & Args,InputKind IK,DiagnosticsEngine & Diags,const llvm::Triple & T,const std::string & OutputFile,const LangOptions & LangOptsRef)1546*e038c9c4Sjoerg bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1547*e038c9c4Sjoerg InputKind IK,
15487330f729Sjoerg DiagnosticsEngine &Diags,
1549*e038c9c4Sjoerg const llvm::Triple &T,
1550*e038c9c4Sjoerg const std::string &OutputFile,
1551*e038c9c4Sjoerg const LangOptions &LangOptsRef) {
1552*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
15537330f729Sjoerg
15547330f729Sjoerg unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
15557330f729Sjoerg // TODO: This could be done in Driver
15567330f729Sjoerg unsigned MaxOptLevel = 3;
15577330f729Sjoerg if (OptimizationLevel > MaxOptLevel) {
15587330f729Sjoerg // If the optimization level is not supported, fall back on the default
15597330f729Sjoerg // optimization
15607330f729Sjoerg Diags.Report(diag::warn_drv_optimization_value)
15617330f729Sjoerg << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
15627330f729Sjoerg OptimizationLevel = MaxOptLevel;
15637330f729Sjoerg }
15647330f729Sjoerg Opts.OptimizationLevel = OptimizationLevel;
15657330f729Sjoerg
1566*e038c9c4Sjoerg // The key paths of codegen options defined in Options.td start with
1567*e038c9c4Sjoerg // "CodeGenOpts.". Let's provide the expected variable name and type.
1568*e038c9c4Sjoerg CodeGenOptions &CodeGenOpts = Opts;
1569*e038c9c4Sjoerg // Some codegen options depend on language options. Let's provide the expected
1570*e038c9c4Sjoerg // variable name and type.
1571*e038c9c4Sjoerg const LangOptions *LangOpts = &LangOptsRef;
1572*e038c9c4Sjoerg
1573*e038c9c4Sjoerg #define CODEGEN_OPTION_WITH_MARSHALLING( \
1574*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
1575*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
1576*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
1577*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
1578*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
1579*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
1580*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
1581*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
1582*e038c9c4Sjoerg #undef CODEGEN_OPTION_WITH_MARSHALLING
1583*e038c9c4Sjoerg
15847330f729Sjoerg // At O0 we want to fully disable inlining outside of cases marked with
15857330f729Sjoerg // 'alwaysinline' that are required for correctness.
15867330f729Sjoerg Opts.setInlining((Opts.OptimizationLevel == 0)
15877330f729Sjoerg ? CodeGenOptions::OnlyAlwaysInlining
15887330f729Sjoerg : CodeGenOptions::NormalInlining);
15897330f729Sjoerg // Explicit inlining flags can disable some or all inlining even at
15907330f729Sjoerg // optimization levels above zero.
15917330f729Sjoerg if (Arg *InlineArg = Args.getLastArg(
15927330f729Sjoerg options::OPT_finline_functions, options::OPT_finline_hint_functions,
15937330f729Sjoerg options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
15947330f729Sjoerg if (Opts.OptimizationLevel > 0) {
15957330f729Sjoerg const Option &InlineOpt = InlineArg->getOption();
15967330f729Sjoerg if (InlineOpt.matches(options::OPT_finline_functions))
15977330f729Sjoerg Opts.setInlining(CodeGenOptions::NormalInlining);
15987330f729Sjoerg else if (InlineOpt.matches(options::OPT_finline_hint_functions))
15997330f729Sjoerg Opts.setInlining(CodeGenOptions::OnlyHintInlining);
16007330f729Sjoerg else
16017330f729Sjoerg Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
16027330f729Sjoerg }
16037330f729Sjoerg }
16047330f729Sjoerg
1605*e038c9c4Sjoerg // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1606*e038c9c4Sjoerg // -fdirect-access-external-data.
1607*e038c9c4Sjoerg Opts.DirectAccessExternalData =
1608*e038c9c4Sjoerg Args.hasArg(OPT_fdirect_access_external_data) ||
1609*e038c9c4Sjoerg (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1610*e038c9c4Sjoerg LangOpts->PICLevel == 0);
16117330f729Sjoerg
16127330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
16137330f729Sjoerg unsigned Val =
16147330f729Sjoerg llvm::StringSwitch<unsigned>(A->getValue())
16157330f729Sjoerg .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
16167330f729Sjoerg .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
1617*e038c9c4Sjoerg .Case("constructor", codegenoptions::DebugInfoConstructor)
16187330f729Sjoerg .Case("limited", codegenoptions::LimitedDebugInfo)
16197330f729Sjoerg .Case("standalone", codegenoptions::FullDebugInfo)
1620*e038c9c4Sjoerg .Case("unused-types", codegenoptions::UnusedTypeInfo)
16217330f729Sjoerg .Default(~0U);
16227330f729Sjoerg if (Val == ~0U)
16237330f729Sjoerg Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
16247330f729Sjoerg << A->getValue();
16257330f729Sjoerg else
16267330f729Sjoerg Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
16277330f729Sjoerg }
1628*e038c9c4Sjoerg
1629*e038c9c4Sjoerg // If -fuse-ctor-homing is set and limited debug info is already on, then use
1630*e038c9c4Sjoerg // constructor homing.
1631*e038c9c4Sjoerg if (Args.getLastArg(OPT_fuse_ctor_homing))
1632*e038c9c4Sjoerg if (Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
1633*e038c9c4Sjoerg Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
1634*e038c9c4Sjoerg
1635*e038c9c4Sjoerg for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1636*e038c9c4Sjoerg auto Split = StringRef(Arg).split('=');
1637*e038c9c4Sjoerg Opts.DebugPrefixMap.insert(
1638*e038c9c4Sjoerg {std::string(Split.first), std::string(Split.second)});
16397330f729Sjoerg }
16407330f729Sjoerg
1641*e038c9c4Sjoerg for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1642*e038c9c4Sjoerg auto Split = StringRef(Arg).split('=');
1643*e038c9c4Sjoerg Opts.CoveragePrefixMap.insert(
1644*e038c9c4Sjoerg {std::string(Split.first), std::string(Split.second)});
1645*e038c9c4Sjoerg }
16467330f729Sjoerg
16477330f729Sjoerg const llvm::Triple::ArchType DebugEntryValueArchs[] = {
16487330f729Sjoerg llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1649*e038c9c4Sjoerg llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1650*e038c9c4Sjoerg llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
16517330f729Sjoerg
1652*e038c9c4Sjoerg if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
16537330f729Sjoerg llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1654*e038c9c4Sjoerg Opts.EmitCallSiteInfo = true;
16557330f729Sjoerg
1656*e038c9c4Sjoerg if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1657*e038c9c4Sjoerg Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1658*e038c9c4Sjoerg << Opts.DIBugsReportFilePath;
1659*e038c9c4Sjoerg Opts.DIBugsReportFilePath = "";
1660*e038c9c4Sjoerg }
1661*e038c9c4Sjoerg
16627330f729Sjoerg Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
16637330f729Sjoerg Args.hasArg(OPT_new_struct_path_tbaa);
16647330f729Sjoerg Opts.OptimizeSize = getOptimizationLevelSize(Args);
1665*e038c9c4Sjoerg Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
16667330f729Sjoerg if (Opts.SimplifyLibCalls)
1667*e038c9c4Sjoerg Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
16687330f729Sjoerg Opts.UnrollLoops =
16697330f729Sjoerg Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
16707330f729Sjoerg (Opts.OptimizationLevel > 1));
1671*e038c9c4Sjoerg Opts.BinutilsVersion =
1672*e038c9c4Sjoerg std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
16737330f729Sjoerg
16747330f729Sjoerg Opts.DebugNameTable = static_cast<unsigned>(
16757330f729Sjoerg Args.hasArg(OPT_ggnu_pubnames)
16767330f729Sjoerg ? llvm::DICompileUnit::DebugNameTableKind::GNU
16777330f729Sjoerg : Args.hasArg(OPT_gpubnames)
16787330f729Sjoerg ? llvm::DICompileUnit::DebugNameTableKind::Default
16797330f729Sjoerg : llvm::DICompileUnit::DebugNameTableKind::None);
16807330f729Sjoerg
16817330f729Sjoerg if (!Opts.ProfileInstrumentUsePath.empty())
16827330f729Sjoerg setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
1683*e038c9c4Sjoerg
1684*e038c9c4Sjoerg if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1685*e038c9c4Sjoerg Opts.TimePasses = true;
1686*e038c9c4Sjoerg
1687*e038c9c4Sjoerg // -ftime-report= is only for new pass manager.
1688*e038c9c4Sjoerg if (A->getOption().getID() == OPT_ftime_report_EQ) {
1689*e038c9c4Sjoerg if (Opts.LegacyPassManager)
16907330f729Sjoerg Diags.Report(diag::err_drv_argument_only_allowed_with)
1691*e038c9c4Sjoerg << A->getAsString(Args) << "-fno-legacy-pass-manager";
16927330f729Sjoerg
1693*e038c9c4Sjoerg StringRef Val = A->getValue();
1694*e038c9c4Sjoerg if (Val == "per-pass")
1695*e038c9c4Sjoerg Opts.TimePassesPerRun = false;
1696*e038c9c4Sjoerg else if (Val == "per-pass-run")
1697*e038c9c4Sjoerg Opts.TimePassesPerRun = true;
1698*e038c9c4Sjoerg else
16997330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
1700*e038c9c4Sjoerg << A->getAsString(Args) << A->getValue();
1701*e038c9c4Sjoerg }
1702*e038c9c4Sjoerg }
17037330f729Sjoerg
17047330f729Sjoerg Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
17057330f729Sjoerg Opts.PrepareForThinLTO = false;
17067330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
17077330f729Sjoerg StringRef S = A->getValue();
17087330f729Sjoerg if (S == "thin")
17097330f729Sjoerg Opts.PrepareForThinLTO = true;
17107330f729Sjoerg else if (S != "full")
17117330f729Sjoerg Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
17127330f729Sjoerg }
17137330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
17147330f729Sjoerg if (IK.getLanguage() != Language::LLVM_IR)
17157330f729Sjoerg Diags.Report(diag::err_drv_argument_only_allowed_with)
17167330f729Sjoerg << A->getAsString(Args) << "-x ir";
1717*e038c9c4Sjoerg Opts.ThinLTOIndexFile =
1718*e038c9c4Sjoerg std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
17197330f729Sjoerg }
17207330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
17217330f729Sjoerg Opts.SaveTempsFilePrefix =
17227330f729Sjoerg llvm::StringSwitch<std::string>(A->getValue())
1723*e038c9c4Sjoerg .Case("obj", OutputFile)
1724*e038c9c4Sjoerg .Default(llvm::sys::path::filename(OutputFile).str());
17257330f729Sjoerg
1726*e038c9c4Sjoerg // The memory profile runtime appends the pid to make this name more unique.
1727*e038c9c4Sjoerg const char *MemProfileBasename = "memprof.profraw";
1728*e038c9c4Sjoerg if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1729*e038c9c4Sjoerg SmallString<128> Path(
1730*e038c9c4Sjoerg std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1731*e038c9c4Sjoerg llvm::sys::path::append(Path, MemProfileBasename);
1732*e038c9c4Sjoerg Opts.MemoryProfileOutput = std::string(Path);
1733*e038c9c4Sjoerg } else if (Args.hasArg(OPT_fmemory_profile))
1734*e038c9c4Sjoerg Opts.MemoryProfileOutput = MemProfileBasename;
17357330f729Sjoerg
1736*e038c9c4Sjoerg memcpy(Opts.CoverageVersion, "408*", 4);
17377330f729Sjoerg if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
17387330f729Sjoerg if (Args.hasArg(OPT_coverage_version_EQ)) {
17397330f729Sjoerg StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
17407330f729Sjoerg if (CoverageVersion.size() != 4) {
17417330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
17427330f729Sjoerg << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
17437330f729Sjoerg << CoverageVersion;
17447330f729Sjoerg } else {
17457330f729Sjoerg memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
17467330f729Sjoerg }
17477330f729Sjoerg }
17487330f729Sjoerg }
17497330f729Sjoerg // FIXME: For backend options that are not yet recorded as function
17507330f729Sjoerg // attributes in the IR, keep track of them so we can embed them in a
17517330f729Sjoerg // separate data section and use them when building the bitcode.
17527330f729Sjoerg for (const auto &A : Args) {
17537330f729Sjoerg // Do not encode output and input.
17547330f729Sjoerg if (A->getOption().getID() == options::OPT_o ||
17557330f729Sjoerg A->getOption().getID() == options::OPT_INPUT ||
17567330f729Sjoerg A->getOption().getID() == options::OPT_x ||
17577330f729Sjoerg A->getOption().getID() == options::OPT_fembed_bitcode ||
1758*e038c9c4Sjoerg A->getOption().matches(options::OPT_W_Group))
17597330f729Sjoerg continue;
17607330f729Sjoerg ArgStringList ASL;
17617330f729Sjoerg A->render(Args, ASL);
17627330f729Sjoerg for (const auto &arg : ASL) {
17637330f729Sjoerg StringRef ArgStr(arg);
17647330f729Sjoerg Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
17657330f729Sjoerg // using \00 to separate each commandline options.
17667330f729Sjoerg Opts.CmdArgs.push_back('\0');
17677330f729Sjoerg }
17687330f729Sjoerg }
17697330f729Sjoerg
17707330f729Sjoerg auto XRayInstrBundles =
17717330f729Sjoerg Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
17727330f729Sjoerg if (XRayInstrBundles.empty())
17737330f729Sjoerg Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
17747330f729Sjoerg else
17757330f729Sjoerg for (const auto &A : XRayInstrBundles)
17767330f729Sjoerg parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
17777330f729Sjoerg Diags, Opts.XRayInstrumentationBundle);
17787330f729Sjoerg
17797330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
17807330f729Sjoerg StringRef Name = A->getValue();
17817330f729Sjoerg if (Name == "full") {
17827330f729Sjoerg Opts.CFProtectionReturn = 1;
17837330f729Sjoerg Opts.CFProtectionBranch = 1;
17847330f729Sjoerg } else if (Name == "return")
17857330f729Sjoerg Opts.CFProtectionReturn = 1;
17867330f729Sjoerg else if (Name == "branch")
17877330f729Sjoerg Opts.CFProtectionBranch = 1;
1788*e038c9c4Sjoerg else if (Name != "none")
17897330f729Sjoerg Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
17907330f729Sjoerg }
17917330f729Sjoerg
17927330f729Sjoerg for (auto *A :
17937330f729Sjoerg Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
17947330f729Sjoerg CodeGenOptions::BitcodeFileToLink F;
17957330f729Sjoerg F.Filename = A->getValue();
17967330f729Sjoerg if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
17977330f729Sjoerg F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
17987330f729Sjoerg // When linking CUDA bitcode, propagate function attributes so that
17997330f729Sjoerg // e.g. libdevice gets fast-math attrs if we're building with fast-math.
18007330f729Sjoerg F.PropagateAttrs = true;
18017330f729Sjoerg F.Internalize = true;
18027330f729Sjoerg }
18037330f729Sjoerg Opts.LinkBitcodeFiles.push_back(F);
18047330f729Sjoerg }
18057330f729Sjoerg
18067330f729Sjoerg if (Args.getLastArg(OPT_femulated_tls) ||
18077330f729Sjoerg Args.getLastArg(OPT_fno_emulated_tls)) {
18087330f729Sjoerg Opts.ExplicitEmulatedTLS = true;
18097330f729Sjoerg }
18107330f729Sjoerg
18117330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1812*e038c9c4Sjoerg if (T.isOSAIX()) {
18137330f729Sjoerg StringRef Name = A->getValue();
1814*e038c9c4Sjoerg if (Name != "global-dynamic")
1815*e038c9c4Sjoerg Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
18167330f729Sjoerg }
18177330f729Sjoerg }
18187330f729Sjoerg
18197330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
18207330f729Sjoerg StringRef Val = A->getValue();
1821*e038c9c4Sjoerg Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1822*e038c9c4Sjoerg if (!Opts.FPDenormalMode.isValid())
18237330f729Sjoerg Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
18247330f729Sjoerg }
18257330f729Sjoerg
1826*e038c9c4Sjoerg if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1827*e038c9c4Sjoerg StringRef Val = A->getValue();
1828*e038c9c4Sjoerg Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1829*e038c9c4Sjoerg if (!Opts.FP32DenormalMode.isValid())
1830*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1831*e038c9c4Sjoerg }
1832*e038c9c4Sjoerg
1833*e038c9c4Sjoerg // X86_32 has -fppc-struct-return and -freg-struct-return.
1834*e038c9c4Sjoerg // PPC32 has -maix-struct-return and -msvr4-struct-return.
1835*e038c9c4Sjoerg if (Arg *A =
1836*e038c9c4Sjoerg Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1837*e038c9c4Sjoerg OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1838*e038c9c4Sjoerg // TODO: We might want to consider enabling these options on AIX in the
1839*e038c9c4Sjoerg // future.
1840*e038c9c4Sjoerg if (T.isOSAIX())
1841*e038c9c4Sjoerg Diags.Report(diag::err_drv_unsupported_opt_for_target)
1842*e038c9c4Sjoerg << A->getSpelling() << T.str();
1843*e038c9c4Sjoerg
1844*e038c9c4Sjoerg const Option &O = A->getOption();
1845*e038c9c4Sjoerg if (O.matches(OPT_fpcc_struct_return) ||
1846*e038c9c4Sjoerg O.matches(OPT_maix_struct_return)) {
18477330f729Sjoerg Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
18487330f729Sjoerg } else {
1849*e038c9c4Sjoerg assert(O.matches(OPT_freg_struct_return) ||
1850*e038c9c4Sjoerg O.matches(OPT_msvr4_struct_return));
18517330f729Sjoerg Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
18527330f729Sjoerg }
18537330f729Sjoerg }
18547330f729Sjoerg
1855*e038c9c4Sjoerg if (Arg *A =
1856*e038c9c4Sjoerg Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
1857*e038c9c4Sjoerg if (!T.isOSAIX())
1858*e038c9c4Sjoerg Diags.Report(diag::err_drv_unsupported_opt_for_target)
1859*e038c9c4Sjoerg << A->getSpelling() << T.str();
1860*e038c9c4Sjoerg
1861*e038c9c4Sjoerg const Option &O = A->getOption();
1862*e038c9c4Sjoerg if (O.matches(OPT_mabi_EQ_vec_default))
1863*e038c9c4Sjoerg Diags.Report(diag::err_aix_default_altivec_abi)
1864*e038c9c4Sjoerg << A->getSpelling() << T.str();
1865*e038c9c4Sjoerg else {
1866*e038c9c4Sjoerg assert(O.matches(OPT_mabi_EQ_vec_extabi));
1867*e038c9c4Sjoerg Opts.EnableAIXExtendedAltivecABI = 1;
1868*e038c9c4Sjoerg }
1869*e038c9c4Sjoerg }
1870*e038c9c4Sjoerg
18717330f729Sjoerg bool NeedLocTracking = false;
18727330f729Sjoerg
18737330f729Sjoerg if (!Opts.OptRecordFile.empty())
18747330f729Sjoerg NeedLocTracking = true;
18757330f729Sjoerg
18767330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
18777330f729Sjoerg Opts.OptRecordPasses = A->getValue();
18787330f729Sjoerg NeedLocTracking = true;
18797330f729Sjoerg }
18807330f729Sjoerg
18817330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
18827330f729Sjoerg Opts.OptRecordFormat = A->getValue();
18837330f729Sjoerg NeedLocTracking = true;
18847330f729Sjoerg }
18857330f729Sjoerg
1886*e038c9c4Sjoerg Opts.OptimizationRemark =
1887*e038c9c4Sjoerg ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
18887330f729Sjoerg
1889*e038c9c4Sjoerg Opts.OptimizationRemarkMissed =
1890*e038c9c4Sjoerg ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
18917330f729Sjoerg
1892*e038c9c4Sjoerg Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
1893*e038c9c4Sjoerg Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
18947330f729Sjoerg
1895*e038c9c4Sjoerg NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
1896*e038c9c4Sjoerg Opts.OptimizationRemarkMissed.hasValidPattern() ||
1897*e038c9c4Sjoerg Opts.OptimizationRemarkAnalysis.hasValidPattern();
1898*e038c9c4Sjoerg
18997330f729Sjoerg bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
19007330f729Sjoerg bool UsingProfile = UsingSampleProfile ||
19017330f729Sjoerg (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
19027330f729Sjoerg
19037330f729Sjoerg if (Opts.DiagnosticsWithHotness && !UsingProfile &&
19047330f729Sjoerg // An IR file will contain PGO as metadata
19057330f729Sjoerg IK.getLanguage() != Language::LLVM_IR)
19067330f729Sjoerg Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
19077330f729Sjoerg << "-fdiagnostics-show-hotness";
19087330f729Sjoerg
1909*e038c9c4Sjoerg // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1910*e038c9c4Sjoerg if (auto *arg =
1911*e038c9c4Sjoerg Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1912*e038c9c4Sjoerg auto ResultOrErr =
1913*e038c9c4Sjoerg llvm::remarks::parseHotnessThresholdOption(arg->getValue());
1914*e038c9c4Sjoerg
1915*e038c9c4Sjoerg if (!ResultOrErr) {
1916*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
1917*e038c9c4Sjoerg << "-fdiagnostics-hotness-threshold=";
1918*e038c9c4Sjoerg } else {
1919*e038c9c4Sjoerg Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
1920*e038c9c4Sjoerg if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
1921*e038c9c4Sjoerg Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
1922*e038c9c4Sjoerg !UsingProfile)
19237330f729Sjoerg Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
19247330f729Sjoerg << "-fdiagnostics-hotness-threshold=";
1925*e038c9c4Sjoerg }
1926*e038c9c4Sjoerg }
19277330f729Sjoerg
19287330f729Sjoerg // If the user requested to use a sample profile for PGO, then the
19297330f729Sjoerg // backend will need to track source location information so the profile
19307330f729Sjoerg // can be incorporated into the IR.
19317330f729Sjoerg if (UsingSampleProfile)
19327330f729Sjoerg NeedLocTracking = true;
19337330f729Sjoerg
1934*e038c9c4Sjoerg if (!Opts.StackUsageOutput.empty())
1935*e038c9c4Sjoerg NeedLocTracking = true;
1936*e038c9c4Sjoerg
19377330f729Sjoerg // If the user requested a flag that requires source locations available in
19387330f729Sjoerg // the backend, make sure that the backend tracks source location information.
19397330f729Sjoerg if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
19407330f729Sjoerg Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
19417330f729Sjoerg
19427330f729Sjoerg // Parse -fsanitize-recover= arguments.
19437330f729Sjoerg // FIXME: Report unrecoverable sanitizers incorrectly specified here.
19447330f729Sjoerg parseSanitizerKinds("-fsanitize-recover=",
19457330f729Sjoerg Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
19467330f729Sjoerg Opts.SanitizeRecover);
19477330f729Sjoerg parseSanitizerKinds("-fsanitize-trap=",
19487330f729Sjoerg Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
19497330f729Sjoerg Opts.SanitizeTrap);
19507330f729Sjoerg
19517330f729Sjoerg Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
19527330f729Sjoerg
1953*e038c9c4Sjoerg if (Args.hasArg(options::OPT_ffinite_loops))
1954*e038c9c4Sjoerg Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
1955*e038c9c4Sjoerg else if (Args.hasArg(options::OPT_fno_finite_loops))
1956*e038c9c4Sjoerg Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
19577330f729Sjoerg
1958*e038c9c4Sjoerg Opts.EmitIEEENaNCompliantInsts =
1959*e038c9c4Sjoerg Args.hasFlag(options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee);
1960*e038c9c4Sjoerg if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
1961*e038c9c4Sjoerg Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
19627330f729Sjoerg
1963*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
1964*e038c9c4Sjoerg }
19657330f729Sjoerg
1966*e038c9c4Sjoerg static void
GenerateDependencyOutputArgs(const DependencyOutputOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)1967*e038c9c4Sjoerg GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
1968*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
1969*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
1970*e038c9c4Sjoerg const DependencyOutputOptions &DependencyOutputOpts = Opts;
1971*e038c9c4Sjoerg #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
1972*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
1973*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
1974*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
1975*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
1976*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
1977*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
1978*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
1979*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
1980*e038c9c4Sjoerg #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
1981*e038c9c4Sjoerg
1982*e038c9c4Sjoerg if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
1983*e038c9c4Sjoerg GenerateArg(Args, OPT_show_includes, SA);
1984*e038c9c4Sjoerg
1985*e038c9c4Sjoerg for (const auto &Dep : Opts.ExtraDeps) {
1986*e038c9c4Sjoerg switch (Dep.second) {
1987*e038c9c4Sjoerg case EDK_SanitizeIgnorelist:
1988*e038c9c4Sjoerg // Sanitizer ignorelist arguments are generated from LanguageOptions.
1989*e038c9c4Sjoerg continue;
1990*e038c9c4Sjoerg case EDK_ModuleFile:
1991*e038c9c4Sjoerg // Module file arguments are generated from FrontendOptions and
1992*e038c9c4Sjoerg // HeaderSearchOptions.
1993*e038c9c4Sjoerg continue;
1994*e038c9c4Sjoerg case EDK_ProfileList:
1995*e038c9c4Sjoerg // Profile list arguments are generated from LanguageOptions via the
1996*e038c9c4Sjoerg // marshalling infrastructure.
1997*e038c9c4Sjoerg continue;
1998*e038c9c4Sjoerg case EDK_DepFileEntry:
1999*e038c9c4Sjoerg GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
2000*e038c9c4Sjoerg break;
20017330f729Sjoerg }
20027330f729Sjoerg }
20037330f729Sjoerg }
20047330f729Sjoerg
ParseDependencyOutputArgs(DependencyOutputOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action,bool ShowLineMarkers)2005*e038c9c4Sjoerg static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
2006*e038c9c4Sjoerg ArgList &Args, DiagnosticsEngine &Diags,
2007*e038c9c4Sjoerg frontend::ActionKind Action,
2008*e038c9c4Sjoerg bool ShowLineMarkers) {
2009*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
20107330f729Sjoerg
2011*e038c9c4Sjoerg DependencyOutputOptions &DependencyOutputOpts = Opts;
2012*e038c9c4Sjoerg #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
2013*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2014*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2015*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2016*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2017*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
2018*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2019*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2020*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2021*e038c9c4Sjoerg #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
20227330f729Sjoerg
20237330f729Sjoerg if (Args.hasArg(OPT_show_includes)) {
20247330f729Sjoerg // Writing both /showIncludes and preprocessor output to stdout
20257330f729Sjoerg // would produce interleaved output, so use stderr for /showIncludes.
20267330f729Sjoerg // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2027*e038c9c4Sjoerg if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
20287330f729Sjoerg Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
20297330f729Sjoerg else
20307330f729Sjoerg Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
20317330f729Sjoerg } else {
20327330f729Sjoerg Opts.ShowIncludesDest = ShowIncludesDestination::None;
20337330f729Sjoerg }
2034*e038c9c4Sjoerg
2035*e038c9c4Sjoerg // Add sanitizer ignorelists as extra dependencies.
20367330f729Sjoerg // They won't be discovered by the regular preprocessor, so
20377330f729Sjoerg // we let make / ninja to know about this implicit dependency.
2038*e038c9c4Sjoerg if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2039*e038c9c4Sjoerg for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2040*e038c9c4Sjoerg StringRef Val = A->getValue();
2041*e038c9c4Sjoerg if (Val.find('=') == StringRef::npos)
2042*e038c9c4Sjoerg Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2043*e038c9c4Sjoerg }
2044*e038c9c4Sjoerg if (Opts.IncludeSystemHeaders) {
2045*e038c9c4Sjoerg for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2046*e038c9c4Sjoerg StringRef Val = A->getValue();
2047*e038c9c4Sjoerg if (Val.find('=') == StringRef::npos)
2048*e038c9c4Sjoerg Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2049*e038c9c4Sjoerg }
2050*e038c9c4Sjoerg }
2051*e038c9c4Sjoerg }
2052*e038c9c4Sjoerg
2053*e038c9c4Sjoerg // -fprofile-list= dependencies.
2054*e038c9c4Sjoerg for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2055*e038c9c4Sjoerg Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2056*e038c9c4Sjoerg
2057*e038c9c4Sjoerg // Propagate the extra dependencies.
2058*e038c9c4Sjoerg for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2059*e038c9c4Sjoerg Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2060*e038c9c4Sjoerg
20617330f729Sjoerg // Only the -fmodule-file=<file> form.
20627330f729Sjoerg for (const auto *A : Args.filtered(OPT_fmodule_file)) {
20637330f729Sjoerg StringRef Val = A->getValue();
20647330f729Sjoerg if (Val.find('=') == StringRef::npos)
2065*e038c9c4Sjoerg Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
20667330f729Sjoerg }
2067*e038c9c4Sjoerg
2068*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
20697330f729Sjoerg }
20707330f729Sjoerg
parseShowColorsArgs(const ArgList & Args,bool DefaultColor)20717330f729Sjoerg static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
20727330f729Sjoerg // Color diagnostics default to auto ("on" if terminal supports) in the driver
20737330f729Sjoerg // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
20747330f729Sjoerg // Support both clang's -f[no-]color-diagnostics and gcc's
20757330f729Sjoerg // -f[no-]diagnostics-colors[=never|always|auto].
20767330f729Sjoerg enum {
20777330f729Sjoerg Colors_On,
20787330f729Sjoerg Colors_Off,
20797330f729Sjoerg Colors_Auto
20807330f729Sjoerg } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
20817330f729Sjoerg for (auto *A : Args) {
20827330f729Sjoerg const Option &O = A->getOption();
20837330f729Sjoerg if (O.matches(options::OPT_fcolor_diagnostics) ||
20847330f729Sjoerg O.matches(options::OPT_fdiagnostics_color)) {
20857330f729Sjoerg ShowColors = Colors_On;
20867330f729Sjoerg } else if (O.matches(options::OPT_fno_color_diagnostics) ||
20877330f729Sjoerg O.matches(options::OPT_fno_diagnostics_color)) {
20887330f729Sjoerg ShowColors = Colors_Off;
20897330f729Sjoerg } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
20907330f729Sjoerg StringRef Value(A->getValue());
20917330f729Sjoerg if (Value == "always")
20927330f729Sjoerg ShowColors = Colors_On;
20937330f729Sjoerg else if (Value == "never")
20947330f729Sjoerg ShowColors = Colors_Off;
20957330f729Sjoerg else if (Value == "auto")
20967330f729Sjoerg ShowColors = Colors_Auto;
20977330f729Sjoerg }
20987330f729Sjoerg }
20997330f729Sjoerg return ShowColors == Colors_On ||
21007330f729Sjoerg (ShowColors == Colors_Auto &&
21017330f729Sjoerg llvm::sys::Process::StandardErrHasColors());
21027330f729Sjoerg }
21037330f729Sjoerg
checkVerifyPrefixes(const std::vector<std::string> & VerifyPrefixes,DiagnosticsEngine & Diags)21047330f729Sjoerg static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2105*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
21067330f729Sjoerg bool Success = true;
21077330f729Sjoerg for (const auto &Prefix : VerifyPrefixes) {
21087330f729Sjoerg // Every prefix must start with a letter and contain only alphanumeric
21097330f729Sjoerg // characters, hyphens, and underscores.
21107330f729Sjoerg auto BadChar = llvm::find_if(Prefix, [](char C) {
21117330f729Sjoerg return !isAlphanumeric(C) && C != '-' && C != '_';
21127330f729Sjoerg });
21137330f729Sjoerg if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
21147330f729Sjoerg Success = false;
2115*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2116*e038c9c4Sjoerg Diags.Report(diag::note_drv_verify_prefix_spelling);
21177330f729Sjoerg }
21187330f729Sjoerg }
21197330f729Sjoerg return Success;
21207330f729Sjoerg }
21217330f729Sjoerg
GenerateFileSystemArgs(const FileSystemOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)2122*e038c9c4Sjoerg static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2123*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
2124*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
2125*e038c9c4Sjoerg const FileSystemOptions &FileSystemOpts = Opts;
2126*e038c9c4Sjoerg
2127*e038c9c4Sjoerg #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
2128*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2129*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2130*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2131*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2132*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
2133*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2134*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2135*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2136*e038c9c4Sjoerg #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2137*e038c9c4Sjoerg }
2138*e038c9c4Sjoerg
ParseFileSystemArgs(FileSystemOptions & Opts,const ArgList & Args,DiagnosticsEngine & Diags)2139*e038c9c4Sjoerg static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2140*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
2141*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
2142*e038c9c4Sjoerg
2143*e038c9c4Sjoerg FileSystemOptions &FileSystemOpts = Opts;
2144*e038c9c4Sjoerg
2145*e038c9c4Sjoerg #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
2146*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2147*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2148*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2149*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2150*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
2151*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2152*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2153*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2154*e038c9c4Sjoerg #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2155*e038c9c4Sjoerg
2156*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
2157*e038c9c4Sjoerg }
2158*e038c9c4Sjoerg
GenerateMigratorArgs(const MigratorOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)2159*e038c9c4Sjoerg static void GenerateMigratorArgs(const MigratorOptions &Opts,
2160*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
2161*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
2162*e038c9c4Sjoerg const MigratorOptions &MigratorOpts = Opts;
2163*e038c9c4Sjoerg #define MIGRATOR_OPTION_WITH_MARSHALLING( \
2164*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2165*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2166*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2167*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2168*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
2169*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2170*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2171*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2172*e038c9c4Sjoerg #undef MIGRATOR_OPTION_WITH_MARSHALLING
2173*e038c9c4Sjoerg }
2174*e038c9c4Sjoerg
ParseMigratorArgs(MigratorOptions & Opts,const ArgList & Args,DiagnosticsEngine & Diags)2175*e038c9c4Sjoerg static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2176*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
2177*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
2178*e038c9c4Sjoerg
2179*e038c9c4Sjoerg MigratorOptions &MigratorOpts = Opts;
2180*e038c9c4Sjoerg
2181*e038c9c4Sjoerg #define MIGRATOR_OPTION_WITH_MARSHALLING( \
2182*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2183*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2184*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2185*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2186*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
2187*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2188*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2189*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2190*e038c9c4Sjoerg #undef MIGRATOR_OPTION_WITH_MARSHALLING
2191*e038c9c4Sjoerg
2192*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
2193*e038c9c4Sjoerg }
2194*e038c9c4Sjoerg
GenerateDiagnosticArgs(const DiagnosticOptions & Opts,SmallVectorImpl<const char * > & Args,StringAllocator SA,bool DefaultDiagColor)2195*e038c9c4Sjoerg void CompilerInvocation::GenerateDiagnosticArgs(
2196*e038c9c4Sjoerg const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args,
2197*e038c9c4Sjoerg StringAllocator SA, bool DefaultDiagColor) {
2198*e038c9c4Sjoerg const DiagnosticOptions *DiagnosticOpts = &Opts;
2199*e038c9c4Sjoerg #define DIAG_OPTION_WITH_MARSHALLING( \
2200*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2201*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2202*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2203*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2204*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
2205*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2206*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2207*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2208*e038c9c4Sjoerg #undef DIAG_OPTION_WITH_MARSHALLING
2209*e038c9c4Sjoerg
2210*e038c9c4Sjoerg if (!Opts.DiagnosticSerializationFile.empty())
2211*e038c9c4Sjoerg GenerateArg(Args, OPT_diagnostic_serialized_file,
2212*e038c9c4Sjoerg Opts.DiagnosticSerializationFile, SA);
2213*e038c9c4Sjoerg
2214*e038c9c4Sjoerg if (Opts.ShowColors)
2215*e038c9c4Sjoerg GenerateArg(Args, OPT_fcolor_diagnostics, SA);
2216*e038c9c4Sjoerg
2217*e038c9c4Sjoerg if (Opts.VerifyDiagnostics &&
2218*e038c9c4Sjoerg llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2219*e038c9c4Sjoerg GenerateArg(Args, OPT_verify, SA);
2220*e038c9c4Sjoerg
2221*e038c9c4Sjoerg for (const auto &Prefix : Opts.VerifyPrefixes)
2222*e038c9c4Sjoerg if (Prefix != "expected")
2223*e038c9c4Sjoerg GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
2224*e038c9c4Sjoerg
2225*e038c9c4Sjoerg DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2226*e038c9c4Sjoerg if (VIU == DiagnosticLevelMask::None) {
2227*e038c9c4Sjoerg // This is the default, don't generate anything.
2228*e038c9c4Sjoerg } else if (VIU == DiagnosticLevelMask::All) {
2229*e038c9c4Sjoerg GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
2230*e038c9c4Sjoerg } else {
2231*e038c9c4Sjoerg if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2232*e038c9c4Sjoerg GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
2233*e038c9c4Sjoerg if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2234*e038c9c4Sjoerg GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
2235*e038c9c4Sjoerg if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2236*e038c9c4Sjoerg GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
2237*e038c9c4Sjoerg if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2238*e038c9c4Sjoerg GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
2239*e038c9c4Sjoerg }
2240*e038c9c4Sjoerg
2241*e038c9c4Sjoerg for (const auto &Warning : Opts.Warnings) {
2242*e038c9c4Sjoerg // This option is automatically generated from UndefPrefixes.
2243*e038c9c4Sjoerg if (Warning == "undef-prefix")
2244*e038c9c4Sjoerg continue;
2245*e038c9c4Sjoerg Args.push_back(SA(StringRef("-W") + Warning));
2246*e038c9c4Sjoerg }
2247*e038c9c4Sjoerg
2248*e038c9c4Sjoerg for (const auto &Remark : Opts.Remarks) {
2249*e038c9c4Sjoerg // These arguments are generated from OptimizationRemark fields of
2250*e038c9c4Sjoerg // CodeGenOptions.
2251*e038c9c4Sjoerg StringRef IgnoredRemarks[] = {"pass", "no-pass",
2252*e038c9c4Sjoerg "pass-analysis", "no-pass-analysis",
2253*e038c9c4Sjoerg "pass-missed", "no-pass-missed"};
2254*e038c9c4Sjoerg if (llvm::is_contained(IgnoredRemarks, Remark))
2255*e038c9c4Sjoerg continue;
2256*e038c9c4Sjoerg
2257*e038c9c4Sjoerg Args.push_back(SA(StringRef("-R") + Remark));
2258*e038c9c4Sjoerg }
2259*e038c9c4Sjoerg }
2260*e038c9c4Sjoerg
ParseDiagnosticArgs(DiagnosticOptions & Opts,ArgList & Args,DiagnosticsEngine * Diags,bool DefaultDiagColor)22617330f729Sjoerg bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
22627330f729Sjoerg DiagnosticsEngine *Diags,
2263*e038c9c4Sjoerg bool DefaultDiagColor) {
2264*e038c9c4Sjoerg Optional<DiagnosticsEngine> IgnoringDiags;
2265*e038c9c4Sjoerg if (!Diags) {
2266*e038c9c4Sjoerg IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2267*e038c9c4Sjoerg new IgnoringDiagConsumer());
2268*e038c9c4Sjoerg Diags = &*IgnoringDiags;
2269*e038c9c4Sjoerg }
22707330f729Sjoerg
2271*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags->getNumErrors();
2272*e038c9c4Sjoerg
2273*e038c9c4Sjoerg // The key paths of diagnostic options defined in Options.td start with
2274*e038c9c4Sjoerg // "DiagnosticOpts->". Let's provide the expected variable name and type.
2275*e038c9c4Sjoerg DiagnosticOptions *DiagnosticOpts = &Opts;
2276*e038c9c4Sjoerg
2277*e038c9c4Sjoerg #define DIAG_OPTION_WITH_MARSHALLING( \
2278*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2279*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2280*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2281*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2282*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
2283*e038c9c4Sjoerg Args, *Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2284*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2285*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2286*e038c9c4Sjoerg #undef DIAG_OPTION_WITH_MARSHALLING
2287*e038c9c4Sjoerg
2288*e038c9c4Sjoerg llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2289*e038c9c4Sjoerg
22907330f729Sjoerg if (Arg *A =
22917330f729Sjoerg Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
22927330f729Sjoerg Opts.DiagnosticSerializationFile = A->getValue();
22937330f729Sjoerg Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
22947330f729Sjoerg
22957330f729Sjoerg Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
22967330f729Sjoerg Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
22977330f729Sjoerg if (Args.hasArg(OPT_verify))
22987330f729Sjoerg Opts.VerifyPrefixes.push_back("expected");
22997330f729Sjoerg // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
23007330f729Sjoerg // then sort it to prepare for fast lookup using std::binary_search.
2301*e038c9c4Sjoerg if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
23027330f729Sjoerg Opts.VerifyDiagnostics = false;
23037330f729Sjoerg else
23047330f729Sjoerg llvm::sort(Opts.VerifyPrefixes);
23057330f729Sjoerg DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2306*e038c9c4Sjoerg parseDiagnosticLevelMask(
2307*e038c9c4Sjoerg "-verify-ignore-unexpected=",
2308*e038c9c4Sjoerg Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
23097330f729Sjoerg if (Args.hasArg(OPT_verify_ignore_unexpected))
23107330f729Sjoerg DiagMask = DiagnosticLevelMask::All;
23117330f729Sjoerg Opts.setVerifyIgnoreUnexpected(DiagMask);
23127330f729Sjoerg if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
23137330f729Sjoerg Opts.TabStop = DiagnosticOptions::DefaultTabStop;
23147330f729Sjoerg Diags->Report(diag::warn_ignoring_ftabstop_value)
23157330f729Sjoerg << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
23167330f729Sjoerg }
2317*e038c9c4Sjoerg
23187330f729Sjoerg addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
23197330f729Sjoerg addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
23207330f729Sjoerg
2321*e038c9c4Sjoerg return Diags->getNumErrors() == NumErrorsBefore;
23227330f729Sjoerg }
23237330f729Sjoerg
23247330f729Sjoerg /// Parse the argument to the -ftest-module-file-extension
23257330f729Sjoerg /// command-line argument.
23267330f729Sjoerg ///
23277330f729Sjoerg /// \returns true on error, false on success.
parseTestModuleFileExtensionArg(StringRef Arg,std::string & BlockName,unsigned & MajorVersion,unsigned & MinorVersion,bool & Hashed,std::string & UserInfo)23287330f729Sjoerg static bool parseTestModuleFileExtensionArg(StringRef Arg,
23297330f729Sjoerg std::string &BlockName,
23307330f729Sjoerg unsigned &MajorVersion,
23317330f729Sjoerg unsigned &MinorVersion,
23327330f729Sjoerg bool &Hashed,
23337330f729Sjoerg std::string &UserInfo) {
23347330f729Sjoerg SmallVector<StringRef, 5> Args;
23357330f729Sjoerg Arg.split(Args, ':', 5);
23367330f729Sjoerg if (Args.size() < 5)
23377330f729Sjoerg return true;
23387330f729Sjoerg
2339*e038c9c4Sjoerg BlockName = std::string(Args[0]);
23407330f729Sjoerg if (Args[1].getAsInteger(10, MajorVersion)) return true;
23417330f729Sjoerg if (Args[2].getAsInteger(10, MinorVersion)) return true;
23427330f729Sjoerg if (Args[3].getAsInteger(2, Hashed)) return true;
23437330f729Sjoerg if (Args.size() > 4)
2344*e038c9c4Sjoerg UserInfo = std::string(Args[4]);
23457330f729Sjoerg return false;
23467330f729Sjoerg }
23477330f729Sjoerg
2348*e038c9c4Sjoerg /// Return a table that associates command line option specifiers with the
2349*e038c9c4Sjoerg /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2350*e038c9c4Sjoerg /// intentionally missing, as this case is handled separately from other
2351*e038c9c4Sjoerg /// frontend options.
getFrontendActionTable()2352*e038c9c4Sjoerg static const auto &getFrontendActionTable() {
2353*e038c9c4Sjoerg static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2354*e038c9c4Sjoerg {frontend::ASTDeclList, OPT_ast_list},
2355*e038c9c4Sjoerg
2356*e038c9c4Sjoerg {frontend::ASTDump, OPT_ast_dump_all_EQ},
2357*e038c9c4Sjoerg {frontend::ASTDump, OPT_ast_dump_all},
2358*e038c9c4Sjoerg {frontend::ASTDump, OPT_ast_dump_EQ},
2359*e038c9c4Sjoerg {frontend::ASTDump, OPT_ast_dump},
2360*e038c9c4Sjoerg {frontend::ASTDump, OPT_ast_dump_lookups},
2361*e038c9c4Sjoerg {frontend::ASTDump, OPT_ast_dump_decl_types},
2362*e038c9c4Sjoerg
2363*e038c9c4Sjoerg {frontend::ASTPrint, OPT_ast_print},
2364*e038c9c4Sjoerg {frontend::ASTView, OPT_ast_view},
2365*e038c9c4Sjoerg {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2366*e038c9c4Sjoerg {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2367*e038c9c4Sjoerg {frontend::DumpTokens, OPT_dump_tokens},
2368*e038c9c4Sjoerg {frontend::EmitAssembly, OPT_S},
2369*e038c9c4Sjoerg {frontend::EmitBC, OPT_emit_llvm_bc},
2370*e038c9c4Sjoerg {frontend::EmitHTML, OPT_emit_html},
2371*e038c9c4Sjoerg {frontend::EmitLLVM, OPT_emit_llvm},
2372*e038c9c4Sjoerg {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2373*e038c9c4Sjoerg {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2374*e038c9c4Sjoerg {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2375*e038c9c4Sjoerg {frontend::EmitObj, OPT_emit_obj},
2376*e038c9c4Sjoerg
2377*e038c9c4Sjoerg {frontend::FixIt, OPT_fixit_EQ},
2378*e038c9c4Sjoerg {frontend::FixIt, OPT_fixit},
2379*e038c9c4Sjoerg
2380*e038c9c4Sjoerg {frontend::GenerateModule, OPT_emit_module},
2381*e038c9c4Sjoerg {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2382*e038c9c4Sjoerg {frontend::GenerateHeaderModule, OPT_emit_header_module},
2383*e038c9c4Sjoerg {frontend::GeneratePCH, OPT_emit_pch},
2384*e038c9c4Sjoerg {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2385*e038c9c4Sjoerg {frontend::InitOnly, OPT_init_only},
2386*e038c9c4Sjoerg {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2387*e038c9c4Sjoerg {frontend::ModuleFileInfo, OPT_module_file_info},
2388*e038c9c4Sjoerg {frontend::VerifyPCH, OPT_verify_pch},
2389*e038c9c4Sjoerg {frontend::PrintPreamble, OPT_print_preamble},
2390*e038c9c4Sjoerg {frontend::PrintPreprocessedInput, OPT_E},
2391*e038c9c4Sjoerg {frontend::TemplightDump, OPT_templight_dump},
2392*e038c9c4Sjoerg {frontend::RewriteMacros, OPT_rewrite_macros},
2393*e038c9c4Sjoerg {frontend::RewriteObjC, OPT_rewrite_objc},
2394*e038c9c4Sjoerg {frontend::RewriteTest, OPT_rewrite_test},
2395*e038c9c4Sjoerg {frontend::RunAnalysis, OPT_analyze},
2396*e038c9c4Sjoerg {frontend::MigrateSource, OPT_migrate},
2397*e038c9c4Sjoerg {frontend::RunPreprocessorOnly, OPT_Eonly},
2398*e038c9c4Sjoerg {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2399*e038c9c4Sjoerg OPT_print_dependency_directives_minimized_source},
2400*e038c9c4Sjoerg };
2401*e038c9c4Sjoerg
2402*e038c9c4Sjoerg return Table;
2403*e038c9c4Sjoerg }
2404*e038c9c4Sjoerg
2405*e038c9c4Sjoerg /// Maps command line option to frontend action.
getFrontendAction(OptSpecifier & Opt)2406*e038c9c4Sjoerg static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) {
2407*e038c9c4Sjoerg for (const auto &ActionOpt : getFrontendActionTable())
2408*e038c9c4Sjoerg if (ActionOpt.second == Opt.getID())
2409*e038c9c4Sjoerg return ActionOpt.first;
2410*e038c9c4Sjoerg
2411*e038c9c4Sjoerg return None;
2412*e038c9c4Sjoerg }
2413*e038c9c4Sjoerg
2414*e038c9c4Sjoerg /// Maps frontend action to command line option.
2415*e038c9c4Sjoerg static Optional<OptSpecifier>
getProgramActionOpt(frontend::ActionKind ProgramAction)2416*e038c9c4Sjoerg getProgramActionOpt(frontend::ActionKind ProgramAction) {
2417*e038c9c4Sjoerg for (const auto &ActionOpt : getFrontendActionTable())
2418*e038c9c4Sjoerg if (ActionOpt.first == ProgramAction)
2419*e038c9c4Sjoerg return OptSpecifier(ActionOpt.second);
2420*e038c9c4Sjoerg
2421*e038c9c4Sjoerg return None;
2422*e038c9c4Sjoerg }
2423*e038c9c4Sjoerg
GenerateFrontendArgs(const FrontendOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,bool IsHeader)2424*e038c9c4Sjoerg static void GenerateFrontendArgs(const FrontendOptions &Opts,
2425*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
2426*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
2427*e038c9c4Sjoerg bool IsHeader) {
2428*e038c9c4Sjoerg const FrontendOptions &FrontendOpts = Opts;
2429*e038c9c4Sjoerg #define FRONTEND_OPTION_WITH_MARSHALLING( \
2430*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2431*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2432*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2433*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2434*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
2435*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2436*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2437*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2438*e038c9c4Sjoerg #undef FRONTEND_OPTION_WITH_MARSHALLING
2439*e038c9c4Sjoerg
2440*e038c9c4Sjoerg Optional<OptSpecifier> ProgramActionOpt =
2441*e038c9c4Sjoerg getProgramActionOpt(Opts.ProgramAction);
2442*e038c9c4Sjoerg
2443*e038c9c4Sjoerg // Generating a simple flag covers most frontend actions.
2444*e038c9c4Sjoerg std::function<void()> GenerateProgramAction = [&]() {
2445*e038c9c4Sjoerg GenerateArg(Args, *ProgramActionOpt, SA);
2446*e038c9c4Sjoerg };
2447*e038c9c4Sjoerg
2448*e038c9c4Sjoerg if (!ProgramActionOpt) {
2449*e038c9c4Sjoerg // PluginAction is the only program action handled separately.
2450*e038c9c4Sjoerg assert(Opts.ProgramAction == frontend::PluginAction &&
2451*e038c9c4Sjoerg "Frontend action without option.");
2452*e038c9c4Sjoerg GenerateProgramAction = [&]() {
2453*e038c9c4Sjoerg GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
2454*e038c9c4Sjoerg };
2455*e038c9c4Sjoerg }
2456*e038c9c4Sjoerg
2457*e038c9c4Sjoerg // FIXME: Simplify the complex 'AST dump' command line.
2458*e038c9c4Sjoerg if (Opts.ProgramAction == frontend::ASTDump) {
2459*e038c9c4Sjoerg GenerateProgramAction = [&]() {
2460*e038c9c4Sjoerg // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2461*e038c9c4Sjoerg // marshalling infrastructure.
2462*e038c9c4Sjoerg
2463*e038c9c4Sjoerg if (Opts.ASTDumpFormat != ADOF_Default) {
2464*e038c9c4Sjoerg StringRef Format;
2465*e038c9c4Sjoerg switch (Opts.ASTDumpFormat) {
2466*e038c9c4Sjoerg case ADOF_Default:
2467*e038c9c4Sjoerg llvm_unreachable("Default AST dump format.");
2468*e038c9c4Sjoerg case ADOF_JSON:
2469*e038c9c4Sjoerg Format = "json";
2470*e038c9c4Sjoerg break;
2471*e038c9c4Sjoerg }
2472*e038c9c4Sjoerg
2473*e038c9c4Sjoerg if (Opts.ASTDumpAll)
2474*e038c9c4Sjoerg GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
2475*e038c9c4Sjoerg if (Opts.ASTDumpDecls)
2476*e038c9c4Sjoerg GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
2477*e038c9c4Sjoerg } else {
2478*e038c9c4Sjoerg if (Opts.ASTDumpAll)
2479*e038c9c4Sjoerg GenerateArg(Args, OPT_ast_dump_all, SA);
2480*e038c9c4Sjoerg if (Opts.ASTDumpDecls)
2481*e038c9c4Sjoerg GenerateArg(Args, OPT_ast_dump, SA);
2482*e038c9c4Sjoerg }
2483*e038c9c4Sjoerg };
2484*e038c9c4Sjoerg }
2485*e038c9c4Sjoerg
2486*e038c9c4Sjoerg if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2487*e038c9c4Sjoerg GenerateProgramAction = [&]() {
2488*e038c9c4Sjoerg GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
2489*e038c9c4Sjoerg };
2490*e038c9c4Sjoerg }
2491*e038c9c4Sjoerg
2492*e038c9c4Sjoerg GenerateProgramAction();
2493*e038c9c4Sjoerg
2494*e038c9c4Sjoerg for (const auto &PluginArgs : Opts.PluginArgs) {
2495*e038c9c4Sjoerg Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2496*e038c9c4Sjoerg const char *Spelling =
2497*e038c9c4Sjoerg SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
2498*e038c9c4Sjoerg for (const auto &PluginArg : PluginArgs.second)
2499*e038c9c4Sjoerg denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
2500*e038c9c4Sjoerg }
2501*e038c9c4Sjoerg
2502*e038c9c4Sjoerg for (const auto &Ext : Opts.ModuleFileExtensions)
2503*e038c9c4Sjoerg if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2504*e038c9c4Sjoerg GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
2505*e038c9c4Sjoerg
2506*e038c9c4Sjoerg if (!Opts.CodeCompletionAt.FileName.empty())
2507*e038c9c4Sjoerg GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
2508*e038c9c4Sjoerg SA);
2509*e038c9c4Sjoerg
2510*e038c9c4Sjoerg for (const auto &Plugin : Opts.Plugins)
2511*e038c9c4Sjoerg GenerateArg(Args, OPT_load, Plugin, SA);
2512*e038c9c4Sjoerg
2513*e038c9c4Sjoerg // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2514*e038c9c4Sjoerg
2515*e038c9c4Sjoerg for (const auto &ModuleFile : Opts.ModuleFiles)
2516*e038c9c4Sjoerg GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
2517*e038c9c4Sjoerg
2518*e038c9c4Sjoerg if (Opts.AuxTargetCPU.hasValue())
2519*e038c9c4Sjoerg GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
2520*e038c9c4Sjoerg
2521*e038c9c4Sjoerg if (Opts.AuxTargetFeatures.hasValue())
2522*e038c9c4Sjoerg for (const auto &Feature : *Opts.AuxTargetFeatures)
2523*e038c9c4Sjoerg GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
2524*e038c9c4Sjoerg
2525*e038c9c4Sjoerg {
2526*e038c9c4Sjoerg StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2527*e038c9c4Sjoerg StringRef ModuleMap =
2528*e038c9c4Sjoerg Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2529*e038c9c4Sjoerg StringRef Header = IsHeader ? "-header" : "";
2530*e038c9c4Sjoerg
2531*e038c9c4Sjoerg StringRef Lang;
2532*e038c9c4Sjoerg switch (Opts.DashX.getLanguage()) {
2533*e038c9c4Sjoerg case Language::C:
2534*e038c9c4Sjoerg Lang = "c";
2535*e038c9c4Sjoerg break;
2536*e038c9c4Sjoerg case Language::OpenCL:
2537*e038c9c4Sjoerg Lang = "cl";
2538*e038c9c4Sjoerg break;
2539*e038c9c4Sjoerg case Language::OpenCLCXX:
2540*e038c9c4Sjoerg Lang = "clcpp";
2541*e038c9c4Sjoerg break;
2542*e038c9c4Sjoerg case Language::CUDA:
2543*e038c9c4Sjoerg Lang = "cuda";
2544*e038c9c4Sjoerg break;
2545*e038c9c4Sjoerg case Language::HIP:
2546*e038c9c4Sjoerg Lang = "hip";
2547*e038c9c4Sjoerg break;
2548*e038c9c4Sjoerg case Language::CXX:
2549*e038c9c4Sjoerg Lang = "c++";
2550*e038c9c4Sjoerg break;
2551*e038c9c4Sjoerg case Language::ObjC:
2552*e038c9c4Sjoerg Lang = "objective-c";
2553*e038c9c4Sjoerg break;
2554*e038c9c4Sjoerg case Language::ObjCXX:
2555*e038c9c4Sjoerg Lang = "objective-c++";
2556*e038c9c4Sjoerg break;
2557*e038c9c4Sjoerg case Language::RenderScript:
2558*e038c9c4Sjoerg Lang = "renderscript";
2559*e038c9c4Sjoerg break;
2560*e038c9c4Sjoerg case Language::Asm:
2561*e038c9c4Sjoerg Lang = "assembler-with-cpp";
2562*e038c9c4Sjoerg break;
2563*e038c9c4Sjoerg case Language::Unknown:
2564*e038c9c4Sjoerg assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2565*e038c9c4Sjoerg "Generating -x argument for unknown language (not precompiled).");
2566*e038c9c4Sjoerg Lang = "ast";
2567*e038c9c4Sjoerg break;
2568*e038c9c4Sjoerg case Language::LLVM_IR:
2569*e038c9c4Sjoerg Lang = "ir";
2570*e038c9c4Sjoerg break;
2571*e038c9c4Sjoerg }
2572*e038c9c4Sjoerg
2573*e038c9c4Sjoerg GenerateArg(Args, OPT_x, Lang + Header + ModuleMap + Preprocessed, SA);
2574*e038c9c4Sjoerg }
2575*e038c9c4Sjoerg
2576*e038c9c4Sjoerg // OPT_INPUT has a unique class, generate it directly.
2577*e038c9c4Sjoerg for (const auto &Input : Opts.Inputs)
2578*e038c9c4Sjoerg Args.push_back(SA(Input.getFile()));
2579*e038c9c4Sjoerg }
2580*e038c9c4Sjoerg
ParseFrontendArgs(FrontendOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,bool & IsHeaderFile)2581*e038c9c4Sjoerg static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2582*e038c9c4Sjoerg DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2583*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
2584*e038c9c4Sjoerg
2585*e038c9c4Sjoerg FrontendOptions &FrontendOpts = Opts;
2586*e038c9c4Sjoerg
2587*e038c9c4Sjoerg #define FRONTEND_OPTION_WITH_MARSHALLING( \
2588*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2589*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2590*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2591*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2592*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
2593*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2594*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2595*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2596*e038c9c4Sjoerg #undef FRONTEND_OPTION_WITH_MARSHALLING
2597*e038c9c4Sjoerg
25987330f729Sjoerg Opts.ProgramAction = frontend::ParseSyntaxOnly;
25997330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2600*e038c9c4Sjoerg OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2601*e038c9c4Sjoerg Optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
2602*e038c9c4Sjoerg assert(ProgramAction && "Option specifier not in Action_Group.");
2603*e038c9c4Sjoerg
2604*e038c9c4Sjoerg if (ProgramAction == frontend::ASTDump &&
2605*e038c9c4Sjoerg (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
26067330f729Sjoerg unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
26077330f729Sjoerg .CaseLower("default", ADOF_Default)
26087330f729Sjoerg .CaseLower("json", ADOF_JSON)
26097330f729Sjoerg .Default(std::numeric_limits<unsigned>::max());
26107330f729Sjoerg
26117330f729Sjoerg if (Val != std::numeric_limits<unsigned>::max())
26127330f729Sjoerg Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
26137330f729Sjoerg else {
26147330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
26157330f729Sjoerg << A->getAsString(Args) << A->getValue();
26167330f729Sjoerg Opts.ASTDumpFormat = ADOF_Default;
26177330f729Sjoerg }
26187330f729Sjoerg }
2619*e038c9c4Sjoerg
2620*e038c9c4Sjoerg if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
26217330f729Sjoerg Opts.FixItSuffix = A->getValue();
2622*e038c9c4Sjoerg
2623*e038c9c4Sjoerg if (ProgramAction == frontend::GenerateInterfaceStubs) {
26247330f729Sjoerg StringRef ArgStr =
26257330f729Sjoerg Args.hasArg(OPT_interface_stub_version_EQ)
26267330f729Sjoerg ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2627*e038c9c4Sjoerg : "experimental-ifs-v2";
26287330f729Sjoerg if (ArgStr == "experimental-yaml-elf-v1" ||
2629*e038c9c4Sjoerg ArgStr == "experimental-ifs-v1" ||
26307330f729Sjoerg ArgStr == "experimental-tapi-elf-v1") {
26317330f729Sjoerg std::string ErrorMessage =
26327330f729Sjoerg "Invalid interface stub format: " + ArgStr.str() +
26337330f729Sjoerg " is deprecated.";
26347330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
26357330f729Sjoerg << "Must specify a valid interface stub format type, ie: "
2636*e038c9c4Sjoerg "-interface-stub-version=experimental-ifs-v2"
26377330f729Sjoerg << ErrorMessage;
2638*e038c9c4Sjoerg ProgramAction = frontend::ParseSyntaxOnly;
2639*e038c9c4Sjoerg } else if (!ArgStr.startswith("experimental-ifs-")) {
26407330f729Sjoerg std::string ErrorMessage =
26417330f729Sjoerg "Invalid interface stub format: " + ArgStr.str() + ".";
26427330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
26437330f729Sjoerg << "Must specify a valid interface stub format type, ie: "
2644*e038c9c4Sjoerg "-interface-stub-version=experimental-ifs-v2"
26457330f729Sjoerg << ErrorMessage;
2646*e038c9c4Sjoerg ProgramAction = frontend::ParseSyntaxOnly;
26477330f729Sjoerg }
26487330f729Sjoerg }
2649*e038c9c4Sjoerg
2650*e038c9c4Sjoerg Opts.ProgramAction = *ProgramAction;
26517330f729Sjoerg }
26527330f729Sjoerg
26537330f729Sjoerg if (const Arg* A = Args.getLastArg(OPT_plugin)) {
26547330f729Sjoerg Opts.Plugins.emplace_back(A->getValue(0));
26557330f729Sjoerg Opts.ProgramAction = frontend::PluginAction;
26567330f729Sjoerg Opts.ActionName = A->getValue();
26577330f729Sjoerg }
26587330f729Sjoerg for (const auto *AA : Args.filtered(OPT_plugin_arg))
26597330f729Sjoerg Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
26607330f729Sjoerg
26617330f729Sjoerg for (const std::string &Arg :
26627330f729Sjoerg Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
26637330f729Sjoerg std::string BlockName;
26647330f729Sjoerg unsigned MajorVersion;
26657330f729Sjoerg unsigned MinorVersion;
26667330f729Sjoerg bool Hashed;
26677330f729Sjoerg std::string UserInfo;
26687330f729Sjoerg if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
26697330f729Sjoerg MinorVersion, Hashed, UserInfo)) {
26707330f729Sjoerg Diags.Report(diag::err_test_module_file_extension_format) << Arg;
26717330f729Sjoerg
26727330f729Sjoerg continue;
26737330f729Sjoerg }
26747330f729Sjoerg
26757330f729Sjoerg // Add the testing module file extension.
26767330f729Sjoerg Opts.ModuleFileExtensions.push_back(
26777330f729Sjoerg std::make_shared<TestModuleFileExtension>(
26787330f729Sjoerg BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
26797330f729Sjoerg }
26807330f729Sjoerg
26817330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
26827330f729Sjoerg Opts.CodeCompletionAt =
26837330f729Sjoerg ParsedSourceLocation::FromString(A->getValue());
26847330f729Sjoerg if (Opts.CodeCompletionAt.FileName.empty())
26857330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
26867330f729Sjoerg << A->getAsString(Args) << A->getValue();
26877330f729Sjoerg }
26887330f729Sjoerg
26897330f729Sjoerg Opts.Plugins = Args.getAllArgValues(OPT_load);
26907330f729Sjoerg Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
26917330f729Sjoerg Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
26927330f729Sjoerg // Only the -fmodule-file=<file> form.
26937330f729Sjoerg for (const auto *A : Args.filtered(OPT_fmodule_file)) {
26947330f729Sjoerg StringRef Val = A->getValue();
26957330f729Sjoerg if (Val.find('=') == StringRef::npos)
2696*e038c9c4Sjoerg Opts.ModuleFiles.push_back(std::string(Val));
26977330f729Sjoerg }
26987330f729Sjoerg
2699*e038c9c4Sjoerg if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
2700*e038c9c4Sjoerg Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2701*e038c9c4Sjoerg << "-emit-module";
27027330f729Sjoerg
2703*e038c9c4Sjoerg if (Args.hasArg(OPT_aux_target_cpu))
2704*e038c9c4Sjoerg Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2705*e038c9c4Sjoerg if (Args.hasArg(OPT_aux_target_feature))
2706*e038c9c4Sjoerg Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
27077330f729Sjoerg
27087330f729Sjoerg if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
27097330f729Sjoerg Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
27107330f729Sjoerg Diags.Report(diag::err_drv_argument_not_allowed_with)
27117330f729Sjoerg << "ARC migration" << "ObjC migration";
27127330f729Sjoerg }
27137330f729Sjoerg
27147330f729Sjoerg InputKind DashX(Language::Unknown);
27157330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_x)) {
27167330f729Sjoerg StringRef XValue = A->getValue();
27177330f729Sjoerg
27187330f729Sjoerg // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
27197330f729Sjoerg // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
27207330f729Sjoerg bool Preprocessed = XValue.consume_back("-cpp-output");
27217330f729Sjoerg bool ModuleMap = XValue.consume_back("-module-map");
2722*e038c9c4Sjoerg IsHeaderFile = !Preprocessed && !ModuleMap &&
2723*e038c9c4Sjoerg XValue != "precompiled-header" &&
2724*e038c9c4Sjoerg XValue.consume_back("-header");
27257330f729Sjoerg
27267330f729Sjoerg // Principal languages.
27277330f729Sjoerg DashX = llvm::StringSwitch<InputKind>(XValue)
27287330f729Sjoerg .Case("c", Language::C)
27297330f729Sjoerg .Case("cl", Language::OpenCL)
2730*e038c9c4Sjoerg .Case("clcpp", Language::OpenCLCXX)
27317330f729Sjoerg .Case("cuda", Language::CUDA)
27327330f729Sjoerg .Case("hip", Language::HIP)
27337330f729Sjoerg .Case("c++", Language::CXX)
27347330f729Sjoerg .Case("objective-c", Language::ObjC)
27357330f729Sjoerg .Case("objective-c++", Language::ObjCXX)
27367330f729Sjoerg .Case("renderscript", Language::RenderScript)
27377330f729Sjoerg .Default(Language::Unknown);
27387330f729Sjoerg
27397330f729Sjoerg // "objc[++]-cpp-output" is an acceptable synonym for
27407330f729Sjoerg // "objective-c[++]-cpp-output".
27417330f729Sjoerg if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
27427330f729Sjoerg DashX = llvm::StringSwitch<InputKind>(XValue)
27437330f729Sjoerg .Case("objc", Language::ObjC)
27447330f729Sjoerg .Case("objc++", Language::ObjCXX)
27457330f729Sjoerg .Default(Language::Unknown);
27467330f729Sjoerg
27477330f729Sjoerg // Some special cases cannot be combined with suffixes.
27487330f729Sjoerg if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
27497330f729Sjoerg DashX = llvm::StringSwitch<InputKind>(XValue)
27507330f729Sjoerg .Case("cpp-output", InputKind(Language::C).getPreprocessed())
27517330f729Sjoerg .Case("assembler-with-cpp", Language::Asm)
2752*e038c9c4Sjoerg .Cases("ast", "pcm", "precompiled-header",
27537330f729Sjoerg InputKind(Language::Unknown, InputKind::Precompiled))
27547330f729Sjoerg .Case("ir", Language::LLVM_IR)
27557330f729Sjoerg .Default(Language::Unknown);
27567330f729Sjoerg
27577330f729Sjoerg if (DashX.isUnknown())
27587330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
27597330f729Sjoerg << A->getAsString(Args) << A->getValue();
27607330f729Sjoerg
27617330f729Sjoerg if (Preprocessed)
27627330f729Sjoerg DashX = DashX.getPreprocessed();
27637330f729Sjoerg if (ModuleMap)
27647330f729Sjoerg DashX = DashX.withFormat(InputKind::ModuleMap);
27657330f729Sjoerg }
27667330f729Sjoerg
27677330f729Sjoerg // '-' is the default input if none is given.
27687330f729Sjoerg std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
27697330f729Sjoerg Opts.Inputs.clear();
27707330f729Sjoerg if (Inputs.empty())
27717330f729Sjoerg Inputs.push_back("-");
27727330f729Sjoerg for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
27737330f729Sjoerg InputKind IK = DashX;
27747330f729Sjoerg if (IK.isUnknown()) {
27757330f729Sjoerg IK = FrontendOptions::getInputKindForExtension(
27767330f729Sjoerg StringRef(Inputs[i]).rsplit('.').second);
27777330f729Sjoerg // FIXME: Warn on this?
27787330f729Sjoerg if (IK.isUnknown())
27797330f729Sjoerg IK = Language::C;
27807330f729Sjoerg // FIXME: Remove this hack.
27817330f729Sjoerg if (i == 0)
27827330f729Sjoerg DashX = IK;
27837330f729Sjoerg }
27847330f729Sjoerg
2785*e038c9c4Sjoerg bool IsSystem = false;
2786*e038c9c4Sjoerg
27877330f729Sjoerg // The -emit-module action implicitly takes a module map.
27887330f729Sjoerg if (Opts.ProgramAction == frontend::GenerateModule &&
2789*e038c9c4Sjoerg IK.getFormat() == InputKind::Source) {
27907330f729Sjoerg IK = IK.withFormat(InputKind::ModuleMap);
2791*e038c9c4Sjoerg IsSystem = Opts.IsSystemModule;
27927330f729Sjoerg }
27937330f729Sjoerg
2794*e038c9c4Sjoerg Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
2795*e038c9c4Sjoerg }
2796*e038c9c4Sjoerg
2797*e038c9c4Sjoerg Opts.DashX = DashX;
2798*e038c9c4Sjoerg
2799*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
28007330f729Sjoerg }
28017330f729Sjoerg
GetResourcesPath(const char * Argv0,void * MainAddr)28027330f729Sjoerg std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
28037330f729Sjoerg void *MainAddr) {
28047330f729Sjoerg std::string ClangExecutable =
28057330f729Sjoerg llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
28067330f729Sjoerg return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
28077330f729Sjoerg }
28087330f729Sjoerg
GenerateHeaderSearchArgs(HeaderSearchOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)2809*e038c9c4Sjoerg static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts,
2810*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
2811*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
2812*e038c9c4Sjoerg const HeaderSearchOptions *HeaderSearchOpts = &Opts;
2813*e038c9c4Sjoerg #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
2814*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2815*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2816*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2817*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2818*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
2819*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2820*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2821*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2822*e038c9c4Sjoerg #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2823*e038c9c4Sjoerg
2824*e038c9c4Sjoerg if (Opts.UseLibcxx)
2825*e038c9c4Sjoerg GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
2826*e038c9c4Sjoerg
2827*e038c9c4Sjoerg if (!Opts.ModuleCachePath.empty())
2828*e038c9c4Sjoerg GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
2829*e038c9c4Sjoerg
2830*e038c9c4Sjoerg for (const auto &File : Opts.PrebuiltModuleFiles)
2831*e038c9c4Sjoerg GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
2832*e038c9c4Sjoerg
2833*e038c9c4Sjoerg for (const auto &Path : Opts.PrebuiltModulePaths)
2834*e038c9c4Sjoerg GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
2835*e038c9c4Sjoerg
2836*e038c9c4Sjoerg for (const auto &Macro : Opts.ModulesIgnoreMacros)
2837*e038c9c4Sjoerg GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
2838*e038c9c4Sjoerg
2839*e038c9c4Sjoerg auto Matches = [](const HeaderSearchOptions::Entry &Entry,
2840*e038c9c4Sjoerg llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
2841*e038c9c4Sjoerg llvm::Optional<bool> IsFramework,
2842*e038c9c4Sjoerg llvm::Optional<bool> IgnoreSysRoot) {
2843*e038c9c4Sjoerg return llvm::find(Groups, Entry.Group) != Groups.end() &&
2844*e038c9c4Sjoerg (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
2845*e038c9c4Sjoerg (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
2846*e038c9c4Sjoerg };
2847*e038c9c4Sjoerg
2848*e038c9c4Sjoerg auto It = Opts.UserEntries.begin();
2849*e038c9c4Sjoerg auto End = Opts.UserEntries.end();
2850*e038c9c4Sjoerg
2851*e038c9c4Sjoerg // Add -I..., -F..., and -index-header-map options in order.
2852*e038c9c4Sjoerg for (; It < End &&
2853*e038c9c4Sjoerg Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, None, true);
2854*e038c9c4Sjoerg ++It) {
2855*e038c9c4Sjoerg OptSpecifier Opt = [It, Matches]() {
2856*e038c9c4Sjoerg if (Matches(*It, frontend::IndexHeaderMap, true, true))
2857*e038c9c4Sjoerg return OPT_F;
2858*e038c9c4Sjoerg if (Matches(*It, frontend::IndexHeaderMap, false, true))
2859*e038c9c4Sjoerg return OPT_I;
2860*e038c9c4Sjoerg if (Matches(*It, frontend::Angled, true, true))
2861*e038c9c4Sjoerg return OPT_F;
2862*e038c9c4Sjoerg if (Matches(*It, frontend::Angled, false, true))
2863*e038c9c4Sjoerg return OPT_I;
2864*e038c9c4Sjoerg llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
2865*e038c9c4Sjoerg }();
2866*e038c9c4Sjoerg
2867*e038c9c4Sjoerg if (It->Group == frontend::IndexHeaderMap)
2868*e038c9c4Sjoerg GenerateArg(Args, OPT_index_header_map, SA);
2869*e038c9c4Sjoerg GenerateArg(Args, Opt, It->Path, SA);
2870*e038c9c4Sjoerg };
2871*e038c9c4Sjoerg
2872*e038c9c4Sjoerg // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
2873*e038c9c4Sjoerg // have already been generated as "-I[xx]yy". If that's the case, their
2874*e038c9c4Sjoerg // position on command line was such that this has no semantic impact on
2875*e038c9c4Sjoerg // include paths.
2876*e038c9c4Sjoerg for (; It < End &&
2877*e038c9c4Sjoerg Matches(*It, {frontend::After, frontend::Angled}, false, true);
2878*e038c9c4Sjoerg ++It) {
2879*e038c9c4Sjoerg OptSpecifier Opt =
2880*e038c9c4Sjoerg It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
2881*e038c9c4Sjoerg GenerateArg(Args, Opt, It->Path, SA);
2882*e038c9c4Sjoerg }
2883*e038c9c4Sjoerg
2884*e038c9c4Sjoerg // Note: Some paths that came from "-idirafter=xxyy" may have already been
2885*e038c9c4Sjoerg // generated as "-iwithprefix=xxyy". If that's the case, their position on
2886*e038c9c4Sjoerg // command line was such that this has no semantic impact on include paths.
2887*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
2888*e038c9c4Sjoerg GenerateArg(Args, OPT_idirafter, It->Path, SA);
2889*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
2890*e038c9c4Sjoerg GenerateArg(Args, OPT_iquote, It->Path, SA);
2891*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::System}, false, None); ++It)
2892*e038c9c4Sjoerg GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
2893*e038c9c4Sjoerg It->Path, SA);
2894*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
2895*e038c9c4Sjoerg GenerateArg(Args, OPT_iframework, It->Path, SA);
2896*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
2897*e038c9c4Sjoerg GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
2898*e038c9c4Sjoerg
2899*e038c9c4Sjoerg // Add the paths for the various language specific isystem flags.
2900*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
2901*e038c9c4Sjoerg GenerateArg(Args, OPT_c_isystem, It->Path, SA);
2902*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
2903*e038c9c4Sjoerg GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
2904*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
2905*e038c9c4Sjoerg GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
2906*e038c9c4Sjoerg for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
2907*e038c9c4Sjoerg GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
2908*e038c9c4Sjoerg
2909*e038c9c4Sjoerg // Add the internal paths from a driver that detects standard include paths.
2910*e038c9c4Sjoerg // Note: Some paths that came from "-internal-isystem" arguments may have
2911*e038c9c4Sjoerg // already been generated as "-isystem". If that's the case, their position on
2912*e038c9c4Sjoerg // command line was such that this has no semantic impact on include paths.
2913*e038c9c4Sjoerg for (; It < End &&
2914*e038c9c4Sjoerg Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
2915*e038c9c4Sjoerg ++It) {
2916*e038c9c4Sjoerg OptSpecifier Opt = It->Group == frontend::System
2917*e038c9c4Sjoerg ? OPT_internal_isystem
2918*e038c9c4Sjoerg : OPT_internal_externc_isystem;
2919*e038c9c4Sjoerg GenerateArg(Args, Opt, It->Path, SA);
2920*e038c9c4Sjoerg }
2921*e038c9c4Sjoerg
2922*e038c9c4Sjoerg assert(It == End && "Unhandled HeaderSearchOption::Entry.");
2923*e038c9c4Sjoerg
2924*e038c9c4Sjoerg // Add the path prefixes which are implicitly treated as being system headers.
2925*e038c9c4Sjoerg for (const auto &P : Opts.SystemHeaderPrefixes) {
2926*e038c9c4Sjoerg OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
2927*e038c9c4Sjoerg : OPT_no_system_header_prefix;
2928*e038c9c4Sjoerg GenerateArg(Args, Opt, P.Prefix, SA);
2929*e038c9c4Sjoerg }
2930*e038c9c4Sjoerg
2931*e038c9c4Sjoerg for (const std::string &F : Opts.VFSOverlayFiles)
2932*e038c9c4Sjoerg GenerateArg(Args, OPT_ivfsoverlay, F, SA);
2933*e038c9c4Sjoerg }
2934*e038c9c4Sjoerg
ParseHeaderSearchArgs(HeaderSearchOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,const std::string & WorkingDir)2935*e038c9c4Sjoerg static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
2936*e038c9c4Sjoerg DiagnosticsEngine &Diags,
29377330f729Sjoerg const std::string &WorkingDir) {
2938*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
2939*e038c9c4Sjoerg
2940*e038c9c4Sjoerg HeaderSearchOptions *HeaderSearchOpts = &Opts;
2941*e038c9c4Sjoerg
2942*e038c9c4Sjoerg #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
2943*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2944*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2945*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2946*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
2947*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
2948*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2949*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2950*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
2951*e038c9c4Sjoerg #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2952*e038c9c4Sjoerg
29537330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
29547330f729Sjoerg Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
29557330f729Sjoerg
29567330f729Sjoerg // Canonicalize -fmodules-cache-path before storing it.
29577330f729Sjoerg SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
29587330f729Sjoerg if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
29597330f729Sjoerg if (WorkingDir.empty())
29607330f729Sjoerg llvm::sys::fs::make_absolute(P);
29617330f729Sjoerg else
29627330f729Sjoerg llvm::sys::fs::make_absolute(WorkingDir, P);
29637330f729Sjoerg }
29647330f729Sjoerg llvm::sys::path::remove_dots(P);
2965*e038c9c4Sjoerg Opts.ModuleCachePath = std::string(P.str());
29667330f729Sjoerg
29677330f729Sjoerg // Only the -fmodule-file=<name>=<file> form.
29687330f729Sjoerg for (const auto *A : Args.filtered(OPT_fmodule_file)) {
29697330f729Sjoerg StringRef Val = A->getValue();
2970*e038c9c4Sjoerg if (Val.find('=') != StringRef::npos){
2971*e038c9c4Sjoerg auto Split = Val.split('=');
2972*e038c9c4Sjoerg Opts.PrebuiltModuleFiles.insert(
2973*e038c9c4Sjoerg {std::string(Split.first), std::string(Split.second)});
2974*e038c9c4Sjoerg }
29757330f729Sjoerg }
29767330f729Sjoerg for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
29777330f729Sjoerg Opts.AddPrebuiltModulePath(A->getValue());
29787330f729Sjoerg
29797330f729Sjoerg for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
29807330f729Sjoerg StringRef MacroDef = A->getValue();
29817330f729Sjoerg Opts.ModulesIgnoreMacros.insert(
29827330f729Sjoerg llvm::CachedHashString(MacroDef.split('=').first));
29837330f729Sjoerg }
29847330f729Sjoerg
29857330f729Sjoerg // Add -I..., -F..., and -index-header-map options in order.
29867330f729Sjoerg bool IsIndexHeaderMap = false;
29877330f729Sjoerg bool IsSysrootSpecified =
29887330f729Sjoerg Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
29897330f729Sjoerg for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
29907330f729Sjoerg if (A->getOption().matches(OPT_index_header_map)) {
29917330f729Sjoerg // -index-header-map applies to the next -I or -F.
29927330f729Sjoerg IsIndexHeaderMap = true;
29937330f729Sjoerg continue;
29947330f729Sjoerg }
29957330f729Sjoerg
29967330f729Sjoerg frontend::IncludeDirGroup Group =
29977330f729Sjoerg IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
29987330f729Sjoerg
29997330f729Sjoerg bool IsFramework = A->getOption().matches(OPT_F);
30007330f729Sjoerg std::string Path = A->getValue();
30017330f729Sjoerg
30027330f729Sjoerg if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
30037330f729Sjoerg SmallString<32> Buffer;
30047330f729Sjoerg llvm::sys::path::append(Buffer, Opts.Sysroot,
30057330f729Sjoerg llvm::StringRef(A->getValue()).substr(1));
3006*e038c9c4Sjoerg Path = std::string(Buffer.str());
30077330f729Sjoerg }
30087330f729Sjoerg
30097330f729Sjoerg Opts.AddPath(Path, Group, IsFramework,
30107330f729Sjoerg /*IgnoreSysroot*/ true);
30117330f729Sjoerg IsIndexHeaderMap = false;
30127330f729Sjoerg }
30137330f729Sjoerg
30147330f729Sjoerg // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
30157330f729Sjoerg StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
30167330f729Sjoerg for (const auto *A :
30177330f729Sjoerg Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
30187330f729Sjoerg if (A->getOption().matches(OPT_iprefix))
30197330f729Sjoerg Prefix = A->getValue();
30207330f729Sjoerg else if (A->getOption().matches(OPT_iwithprefix))
30217330f729Sjoerg Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
30227330f729Sjoerg else
30237330f729Sjoerg Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
30247330f729Sjoerg }
30257330f729Sjoerg
30267330f729Sjoerg for (const auto *A : Args.filtered(OPT_idirafter))
30277330f729Sjoerg Opts.AddPath(A->getValue(), frontend::After, false, true);
30287330f729Sjoerg for (const auto *A : Args.filtered(OPT_iquote))
30297330f729Sjoerg Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
30307330f729Sjoerg for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
30317330f729Sjoerg Opts.AddPath(A->getValue(), frontend::System, false,
30327330f729Sjoerg !A->getOption().matches(OPT_iwithsysroot));
30337330f729Sjoerg for (const auto *A : Args.filtered(OPT_iframework))
30347330f729Sjoerg Opts.AddPath(A->getValue(), frontend::System, true, true);
30357330f729Sjoerg for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
30367330f729Sjoerg Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
30377330f729Sjoerg /*IgnoreSysRoot=*/false);
30387330f729Sjoerg
30397330f729Sjoerg // Add the paths for the various language specific isystem flags.
30407330f729Sjoerg for (const auto *A : Args.filtered(OPT_c_isystem))
30417330f729Sjoerg Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
30427330f729Sjoerg for (const auto *A : Args.filtered(OPT_cxx_isystem))
30437330f729Sjoerg Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
30447330f729Sjoerg for (const auto *A : Args.filtered(OPT_objc_isystem))
30457330f729Sjoerg Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
30467330f729Sjoerg for (const auto *A : Args.filtered(OPT_objcxx_isystem))
30477330f729Sjoerg Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
30487330f729Sjoerg
30497330f729Sjoerg // Add the internal paths from a driver that detects standard include paths.
30507330f729Sjoerg for (const auto *A :
30517330f729Sjoerg Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
30527330f729Sjoerg frontend::IncludeDirGroup Group = frontend::System;
30537330f729Sjoerg if (A->getOption().matches(OPT_internal_externc_isystem))
30547330f729Sjoerg Group = frontend::ExternCSystem;
30557330f729Sjoerg Opts.AddPath(A->getValue(), Group, false, true);
30567330f729Sjoerg }
30577330f729Sjoerg
30587330f729Sjoerg // Add the path prefixes which are implicitly treated as being system headers.
30597330f729Sjoerg for (const auto *A :
30607330f729Sjoerg Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
30617330f729Sjoerg Opts.AddSystemHeaderPrefix(
30627330f729Sjoerg A->getValue(), A->getOption().matches(OPT_system_header_prefix));
30637330f729Sjoerg
30647330f729Sjoerg for (const auto *A : Args.filtered(OPT_ivfsoverlay))
30657330f729Sjoerg Opts.AddVFSOverlayFile(A->getValue());
3066*e038c9c4Sjoerg
3067*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
30687330f729Sjoerg }
30697330f729Sjoerg
setLangDefaults(LangOptions & Opts,InputKind IK,const llvm::Triple & T,std::vector<std::string> & Includes,LangStandard::Kind LangStd)30707330f729Sjoerg void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
30717330f729Sjoerg const llvm::Triple &T,
3072*e038c9c4Sjoerg std::vector<std::string> &Includes,
30737330f729Sjoerg LangStandard::Kind LangStd) {
30747330f729Sjoerg // Set some properties which depend solely on the input kind; it would be nice
30757330f729Sjoerg // to move these to the language standard, and have the driver resolve the
30767330f729Sjoerg // input kind + language standard.
30777330f729Sjoerg //
30787330f729Sjoerg // FIXME: Perhaps a better model would be for a single source file to have
30797330f729Sjoerg // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
30807330f729Sjoerg // simultaneously active?
30817330f729Sjoerg if (IK.getLanguage() == Language::Asm) {
30827330f729Sjoerg Opts.AsmPreprocessor = 1;
30837330f729Sjoerg } else if (IK.isObjectiveC()) {
30847330f729Sjoerg Opts.ObjC = 1;
30857330f729Sjoerg }
30867330f729Sjoerg
30877330f729Sjoerg if (LangStd == LangStandard::lang_unspecified) {
30887330f729Sjoerg // Based on the base language, pick one.
30897330f729Sjoerg switch (IK.getLanguage()) {
30907330f729Sjoerg case Language::Unknown:
30917330f729Sjoerg case Language::LLVM_IR:
30927330f729Sjoerg llvm_unreachable("Invalid input kind!");
30937330f729Sjoerg case Language::OpenCL:
30947330f729Sjoerg LangStd = LangStandard::lang_opencl10;
30957330f729Sjoerg break;
3096*e038c9c4Sjoerg case Language::OpenCLCXX:
3097*e038c9c4Sjoerg LangStd = LangStandard::lang_openclcpp;
3098*e038c9c4Sjoerg break;
30997330f729Sjoerg case Language::CUDA:
31007330f729Sjoerg LangStd = LangStandard::lang_cuda;
31017330f729Sjoerg break;
31027330f729Sjoerg case Language::Asm:
31037330f729Sjoerg case Language::C:
31047330f729Sjoerg #if defined(CLANG_DEFAULT_STD_C)
31057330f729Sjoerg LangStd = CLANG_DEFAULT_STD_C;
31067330f729Sjoerg #else
31077330f729Sjoerg // The PS4 uses C99 as the default C standard.
31087330f729Sjoerg if (T.isPS4())
31097330f729Sjoerg LangStd = LangStandard::lang_gnu99;
31107330f729Sjoerg else
3111*e038c9c4Sjoerg LangStd = LangStandard::lang_gnu17;
31127330f729Sjoerg #endif
31137330f729Sjoerg break;
31147330f729Sjoerg case Language::ObjC:
31157330f729Sjoerg #if defined(CLANG_DEFAULT_STD_C)
31167330f729Sjoerg LangStd = CLANG_DEFAULT_STD_C;
31177330f729Sjoerg #else
31187330f729Sjoerg LangStd = LangStandard::lang_gnu11;
31197330f729Sjoerg #endif
31207330f729Sjoerg break;
31217330f729Sjoerg case Language::CXX:
31227330f729Sjoerg case Language::ObjCXX:
31237330f729Sjoerg #if defined(CLANG_DEFAULT_STD_CXX)
31247330f729Sjoerg LangStd = CLANG_DEFAULT_STD_CXX;
31257330f729Sjoerg #else
31267330f729Sjoerg LangStd = LangStandard::lang_gnucxx14;
31277330f729Sjoerg #endif
31287330f729Sjoerg break;
31297330f729Sjoerg case Language::RenderScript:
31307330f729Sjoerg LangStd = LangStandard::lang_c99;
31317330f729Sjoerg break;
31327330f729Sjoerg case Language::HIP:
31337330f729Sjoerg LangStd = LangStandard::lang_hip;
31347330f729Sjoerg break;
31357330f729Sjoerg }
31367330f729Sjoerg }
31377330f729Sjoerg
31387330f729Sjoerg const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3139*e038c9c4Sjoerg Opts.LangStd = LangStd;
31407330f729Sjoerg Opts.LineComment = Std.hasLineComments();
31417330f729Sjoerg Opts.C99 = Std.isC99();
31427330f729Sjoerg Opts.C11 = Std.isC11();
31437330f729Sjoerg Opts.C17 = Std.isC17();
31447330f729Sjoerg Opts.C2x = Std.isC2x();
31457330f729Sjoerg Opts.CPlusPlus = Std.isCPlusPlus();
31467330f729Sjoerg Opts.CPlusPlus11 = Std.isCPlusPlus11();
31477330f729Sjoerg Opts.CPlusPlus14 = Std.isCPlusPlus14();
31487330f729Sjoerg Opts.CPlusPlus17 = Std.isCPlusPlus17();
3149*e038c9c4Sjoerg Opts.CPlusPlus20 = Std.isCPlusPlus20();
3150*e038c9c4Sjoerg Opts.CPlusPlus2b = Std.isCPlusPlus2b();
31517330f729Sjoerg Opts.GNUMode = Std.isGNUMode();
31527330f729Sjoerg Opts.GNUCVersion = 0;
31537330f729Sjoerg Opts.HexFloats = Std.hasHexFloats();
31547330f729Sjoerg Opts.ImplicitInt = Std.hasImplicitInt();
31557330f729Sjoerg
3156*e038c9c4Sjoerg Opts.CPlusPlusModules = Opts.CPlusPlus20;
3157*e038c9c4Sjoerg
31587330f729Sjoerg // Set OpenCL Version.
31597330f729Sjoerg Opts.OpenCL = Std.isOpenCL();
31607330f729Sjoerg if (LangStd == LangStandard::lang_opencl10)
31617330f729Sjoerg Opts.OpenCLVersion = 100;
31627330f729Sjoerg else if (LangStd == LangStandard::lang_opencl11)
31637330f729Sjoerg Opts.OpenCLVersion = 110;
31647330f729Sjoerg else if (LangStd == LangStandard::lang_opencl12)
31657330f729Sjoerg Opts.OpenCLVersion = 120;
31667330f729Sjoerg else if (LangStd == LangStandard::lang_opencl20)
31677330f729Sjoerg Opts.OpenCLVersion = 200;
3168*e038c9c4Sjoerg else if (LangStd == LangStandard::lang_opencl30)
3169*e038c9c4Sjoerg Opts.OpenCLVersion = 300;
31707330f729Sjoerg else if (LangStd == LangStandard::lang_openclcpp)
31717330f729Sjoerg Opts.OpenCLCPlusPlusVersion = 100;
31727330f729Sjoerg
31737330f729Sjoerg // OpenCL has some additional defaults.
31747330f729Sjoerg if (Opts.OpenCL) {
31757330f729Sjoerg Opts.AltiVec = 0;
31767330f729Sjoerg Opts.ZVector = 0;
3177*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_On);
31787330f729Sjoerg Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
3179*e038c9c4Sjoerg Opts.OpenCLPipe = Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
3180*e038c9c4Sjoerg Opts.OpenCLGenericAddressSpace =
3181*e038c9c4Sjoerg Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
31827330f729Sjoerg
31837330f729Sjoerg // Include default header file for OpenCL.
31847330f729Sjoerg if (Opts.IncludeDefaultHeader) {
31857330f729Sjoerg if (Opts.DeclareOpenCLBuiltins) {
31867330f729Sjoerg // Only include base header file for builtin types and constants.
3187*e038c9c4Sjoerg Includes.push_back("opencl-c-base.h");
31887330f729Sjoerg } else {
3189*e038c9c4Sjoerg Includes.push_back("opencl-c.h");
31907330f729Sjoerg }
31917330f729Sjoerg }
31927330f729Sjoerg }
31937330f729Sjoerg
31947330f729Sjoerg Opts.HIP = IK.getLanguage() == Language::HIP;
31957330f729Sjoerg Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
3196*e038c9c4Sjoerg if (Opts.HIP) {
3197*e038c9c4Sjoerg // HIP toolchain does not support 'Fast' FPOpFusion in backends since it
3198*e038c9c4Sjoerg // fuses multiplication/addition instructions without contract flag from
3199*e038c9c4Sjoerg // device library functions in LLVM bitcode, which causes accuracy loss in
3200*e038c9c4Sjoerg // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446.
3201*e038c9c4Sjoerg // For device library functions in bitcode to work, 'Strict' or 'Standard'
3202*e038c9c4Sjoerg // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas'
3203*e038c9c4Sjoerg // FP contract option is used to allow fuse across statements in frontend
3204*e038c9c4Sjoerg // whereas respecting contract flag in backend.
3205*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3206*e038c9c4Sjoerg } else if (Opts.CUDA) {
3207*e038c9c4Sjoerg // Allow fuse across statements disregarding pragmas.
3208*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3209*e038c9c4Sjoerg }
32107330f729Sjoerg
32117330f729Sjoerg Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
32127330f729Sjoerg
32137330f729Sjoerg // OpenCL and C++ both have bool, true, false keywords.
32147330f729Sjoerg Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
32157330f729Sjoerg
32167330f729Sjoerg // OpenCL has half keyword
32177330f729Sjoerg Opts.Half = Opts.OpenCL;
32187330f729Sjoerg }
32197330f729Sjoerg
32207330f729Sjoerg /// Check if input file kind and language standard are compatible.
IsInputCompatibleWithStandard(InputKind IK,const LangStandard & S)32217330f729Sjoerg static bool IsInputCompatibleWithStandard(InputKind IK,
32227330f729Sjoerg const LangStandard &S) {
32237330f729Sjoerg switch (IK.getLanguage()) {
32247330f729Sjoerg case Language::Unknown:
32257330f729Sjoerg case Language::LLVM_IR:
32267330f729Sjoerg llvm_unreachable("should not parse language flags for this input");
32277330f729Sjoerg
32287330f729Sjoerg case Language::C:
32297330f729Sjoerg case Language::ObjC:
32307330f729Sjoerg case Language::RenderScript:
32317330f729Sjoerg return S.getLanguage() == Language::C;
32327330f729Sjoerg
32337330f729Sjoerg case Language::OpenCL:
3234*e038c9c4Sjoerg return S.getLanguage() == Language::OpenCL ||
3235*e038c9c4Sjoerg S.getLanguage() == Language::OpenCLCXX;
3236*e038c9c4Sjoerg
3237*e038c9c4Sjoerg case Language::OpenCLCXX:
3238*e038c9c4Sjoerg return S.getLanguage() == Language::OpenCLCXX;
32397330f729Sjoerg
32407330f729Sjoerg case Language::CXX:
32417330f729Sjoerg case Language::ObjCXX:
32427330f729Sjoerg return S.getLanguage() == Language::CXX;
32437330f729Sjoerg
32447330f729Sjoerg case Language::CUDA:
32457330f729Sjoerg // FIXME: What -std= values should be permitted for CUDA compilations?
32467330f729Sjoerg return S.getLanguage() == Language::CUDA ||
32477330f729Sjoerg S.getLanguage() == Language::CXX;
32487330f729Sjoerg
32497330f729Sjoerg case Language::HIP:
32507330f729Sjoerg return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
32517330f729Sjoerg
32527330f729Sjoerg case Language::Asm:
32537330f729Sjoerg // Accept (and ignore) all -std= values.
32547330f729Sjoerg // FIXME: The -std= value is not ignored; it affects the tokenization
32557330f729Sjoerg // and preprocessing rules if we're preprocessing this asm input.
32567330f729Sjoerg return true;
32577330f729Sjoerg }
32587330f729Sjoerg
32597330f729Sjoerg llvm_unreachable("unexpected input language");
32607330f729Sjoerg }
32617330f729Sjoerg
32627330f729Sjoerg /// Get language name for given input kind.
GetInputKindName(InputKind IK)32637330f729Sjoerg static const StringRef GetInputKindName(InputKind IK) {
32647330f729Sjoerg switch (IK.getLanguage()) {
32657330f729Sjoerg case Language::C:
32667330f729Sjoerg return "C";
32677330f729Sjoerg case Language::ObjC:
32687330f729Sjoerg return "Objective-C";
32697330f729Sjoerg case Language::CXX:
32707330f729Sjoerg return "C++";
32717330f729Sjoerg case Language::ObjCXX:
32727330f729Sjoerg return "Objective-C++";
32737330f729Sjoerg case Language::OpenCL:
32747330f729Sjoerg return "OpenCL";
3275*e038c9c4Sjoerg case Language::OpenCLCXX:
3276*e038c9c4Sjoerg return "C++ for OpenCL";
32777330f729Sjoerg case Language::CUDA:
32787330f729Sjoerg return "CUDA";
32797330f729Sjoerg case Language::RenderScript:
32807330f729Sjoerg return "RenderScript";
32817330f729Sjoerg case Language::HIP:
32827330f729Sjoerg return "HIP";
32837330f729Sjoerg
32847330f729Sjoerg case Language::Asm:
32857330f729Sjoerg return "Asm";
32867330f729Sjoerg case Language::LLVM_IR:
32877330f729Sjoerg return "LLVM IR";
32887330f729Sjoerg
32897330f729Sjoerg case Language::Unknown:
32907330f729Sjoerg break;
32917330f729Sjoerg }
32927330f729Sjoerg llvm_unreachable("unknown input language");
32937330f729Sjoerg }
32947330f729Sjoerg
GenerateLangArgs(const LangOptions & Opts,SmallVectorImpl<const char * > & Args,StringAllocator SA,const llvm::Triple & T,InputKind IK)3295*e038c9c4Sjoerg void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
3296*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
3297*e038c9c4Sjoerg StringAllocator SA,
3298*e038c9c4Sjoerg const llvm::Triple &T, InputKind IK) {
3299*e038c9c4Sjoerg if (IK.getFormat() == InputKind::Precompiled ||
3300*e038c9c4Sjoerg IK.getLanguage() == Language::LLVM_IR) {
3301*e038c9c4Sjoerg if (Opts.ObjCAutoRefCount)
3302*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_arc, SA);
3303*e038c9c4Sjoerg if (Opts.PICLevel != 0)
3304*e038c9c4Sjoerg GenerateArg(Args, OPT_pic_level, Twine(Opts.PICLevel), SA);
3305*e038c9c4Sjoerg if (Opts.PIE)
3306*e038c9c4Sjoerg GenerateArg(Args, OPT_pic_is_pie, SA);
3307*e038c9c4Sjoerg for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3308*e038c9c4Sjoerg GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3309*e038c9c4Sjoerg
3310*e038c9c4Sjoerg return;
3311*e038c9c4Sjoerg }
3312*e038c9c4Sjoerg
3313*e038c9c4Sjoerg OptSpecifier StdOpt;
3314*e038c9c4Sjoerg switch (Opts.LangStd) {
3315*e038c9c4Sjoerg case LangStandard::lang_opencl10:
3316*e038c9c4Sjoerg case LangStandard::lang_opencl11:
3317*e038c9c4Sjoerg case LangStandard::lang_opencl12:
3318*e038c9c4Sjoerg case LangStandard::lang_opencl20:
3319*e038c9c4Sjoerg case LangStandard::lang_opencl30:
3320*e038c9c4Sjoerg case LangStandard::lang_openclcpp:
3321*e038c9c4Sjoerg StdOpt = OPT_cl_std_EQ;
3322*e038c9c4Sjoerg break;
3323*e038c9c4Sjoerg default:
3324*e038c9c4Sjoerg StdOpt = OPT_std_EQ;
3325*e038c9c4Sjoerg break;
3326*e038c9c4Sjoerg }
3327*e038c9c4Sjoerg
3328*e038c9c4Sjoerg auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3329*e038c9c4Sjoerg GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
3330*e038c9c4Sjoerg
3331*e038c9c4Sjoerg if (Opts.IncludeDefaultHeader)
3332*e038c9c4Sjoerg GenerateArg(Args, OPT_finclude_default_header, SA);
3333*e038c9c4Sjoerg if (Opts.DeclareOpenCLBuiltins)
3334*e038c9c4Sjoerg GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
3335*e038c9c4Sjoerg
3336*e038c9c4Sjoerg const LangOptions *LangOpts = &Opts;
3337*e038c9c4Sjoerg
3338*e038c9c4Sjoerg #define LANG_OPTION_WITH_MARSHALLING( \
3339*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3340*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3341*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3342*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
3343*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
3344*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
3345*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
3346*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
3347*e038c9c4Sjoerg #undef LANG_OPTION_WITH_MARSHALLING
3348*e038c9c4Sjoerg
3349*e038c9c4Sjoerg // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3350*e038c9c4Sjoerg
3351*e038c9c4Sjoerg if (Opts.ObjC) {
3352*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
3353*e038c9c4Sjoerg
3354*e038c9c4Sjoerg if (Opts.GC == LangOptions::GCOnly)
3355*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_gc_only, SA);
3356*e038c9c4Sjoerg else if (Opts.GC == LangOptions::HybridGC)
3357*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_gc, SA);
3358*e038c9c4Sjoerg else if (Opts.ObjCAutoRefCount == 1)
3359*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_arc, SA);
3360*e038c9c4Sjoerg
3361*e038c9c4Sjoerg if (Opts.ObjCWeakRuntime)
3362*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
3363*e038c9c4Sjoerg
3364*e038c9c4Sjoerg if (Opts.ObjCWeak)
3365*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_weak, SA);
3366*e038c9c4Sjoerg
3367*e038c9c4Sjoerg if (Opts.ObjCSubscriptingLegacyRuntime)
3368*e038c9c4Sjoerg GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
3369*e038c9c4Sjoerg }
3370*e038c9c4Sjoerg
3371*e038c9c4Sjoerg if (Opts.GNUCVersion != 0) {
3372*e038c9c4Sjoerg unsigned Major = Opts.GNUCVersion / 100 / 100;
3373*e038c9c4Sjoerg unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3374*e038c9c4Sjoerg unsigned Patch = Opts.GNUCVersion % 100;
3375*e038c9c4Sjoerg GenerateArg(Args, OPT_fgnuc_version_EQ,
3376*e038c9c4Sjoerg Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
3377*e038c9c4Sjoerg }
3378*e038c9c4Sjoerg
3379*e038c9c4Sjoerg if (Opts.IgnoreXCOFFVisibility)
3380*e038c9c4Sjoerg GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
3381*e038c9c4Sjoerg
3382*e038c9c4Sjoerg if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3383*e038c9c4Sjoerg GenerateArg(Args, OPT_ftrapv, SA);
3384*e038c9c4Sjoerg GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
3385*e038c9c4Sjoerg } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3386*e038c9c4Sjoerg GenerateArg(Args, OPT_fwrapv, SA);
3387*e038c9c4Sjoerg }
3388*e038c9c4Sjoerg
3389*e038c9c4Sjoerg if (Opts.MSCompatibilityVersion != 0) {
3390*e038c9c4Sjoerg unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3391*e038c9c4Sjoerg unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3392*e038c9c4Sjoerg unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3393*e038c9c4Sjoerg GenerateArg(Args, OPT_fms_compatibility_version,
3394*e038c9c4Sjoerg Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
3395*e038c9c4Sjoerg }
3396*e038c9c4Sjoerg
3397*e038c9c4Sjoerg if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3398*e038c9c4Sjoerg if (!Opts.Trigraphs)
3399*e038c9c4Sjoerg GenerateArg(Args, OPT_fno_trigraphs, SA);
3400*e038c9c4Sjoerg } else {
3401*e038c9c4Sjoerg if (Opts.Trigraphs)
3402*e038c9c4Sjoerg GenerateArg(Args, OPT_ftrigraphs, SA);
3403*e038c9c4Sjoerg }
3404*e038c9c4Sjoerg
3405*e038c9c4Sjoerg if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3406*e038c9c4Sjoerg GenerateArg(Args, OPT_fblocks, SA);
3407*e038c9c4Sjoerg
3408*e038c9c4Sjoerg if (Opts.ConvergentFunctions &&
3409*e038c9c4Sjoerg !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3410*e038c9c4Sjoerg GenerateArg(Args, OPT_fconvergent_functions, SA);
3411*e038c9c4Sjoerg
3412*e038c9c4Sjoerg if (Opts.NoBuiltin && !Opts.Freestanding)
3413*e038c9c4Sjoerg GenerateArg(Args, OPT_fno_builtin, SA);
3414*e038c9c4Sjoerg
3415*e038c9c4Sjoerg if (!Opts.NoBuiltin)
3416*e038c9c4Sjoerg for (const auto &Func : Opts.NoBuiltinFuncs)
3417*e038c9c4Sjoerg GenerateArg(Args, OPT_fno_builtin_, Func, SA);
3418*e038c9c4Sjoerg
3419*e038c9c4Sjoerg if (Opts.LongDoubleSize == 128)
3420*e038c9c4Sjoerg GenerateArg(Args, OPT_mlong_double_128, SA);
3421*e038c9c4Sjoerg else if (Opts.LongDoubleSize == 64)
3422*e038c9c4Sjoerg GenerateArg(Args, OPT_mlong_double_64, SA);
3423*e038c9c4Sjoerg
3424*e038c9c4Sjoerg // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3425*e038c9c4Sjoerg
3426*e038c9c4Sjoerg // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3427*e038c9c4Sjoerg // '-fopenmp-targets='.
3428*e038c9c4Sjoerg if (Opts.OpenMP && !Opts.OpenMPSimd) {
3429*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp, SA);
3430*e038c9c4Sjoerg
3431*e038c9c4Sjoerg if (Opts.OpenMP != 50)
3432*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3433*e038c9c4Sjoerg
3434*e038c9c4Sjoerg if (!Opts.OpenMPUseTLS)
3435*e038c9c4Sjoerg GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
3436*e038c9c4Sjoerg
3437*e038c9c4Sjoerg if (Opts.OpenMPIsDevice)
3438*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_is_device, SA);
3439*e038c9c4Sjoerg
3440*e038c9c4Sjoerg if (Opts.OpenMPIRBuilder)
3441*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
3442*e038c9c4Sjoerg }
3443*e038c9c4Sjoerg
3444*e038c9c4Sjoerg if (Opts.OpenMPSimd) {
3445*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_simd, SA);
3446*e038c9c4Sjoerg
3447*e038c9c4Sjoerg if (Opts.OpenMP != 50)
3448*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3449*e038c9c4Sjoerg }
3450*e038c9c4Sjoerg
3451*e038c9c4Sjoerg if (Opts.OpenMPCUDANumSMs != 0)
3452*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
3453*e038c9c4Sjoerg Twine(Opts.OpenMPCUDANumSMs), SA);
3454*e038c9c4Sjoerg
3455*e038c9c4Sjoerg if (Opts.OpenMPCUDABlocksPerSM != 0)
3456*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3457*e038c9c4Sjoerg Twine(Opts.OpenMPCUDABlocksPerSM), SA);
3458*e038c9c4Sjoerg
3459*e038c9c4Sjoerg if (Opts.OpenMPCUDAReductionBufNum != 1024)
3460*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3461*e038c9c4Sjoerg Twine(Opts.OpenMPCUDAReductionBufNum), SA);
3462*e038c9c4Sjoerg
3463*e038c9c4Sjoerg if (!Opts.OMPTargetTriples.empty()) {
3464*e038c9c4Sjoerg std::string Targets;
3465*e038c9c4Sjoerg llvm::raw_string_ostream OS(Targets);
3466*e038c9c4Sjoerg llvm::interleave(
3467*e038c9c4Sjoerg Opts.OMPTargetTriples, OS,
3468*e038c9c4Sjoerg [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3469*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
3470*e038c9c4Sjoerg }
3471*e038c9c4Sjoerg
3472*e038c9c4Sjoerg if (!Opts.OMPHostIRFile.empty())
3473*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
3474*e038c9c4Sjoerg
3475*e038c9c4Sjoerg if (Opts.OpenMPCUDAMode)
3476*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
3477*e038c9c4Sjoerg
3478*e038c9c4Sjoerg if (Opts.OpenMPCUDATargetParallel)
3479*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_cuda_parallel_target_regions, SA);
3480*e038c9c4Sjoerg
3481*e038c9c4Sjoerg if (Opts.OpenMPCUDAForceFullRuntime)
3482*e038c9c4Sjoerg GenerateArg(Args, OPT_fopenmp_cuda_force_full_runtime, SA);
3483*e038c9c4Sjoerg
3484*e038c9c4Sjoerg // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3485*e038c9c4Sjoerg // generated from CodeGenOptions.
3486*e038c9c4Sjoerg
3487*e038c9c4Sjoerg if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3488*e038c9c4Sjoerg GenerateArg(Args, OPT_ffp_contract, "fast", SA);
3489*e038c9c4Sjoerg else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3490*e038c9c4Sjoerg GenerateArg(Args, OPT_ffp_contract, "on", SA);
3491*e038c9c4Sjoerg else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3492*e038c9c4Sjoerg GenerateArg(Args, OPT_ffp_contract, "off", SA);
3493*e038c9c4Sjoerg else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3494*e038c9c4Sjoerg GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
3495*e038c9c4Sjoerg
3496*e038c9c4Sjoerg for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3497*e038c9c4Sjoerg GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3498*e038c9c4Sjoerg
3499*e038c9c4Sjoerg // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3500*e038c9c4Sjoerg for (const std::string &F : Opts.NoSanitizeFiles)
3501*e038c9c4Sjoerg GenerateArg(Args, OPT_fsanitize_ignorelist_EQ, F, SA);
3502*e038c9c4Sjoerg
3503*e038c9c4Sjoerg if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
3504*e038c9c4Sjoerg GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
3505*e038c9c4Sjoerg else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
3506*e038c9c4Sjoerg GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
3507*e038c9c4Sjoerg else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
3508*e038c9c4Sjoerg GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
3509*e038c9c4Sjoerg else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
3510*e038c9c4Sjoerg GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
3511*e038c9c4Sjoerg else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
3512*e038c9c4Sjoerg GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
3513*e038c9c4Sjoerg else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
3514*e038c9c4Sjoerg GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
3515*e038c9c4Sjoerg else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver12)
3516*e038c9c4Sjoerg GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
3517*e038c9c4Sjoerg
3518*e038c9c4Sjoerg if (Opts.getSignReturnAddressScope() ==
3519*e038c9c4Sjoerg LangOptions::SignReturnAddressScopeKind::All)
3520*e038c9c4Sjoerg GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
3521*e038c9c4Sjoerg else if (Opts.getSignReturnAddressScope() ==
3522*e038c9c4Sjoerg LangOptions::SignReturnAddressScopeKind::NonLeaf)
3523*e038c9c4Sjoerg GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
3524*e038c9c4Sjoerg
3525*e038c9c4Sjoerg if (Opts.getSignReturnAddressKey() ==
3526*e038c9c4Sjoerg LangOptions::SignReturnAddressKeyKind::BKey)
3527*e038c9c4Sjoerg GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
3528*e038c9c4Sjoerg
3529*e038c9c4Sjoerg if (Opts.CXXABI)
3530*e038c9c4Sjoerg GenerateArg(Args, OPT_fcxx_abi_EQ, TargetCXXABI::getSpelling(*Opts.CXXABI),
3531*e038c9c4Sjoerg SA);
3532*e038c9c4Sjoerg }
3533*e038c9c4Sjoerg
ParseLangArgs(LangOptions & Opts,ArgList & Args,InputKind IK,const llvm::Triple & T,std::vector<std::string> & Includes,DiagnosticsEngine & Diags)3534*e038c9c4Sjoerg bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3535*e038c9c4Sjoerg InputKind IK, const llvm::Triple &T,
3536*e038c9c4Sjoerg std::vector<std::string> &Includes,
35377330f729Sjoerg DiagnosticsEngine &Diags) {
3538*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
3539*e038c9c4Sjoerg
3540*e038c9c4Sjoerg if (IK.getFormat() == InputKind::Precompiled ||
3541*e038c9c4Sjoerg IK.getLanguage() == Language::LLVM_IR) {
3542*e038c9c4Sjoerg // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3543*e038c9c4Sjoerg // PassManager in BackendUtil.cpp. They need to be initialized no matter
3544*e038c9c4Sjoerg // what the input type is.
3545*e038c9c4Sjoerg if (Args.hasArg(OPT_fobjc_arc))
3546*e038c9c4Sjoerg Opts.ObjCAutoRefCount = 1;
3547*e038c9c4Sjoerg // PICLevel and PIELevel are needed during code generation and this should
3548*e038c9c4Sjoerg // be set regardless of the input type.
3549*e038c9c4Sjoerg Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3550*e038c9c4Sjoerg Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3551*e038c9c4Sjoerg parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3552*e038c9c4Sjoerg Diags, Opts.Sanitize);
3553*e038c9c4Sjoerg
3554*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
3555*e038c9c4Sjoerg }
3556*e038c9c4Sjoerg
3557*e038c9c4Sjoerg // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3558*e038c9c4Sjoerg // FIXME: Should we really be parsing this for an Language::Asm input?
3559*e038c9c4Sjoerg
35607330f729Sjoerg // FIXME: Cleanup per-file based stuff.
35617330f729Sjoerg LangStandard::Kind LangStd = LangStandard::lang_unspecified;
35627330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
35637330f729Sjoerg LangStd = LangStandard::getLangKind(A->getValue());
35647330f729Sjoerg if (LangStd == LangStandard::lang_unspecified) {
35657330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
35667330f729Sjoerg << A->getAsString(Args) << A->getValue();
35677330f729Sjoerg // Report supported standards with short description.
35687330f729Sjoerg for (unsigned KindValue = 0;
35697330f729Sjoerg KindValue != LangStandard::lang_unspecified;
35707330f729Sjoerg ++KindValue) {
35717330f729Sjoerg const LangStandard &Std = LangStandard::getLangStandardForKind(
35727330f729Sjoerg static_cast<LangStandard::Kind>(KindValue));
35737330f729Sjoerg if (IsInputCompatibleWithStandard(IK, Std)) {
35747330f729Sjoerg auto Diag = Diags.Report(diag::note_drv_use_standard);
35757330f729Sjoerg Diag << Std.getName() << Std.getDescription();
35767330f729Sjoerg unsigned NumAliases = 0;
35777330f729Sjoerg #define LANGSTANDARD(id, name, lang, desc, features)
35787330f729Sjoerg #define LANGSTANDARD_ALIAS(id, alias) \
35797330f729Sjoerg if (KindValue == LangStandard::lang_##id) ++NumAliases;
35807330f729Sjoerg #define LANGSTANDARD_ALIAS_DEPR(id, alias)
35817330f729Sjoerg #include "clang/Basic/LangStandards.def"
35827330f729Sjoerg Diag << NumAliases;
35837330f729Sjoerg #define LANGSTANDARD(id, name, lang, desc, features)
35847330f729Sjoerg #define LANGSTANDARD_ALIAS(id, alias) \
35857330f729Sjoerg if (KindValue == LangStandard::lang_##id) Diag << alias;
35867330f729Sjoerg #define LANGSTANDARD_ALIAS_DEPR(id, alias)
35877330f729Sjoerg #include "clang/Basic/LangStandards.def"
35887330f729Sjoerg }
35897330f729Sjoerg }
35907330f729Sjoerg } else {
35917330f729Sjoerg // Valid standard, check to make sure language and standard are
35927330f729Sjoerg // compatible.
35937330f729Sjoerg const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
35947330f729Sjoerg if (!IsInputCompatibleWithStandard(IK, Std)) {
35957330f729Sjoerg Diags.Report(diag::err_drv_argument_not_allowed_with)
35967330f729Sjoerg << A->getAsString(Args) << GetInputKindName(IK);
35977330f729Sjoerg }
35987330f729Sjoerg }
35997330f729Sjoerg }
36007330f729Sjoerg
36017330f729Sjoerg // -cl-std only applies for OpenCL language standards.
36027330f729Sjoerg // Override the -std option in this case.
36037330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
36047330f729Sjoerg LangStandard::Kind OpenCLLangStd
36057330f729Sjoerg = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
36067330f729Sjoerg .Cases("cl", "CL", LangStandard::lang_opencl10)
3607*e038c9c4Sjoerg .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
36087330f729Sjoerg .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
36097330f729Sjoerg .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
36107330f729Sjoerg .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3611*e038c9c4Sjoerg .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
36127330f729Sjoerg .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
36137330f729Sjoerg .Default(LangStandard::lang_unspecified);
36147330f729Sjoerg
36157330f729Sjoerg if (OpenCLLangStd == LangStandard::lang_unspecified) {
36167330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
36177330f729Sjoerg << A->getAsString(Args) << A->getValue();
36187330f729Sjoerg }
36197330f729Sjoerg else
36207330f729Sjoerg LangStd = OpenCLLangStd;
36217330f729Sjoerg }
36227330f729Sjoerg
3623*e038c9c4Sjoerg // These need to be parsed now. They are used to set OpenCL defaults.
36247330f729Sjoerg Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
36257330f729Sjoerg Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
36267330f729Sjoerg
3627*e038c9c4Sjoerg CompilerInvocation::setLangDefaults(Opts, IK, T, Includes, LangStd);
36287330f729Sjoerg
3629*e038c9c4Sjoerg // The key paths of codegen options defined in Options.td start with
3630*e038c9c4Sjoerg // "LangOpts->". Let's provide the expected variable name and type.
3631*e038c9c4Sjoerg LangOptions *LangOpts = &Opts;
3632*e038c9c4Sjoerg
3633*e038c9c4Sjoerg #define LANG_OPTION_WITH_MARSHALLING( \
3634*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3635*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3636*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3637*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
3638*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
3639*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
3640*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
3641*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
3642*e038c9c4Sjoerg #undef LANG_OPTION_WITH_MARSHALLING
3643*e038c9c4Sjoerg
3644*e038c9c4Sjoerg if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3645*e038c9c4Sjoerg StringRef Name = A->getValue();
3646*e038c9c4Sjoerg if (Name == "full" || Name == "branch") {
3647*e038c9c4Sjoerg Opts.CFProtectionBranch = 1;
3648*e038c9c4Sjoerg }
36497330f729Sjoerg }
36507330f729Sjoerg
3651*e038c9c4Sjoerg if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3652*e038c9c4Sjoerg !Args.hasArg(OPT_sycl_std_EQ)) {
3653*e038c9c4Sjoerg // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3654*e038c9c4Sjoerg // provide -sycl-std=, we want to default it to whatever the default SYCL
3655*e038c9c4Sjoerg // version is. I could not find a way to express this with the options
3656*e038c9c4Sjoerg // tablegen because we still want this value to be SYCL_None when the user
3657*e038c9c4Sjoerg // is not in device or host mode.
3658*e038c9c4Sjoerg Opts.setSYCLVersion(LangOptions::SYCL_Default);
36597330f729Sjoerg }
36607330f729Sjoerg
36617330f729Sjoerg if (Opts.ObjC) {
36627330f729Sjoerg if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
36637330f729Sjoerg StringRef value = arg->getValue();
36647330f729Sjoerg if (Opts.ObjCRuntime.tryParse(value))
36657330f729Sjoerg Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
36667330f729Sjoerg }
36677330f729Sjoerg
36687330f729Sjoerg if (Args.hasArg(OPT_fobjc_gc_only))
36697330f729Sjoerg Opts.setGC(LangOptions::GCOnly);
36707330f729Sjoerg else if (Args.hasArg(OPT_fobjc_gc))
36717330f729Sjoerg Opts.setGC(LangOptions::HybridGC);
36727330f729Sjoerg else if (Args.hasArg(OPT_fobjc_arc)) {
36737330f729Sjoerg Opts.ObjCAutoRefCount = 1;
36747330f729Sjoerg if (!Opts.ObjCRuntime.allowsARC())
36757330f729Sjoerg Diags.Report(diag::err_arc_unsupported_on_runtime);
36767330f729Sjoerg }
36777330f729Sjoerg
36787330f729Sjoerg // ObjCWeakRuntime tracks whether the runtime supports __weak, not
36797330f729Sjoerg // whether the feature is actually enabled. This is predominantly
36807330f729Sjoerg // determined by -fobjc-runtime, but we allow it to be overridden
36817330f729Sjoerg // from the command line for testing purposes.
36827330f729Sjoerg if (Args.hasArg(OPT_fobjc_runtime_has_weak))
36837330f729Sjoerg Opts.ObjCWeakRuntime = 1;
36847330f729Sjoerg else
36857330f729Sjoerg Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
36867330f729Sjoerg
36877330f729Sjoerg // ObjCWeak determines whether __weak is actually enabled.
36887330f729Sjoerg // Note that we allow -fno-objc-weak to disable this even in ARC mode.
36897330f729Sjoerg if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
36907330f729Sjoerg if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
36917330f729Sjoerg assert(!Opts.ObjCWeak);
36927330f729Sjoerg } else if (Opts.getGC() != LangOptions::NonGC) {
36937330f729Sjoerg Diags.Report(diag::err_objc_weak_with_gc);
36947330f729Sjoerg } else if (!Opts.ObjCWeakRuntime) {
36957330f729Sjoerg Diags.Report(diag::err_objc_weak_unsupported);
36967330f729Sjoerg } else {
36977330f729Sjoerg Opts.ObjCWeak = 1;
36987330f729Sjoerg }
36997330f729Sjoerg } else if (Opts.ObjCAutoRefCount) {
37007330f729Sjoerg Opts.ObjCWeak = Opts.ObjCWeakRuntime;
37017330f729Sjoerg }
37027330f729Sjoerg
37037330f729Sjoerg if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
37047330f729Sjoerg Opts.ObjCSubscriptingLegacyRuntime =
37057330f729Sjoerg (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
37067330f729Sjoerg }
37077330f729Sjoerg
37087330f729Sjoerg if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
37097330f729Sjoerg // Check that the version has 1 to 3 components and the minor and patch
37107330f729Sjoerg // versions fit in two decimal digits.
37117330f729Sjoerg VersionTuple GNUCVer;
37127330f729Sjoerg bool Invalid = GNUCVer.tryParse(A->getValue());
37137330f729Sjoerg unsigned Major = GNUCVer.getMajor();
37147330f729Sjoerg unsigned Minor = GNUCVer.getMinor().getValueOr(0);
37157330f729Sjoerg unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
37167330f729Sjoerg if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
37177330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
37187330f729Sjoerg << A->getAsString(Args) << A->getValue();
37197330f729Sjoerg }
37207330f729Sjoerg Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
37217330f729Sjoerg }
37227330f729Sjoerg
3723*e038c9c4Sjoerg // In AIX OS, the -mignore-xcoff-visibility is enable by default if there is
3724*e038c9c4Sjoerg // no -fvisibility=* option.
3725*e038c9c4Sjoerg // This is the reason why '-fvisibility' needs to be always generated:
3726*e038c9c4Sjoerg // its absence implies '-mignore-xcoff-visibility'.
3727*e038c9c4Sjoerg //
3728*e038c9c4Sjoerg // Suppose the original cc1 command line does contain '-fvisibility default':
3729*e038c9c4Sjoerg // '-mignore-xcoff-visibility' should not be implied.
3730*e038c9c4Sjoerg // * If '-fvisibility' is not generated (as most options with default values
3731*e038c9c4Sjoerg // don't), its absence would imply '-mignore-xcoff-visibility'. This changes
3732*e038c9c4Sjoerg // the command line semantics.
3733*e038c9c4Sjoerg // * If '-fvisibility' is generated regardless of its presence and value,
3734*e038c9c4Sjoerg // '-mignore-xcoff-visibility' won't be implied and the command line
3735*e038c9c4Sjoerg // semantics are kept intact.
3736*e038c9c4Sjoerg //
3737*e038c9c4Sjoerg // When the original cc1 command line does **not** contain '-fvisibility',
3738*e038c9c4Sjoerg // '-mignore-xcoff-visibility' is implied. The generated command line will
3739*e038c9c4Sjoerg // contain both '-fvisibility default' and '-mignore-xcoff-visibility' and
3740*e038c9c4Sjoerg // subsequent calls to `CreateFromArgs`/`generateCC1CommandLine` will always
3741*e038c9c4Sjoerg // produce the same arguments.
37427330f729Sjoerg
3743*e038c9c4Sjoerg if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) ||
3744*e038c9c4Sjoerg !Args.hasArg(OPT_fvisibility)))
3745*e038c9c4Sjoerg Opts.IgnoreXCOFFVisibility = 1;
37467330f729Sjoerg
37477330f729Sjoerg if (Args.hasArg(OPT_ftrapv)) {
37487330f729Sjoerg Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
37497330f729Sjoerg // Set the handler, if one is specified.
37507330f729Sjoerg Opts.OverflowHandler =
3751*e038c9c4Sjoerg std::string(Args.getLastArgValue(OPT_ftrapv_handler));
37527330f729Sjoerg }
37537330f729Sjoerg else if (Args.hasArg(OPT_fwrapv))
37547330f729Sjoerg Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
37557330f729Sjoerg
37567330f729Sjoerg Opts.MSCompatibilityVersion = 0;
37577330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
37587330f729Sjoerg VersionTuple VT;
37597330f729Sjoerg if (VT.tryParse(A->getValue()))
37607330f729Sjoerg Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
37617330f729Sjoerg << A->getValue();
37627330f729Sjoerg Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
37637330f729Sjoerg VT.getMinor().getValueOr(0) * 100000 +
37647330f729Sjoerg VT.getSubminor().getValueOr(0);
37657330f729Sjoerg }
37667330f729Sjoerg
37677330f729Sjoerg // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
37687330f729Sjoerg // is specified, or -std is set to a conforming mode.
37697330f729Sjoerg // Trigraphs are disabled by default in c++1z onwards.
3770*e038c9c4Sjoerg // For z/OS, trigraphs are enabled by default (without regard to the above).
3771*e038c9c4Sjoerg Opts.Trigraphs =
3772*e038c9c4Sjoerg (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
37737330f729Sjoerg Opts.Trigraphs =
37747330f729Sjoerg Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
37757330f729Sjoerg
37767330f729Sjoerg Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
37777330f729Sjoerg && Opts.OpenCLVersion == 200);
37787330f729Sjoerg
3779*e038c9c4Sjoerg Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3780*e038c9c4Sjoerg Opts.SYCLIsDevice ||
3781*e038c9c4Sjoerg Args.hasArg(OPT_fconvergent_functions);
37827330f729Sjoerg
37837330f729Sjoerg Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
37847330f729Sjoerg if (!Opts.NoBuiltin)
37857330f729Sjoerg getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
37867330f729Sjoerg Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
37877330f729Sjoerg ? 128
37887330f729Sjoerg : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
3789*e038c9c4Sjoerg if (Opts.FastRelaxedMath)
3790*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
37917330f729Sjoerg llvm::sort(Opts.ModuleFeatures);
37927330f729Sjoerg
37937330f729Sjoerg // -mrtd option
37947330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_mrtd)) {
37957330f729Sjoerg if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
37967330f729Sjoerg Diags.Report(diag::err_drv_argument_not_allowed_with)
37977330f729Sjoerg << A->getSpelling() << "-fdefault-calling-conv";
37987330f729Sjoerg else {
37997330f729Sjoerg if (T.getArch() != llvm::Triple::x86)
38007330f729Sjoerg Diags.Report(diag::err_drv_argument_not_allowed_with)
38017330f729Sjoerg << A->getSpelling() << T.getTriple();
38027330f729Sjoerg else
38037330f729Sjoerg Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
38047330f729Sjoerg }
38057330f729Sjoerg }
38067330f729Sjoerg
3807*e038c9c4Sjoerg // Check if -fopenmp is specified and set default version to 5.0.
3808*e038c9c4Sjoerg Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0;
38097330f729Sjoerg // Check if -fopenmp-simd is specified.
38107330f729Sjoerg bool IsSimdSpecified =
38117330f729Sjoerg Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
38127330f729Sjoerg /*Default=*/false);
38137330f729Sjoerg Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
38147330f729Sjoerg Opts.OpenMPUseTLS =
38157330f729Sjoerg Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
38167330f729Sjoerg Opts.OpenMPIsDevice =
38177330f729Sjoerg Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
3818*e038c9c4Sjoerg Opts.OpenMPIRBuilder =
3819*e038c9c4Sjoerg Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
38207330f729Sjoerg bool IsTargetSpecified =
38217330f729Sjoerg Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
38227330f729Sjoerg
3823*e038c9c4Sjoerg Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice;
3824*e038c9c4Sjoerg
38257330f729Sjoerg if (Opts.OpenMP || Opts.OpenMPSimd) {
38267330f729Sjoerg if (int Version = getLastArgIntValue(
38277330f729Sjoerg Args, OPT_fopenmp_version_EQ,
3828*e038c9c4Sjoerg (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
38297330f729Sjoerg Opts.OpenMP = Version;
38307330f729Sjoerg // Provide diagnostic when a given target is not expected to be an OpenMP
38317330f729Sjoerg // device or host.
38327330f729Sjoerg if (!Opts.OpenMPIsDevice) {
38337330f729Sjoerg switch (T.getArch()) {
38347330f729Sjoerg default:
38357330f729Sjoerg break;
38367330f729Sjoerg // Add unsupported host targets here:
38377330f729Sjoerg case llvm::Triple::nvptx:
38387330f729Sjoerg case llvm::Triple::nvptx64:
3839*e038c9c4Sjoerg Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
38407330f729Sjoerg break;
38417330f729Sjoerg }
38427330f729Sjoerg }
38437330f729Sjoerg }
38447330f729Sjoerg
38457330f729Sjoerg // Set the flag to prevent the implementation from emitting device exception
38467330f729Sjoerg // handling code for those requiring so.
3847*e038c9c4Sjoerg if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3848*e038c9c4Sjoerg Opts.OpenCLCPlusPlus) {
38497330f729Sjoerg Opts.Exceptions = 0;
38507330f729Sjoerg Opts.CXXExceptions = 0;
38517330f729Sjoerg }
38527330f729Sjoerg if (Opts.OpenMPIsDevice && T.isNVPTX()) {
38537330f729Sjoerg Opts.OpenMPCUDANumSMs =
38547330f729Sjoerg getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
38557330f729Sjoerg Opts.OpenMPCUDANumSMs, Diags);
38567330f729Sjoerg Opts.OpenMPCUDABlocksPerSM =
38577330f729Sjoerg getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
38587330f729Sjoerg Opts.OpenMPCUDABlocksPerSM, Diags);
38597330f729Sjoerg Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
38607330f729Sjoerg Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
38617330f729Sjoerg Opts.OpenMPCUDAReductionBufNum, Diags);
38627330f729Sjoerg }
38637330f729Sjoerg
38647330f729Sjoerg // Get the OpenMP target triples if any.
38657330f729Sjoerg if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3866*e038c9c4Sjoerg enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3867*e038c9c4Sjoerg auto getArchPtrSize = [](const llvm::Triple &T) {
3868*e038c9c4Sjoerg if (T.isArch16Bit())
3869*e038c9c4Sjoerg return Arch16Bit;
3870*e038c9c4Sjoerg if (T.isArch32Bit())
3871*e038c9c4Sjoerg return Arch32Bit;
3872*e038c9c4Sjoerg assert(T.isArch64Bit() && "Expected 64-bit architecture");
3873*e038c9c4Sjoerg return Arch64Bit;
3874*e038c9c4Sjoerg };
38757330f729Sjoerg
38767330f729Sjoerg for (unsigned i = 0; i < A->getNumValues(); ++i) {
38777330f729Sjoerg llvm::Triple TT(A->getValue(i));
38787330f729Sjoerg
38797330f729Sjoerg if (TT.getArch() == llvm::Triple::UnknownArch ||
3880*e038c9c4Sjoerg !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
38817330f729Sjoerg TT.getArch() == llvm::Triple::nvptx ||
38827330f729Sjoerg TT.getArch() == llvm::Triple::nvptx64 ||
3883*e038c9c4Sjoerg TT.getArch() == llvm::Triple::amdgcn ||
38847330f729Sjoerg TT.getArch() == llvm::Triple::x86 ||
38857330f729Sjoerg TT.getArch() == llvm::Triple::x86_64))
38867330f729Sjoerg Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3887*e038c9c4Sjoerg else if (getArchPtrSize(T) != getArchPtrSize(TT))
3888*e038c9c4Sjoerg Diags.Report(diag::err_drv_incompatible_omp_arch)
3889*e038c9c4Sjoerg << A->getValue(i) << T.str();
38907330f729Sjoerg else
38917330f729Sjoerg Opts.OMPTargetTriples.push_back(TT);
38927330f729Sjoerg }
38937330f729Sjoerg }
38947330f729Sjoerg
38957330f729Sjoerg // Get OpenMP host file path if any and report if a non existent file is
38967330f729Sjoerg // found
38977330f729Sjoerg if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
38987330f729Sjoerg Opts.OMPHostIRFile = A->getValue();
38997330f729Sjoerg if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
39007330f729Sjoerg Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
39017330f729Sjoerg << Opts.OMPHostIRFile;
39027330f729Sjoerg }
39037330f729Sjoerg
3904*e038c9c4Sjoerg // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3905*e038c9c4Sjoerg Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
39067330f729Sjoerg Args.hasArg(options::OPT_fopenmp_cuda_mode);
39077330f729Sjoerg
3908*e038c9c4Sjoerg // Set CUDA support for parallel execution of target regions for OpenMP target
3909*e038c9c4Sjoerg // NVPTX/AMDGCN if specified in options.
3910*e038c9c4Sjoerg Opts.OpenMPCUDATargetParallel =
3911*e038c9c4Sjoerg Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3912*e038c9c4Sjoerg Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions);
39137330f729Sjoerg
3914*e038c9c4Sjoerg // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3915*e038c9c4Sjoerg Opts.OpenMPCUDAForceFullRuntime =
3916*e038c9c4Sjoerg Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3917*e038c9c4Sjoerg Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
39187330f729Sjoerg
39197330f729Sjoerg // FIXME: Eliminate this dependency.
39207330f729Sjoerg unsigned Opt = getOptimizationLevel(Args, IK, Diags),
39217330f729Sjoerg OptSize = getOptimizationLevelSize(Args);
39227330f729Sjoerg Opts.Optimize = Opt != 0;
39237330f729Sjoerg Opts.OptimizeSize = OptSize != 0;
39247330f729Sjoerg
39257330f729Sjoerg // This is the __NO_INLINE__ define, which just depends on things like the
39267330f729Sjoerg // optimization level and -fno-inline, not actually whether the backend has
39277330f729Sjoerg // inlining enabled.
39287330f729Sjoerg Opts.NoInlineDefine = !Opts.Optimize;
39297330f729Sjoerg if (Arg *InlineArg = Args.getLastArg(
39307330f729Sjoerg options::OPT_finline_functions, options::OPT_finline_hint_functions,
39317330f729Sjoerg options::OPT_fno_inline_functions, options::OPT_fno_inline))
39327330f729Sjoerg if (InlineArg->getOption().matches(options::OPT_fno_inline))
39337330f729Sjoerg Opts.NoInlineDefine = true;
39347330f729Sjoerg
39357330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
39367330f729Sjoerg StringRef Val = A->getValue();
39377330f729Sjoerg if (Val == "fast")
3938*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
39397330f729Sjoerg else if (Val == "on")
3940*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_On);
39417330f729Sjoerg else if (Val == "off")
3942*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3943*e038c9c4Sjoerg else if (Val == "fast-honor-pragmas")
3944*e038c9c4Sjoerg Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
39457330f729Sjoerg else
39467330f729Sjoerg Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
39477330f729Sjoerg }
39487330f729Sjoerg
39497330f729Sjoerg // Parse -fsanitize= arguments.
39507330f729Sjoerg parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
39517330f729Sjoerg Diags, Opts.Sanitize);
3952*e038c9c4Sjoerg Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
3953*e038c9c4Sjoerg std::vector<std::string> systemIgnorelists =
3954*e038c9c4Sjoerg Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
3955*e038c9c4Sjoerg Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
3956*e038c9c4Sjoerg systemIgnorelists.begin(),
3957*e038c9c4Sjoerg systemIgnorelists.end());
39587330f729Sjoerg
39597330f729Sjoerg if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
39607330f729Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Latest);
39617330f729Sjoerg
39627330f729Sjoerg StringRef Ver = A->getValue();
39637330f729Sjoerg std::pair<StringRef, StringRef> VerParts = Ver.split('.');
39647330f729Sjoerg unsigned Major, Minor = 0;
39657330f729Sjoerg
39667330f729Sjoerg // Check the version number is valid: either 3.x (0 <= x <= 9) or
39677330f729Sjoerg // y or y.0 (4 <= y <= current version).
39687330f729Sjoerg if (!VerParts.first.startswith("0") &&
39697330f729Sjoerg !VerParts.first.getAsInteger(10, Major) &&
39707330f729Sjoerg 3 <= Major && Major <= CLANG_VERSION_MAJOR &&
39717330f729Sjoerg (Major == 3 ? VerParts.second.size() == 1 &&
39727330f729Sjoerg !VerParts.second.getAsInteger(10, Minor)
39737330f729Sjoerg : VerParts.first.size() == Ver.size() ||
39747330f729Sjoerg VerParts.second == "0")) {
39757330f729Sjoerg // Got a valid version number.
39767330f729Sjoerg if (Major == 3 && Minor <= 8)
39777330f729Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
39787330f729Sjoerg else if (Major <= 4)
39797330f729Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
39807330f729Sjoerg else if (Major <= 6)
39817330f729Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
39827330f729Sjoerg else if (Major <= 7)
39837330f729Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
39847330f729Sjoerg else if (Major <= 9)
39857330f729Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3986*e038c9c4Sjoerg else if (Major <= 11)
3987*e038c9c4Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
3988*e038c9c4Sjoerg else if (Major <= 12)
3989*e038c9c4Sjoerg Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
39907330f729Sjoerg } else if (Ver != "latest") {
39917330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
39927330f729Sjoerg << A->getAsString(Args) << A->getValue();
39937330f729Sjoerg }
39947330f729Sjoerg }
39957330f729Sjoerg
3996*e038c9c4Sjoerg if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
3997*e038c9c4Sjoerg StringRef SignScope = A->getValue();
3998*e038c9c4Sjoerg
3999*e038c9c4Sjoerg if (SignScope.equals_lower("none"))
4000*e038c9c4Sjoerg Opts.setSignReturnAddressScope(
4001*e038c9c4Sjoerg LangOptions::SignReturnAddressScopeKind::None);
4002*e038c9c4Sjoerg else if (SignScope.equals_lower("all"))
4003*e038c9c4Sjoerg Opts.setSignReturnAddressScope(
4004*e038c9c4Sjoerg LangOptions::SignReturnAddressScopeKind::All);
4005*e038c9c4Sjoerg else if (SignScope.equals_lower("non-leaf"))
4006*e038c9c4Sjoerg Opts.setSignReturnAddressScope(
4007*e038c9c4Sjoerg LangOptions::SignReturnAddressScopeKind::NonLeaf);
4008*e038c9c4Sjoerg else
4009*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_value)
4010*e038c9c4Sjoerg << A->getAsString(Args) << SignScope;
4011*e038c9c4Sjoerg
4012*e038c9c4Sjoerg if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
4013*e038c9c4Sjoerg StringRef SignKey = A->getValue();
4014*e038c9c4Sjoerg if (!SignScope.empty() && !SignKey.empty()) {
4015*e038c9c4Sjoerg if (SignKey.equals_lower("a_key"))
4016*e038c9c4Sjoerg Opts.setSignReturnAddressKey(
4017*e038c9c4Sjoerg LangOptions::SignReturnAddressKeyKind::AKey);
4018*e038c9c4Sjoerg else if (SignKey.equals_lower("b_key"))
4019*e038c9c4Sjoerg Opts.setSignReturnAddressKey(
4020*e038c9c4Sjoerg LangOptions::SignReturnAddressKeyKind::BKey);
4021*e038c9c4Sjoerg else
4022*e038c9c4Sjoerg Diags.Report(diag::err_drv_invalid_value)
4023*e038c9c4Sjoerg << A->getAsString(Args) << SignKey;
4024*e038c9c4Sjoerg }
4025*e038c9c4Sjoerg }
4026*e038c9c4Sjoerg }
4027*e038c9c4Sjoerg
4028*e038c9c4Sjoerg // The value can be empty, which indicates the system default should be used.
4029*e038c9c4Sjoerg StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4030*e038c9c4Sjoerg if (!CXXABI.empty()) {
4031*e038c9c4Sjoerg if (!TargetCXXABI::isABI(CXXABI)) {
4032*e038c9c4Sjoerg Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4033*e038c9c4Sjoerg } else {
4034*e038c9c4Sjoerg auto Kind = TargetCXXABI::getKind(CXXABI);
4035*e038c9c4Sjoerg if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4036*e038c9c4Sjoerg Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4037*e038c9c4Sjoerg else
4038*e038c9c4Sjoerg Opts.CXXABI = Kind;
4039*e038c9c4Sjoerg }
4040*e038c9c4Sjoerg }
4041*e038c9c4Sjoerg
4042*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
40437330f729Sjoerg }
40447330f729Sjoerg
isStrictlyPreprocessorAction(frontend::ActionKind Action)40457330f729Sjoerg static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
40467330f729Sjoerg switch (Action) {
40477330f729Sjoerg case frontend::ASTDeclList:
40487330f729Sjoerg case frontend::ASTDump:
40497330f729Sjoerg case frontend::ASTPrint:
40507330f729Sjoerg case frontend::ASTView:
40517330f729Sjoerg case frontend::EmitAssembly:
40527330f729Sjoerg case frontend::EmitBC:
40537330f729Sjoerg case frontend::EmitHTML:
40547330f729Sjoerg case frontend::EmitLLVM:
40557330f729Sjoerg case frontend::EmitLLVMOnly:
40567330f729Sjoerg case frontend::EmitCodeGenOnly:
40577330f729Sjoerg case frontend::EmitObj:
40587330f729Sjoerg case frontend::FixIt:
40597330f729Sjoerg case frontend::GenerateModule:
40607330f729Sjoerg case frontend::GenerateModuleInterface:
40617330f729Sjoerg case frontend::GenerateHeaderModule:
40627330f729Sjoerg case frontend::GeneratePCH:
4063*e038c9c4Sjoerg case frontend::GenerateInterfaceStubs:
40647330f729Sjoerg case frontend::ParseSyntaxOnly:
40657330f729Sjoerg case frontend::ModuleFileInfo:
40667330f729Sjoerg case frontend::VerifyPCH:
40677330f729Sjoerg case frontend::PluginAction:
40687330f729Sjoerg case frontend::RewriteObjC:
40697330f729Sjoerg case frontend::RewriteTest:
40707330f729Sjoerg case frontend::RunAnalysis:
40717330f729Sjoerg case frontend::TemplightDump:
40727330f729Sjoerg case frontend::MigrateSource:
40737330f729Sjoerg return false;
40747330f729Sjoerg
40757330f729Sjoerg case frontend::DumpCompilerOptions:
40767330f729Sjoerg case frontend::DumpRawTokens:
40777330f729Sjoerg case frontend::DumpTokens:
40787330f729Sjoerg case frontend::InitOnly:
40797330f729Sjoerg case frontend::PrintPreamble:
40807330f729Sjoerg case frontend::PrintPreprocessedInput:
40817330f729Sjoerg case frontend::RewriteMacros:
40827330f729Sjoerg case frontend::RunPreprocessorOnly:
40837330f729Sjoerg case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
40847330f729Sjoerg return true;
40857330f729Sjoerg }
40867330f729Sjoerg llvm_unreachable("invalid frontend action");
40877330f729Sjoerg }
40887330f729Sjoerg
GeneratePreprocessorArgs(PreprocessorOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,const LangOptions & LangOpts,const FrontendOptions & FrontendOpts,const CodeGenOptions & CodeGenOpts)4089*e038c9c4Sjoerg static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
4090*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
4091*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA,
4092*e038c9c4Sjoerg const LangOptions &LangOpts,
4093*e038c9c4Sjoerg const FrontendOptions &FrontendOpts,
4094*e038c9c4Sjoerg const CodeGenOptions &CodeGenOpts) {
4095*e038c9c4Sjoerg PreprocessorOptions *PreprocessorOpts = &Opts;
4096*e038c9c4Sjoerg
4097*e038c9c4Sjoerg #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
4098*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4099*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4100*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4101*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
4102*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
4103*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4104*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4105*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
4106*e038c9c4Sjoerg #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4107*e038c9c4Sjoerg
4108*e038c9c4Sjoerg if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4109*e038c9c4Sjoerg GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
4110*e038c9c4Sjoerg
4111*e038c9c4Sjoerg for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4112*e038c9c4Sjoerg GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
4113*e038c9c4Sjoerg
4114*e038c9c4Sjoerg for (const auto &MP : Opts.MacroPrefixMap)
4115*e038c9c4Sjoerg GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
4116*e038c9c4Sjoerg
4117*e038c9c4Sjoerg if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4118*e038c9c4Sjoerg GenerateArg(Args, OPT_preamble_bytes_EQ,
4119*e038c9c4Sjoerg Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4120*e038c9c4Sjoerg (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
4121*e038c9c4Sjoerg SA);
4122*e038c9c4Sjoerg
4123*e038c9c4Sjoerg for (const auto &M : Opts.Macros) {
4124*e038c9c4Sjoerg // Don't generate __CET__ macro definitions. They are implied by the
4125*e038c9c4Sjoerg // -fcf-protection option that is generated elsewhere.
4126*e038c9c4Sjoerg if (M.first == "__CET__=1" && !M.second &&
4127*e038c9c4Sjoerg !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4128*e038c9c4Sjoerg continue;
4129*e038c9c4Sjoerg if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4130*e038c9c4Sjoerg !CodeGenOpts.CFProtectionBranch)
4131*e038c9c4Sjoerg continue;
4132*e038c9c4Sjoerg if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4133*e038c9c4Sjoerg CodeGenOpts.CFProtectionBranch)
4134*e038c9c4Sjoerg continue;
4135*e038c9c4Sjoerg
4136*e038c9c4Sjoerg GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
4137*e038c9c4Sjoerg }
4138*e038c9c4Sjoerg
4139*e038c9c4Sjoerg for (const auto &I : Opts.Includes) {
4140*e038c9c4Sjoerg // Don't generate OpenCL includes. They are implied by other flags that are
4141*e038c9c4Sjoerg // generated elsewhere.
4142*e038c9c4Sjoerg if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4143*e038c9c4Sjoerg ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4144*e038c9c4Sjoerg I == "opencl-c.h"))
4145*e038c9c4Sjoerg continue;
4146*e038c9c4Sjoerg
4147*e038c9c4Sjoerg GenerateArg(Args, OPT_include, I, SA);
4148*e038c9c4Sjoerg }
4149*e038c9c4Sjoerg
4150*e038c9c4Sjoerg for (const auto &CI : Opts.ChainedIncludes)
4151*e038c9c4Sjoerg GenerateArg(Args, OPT_chain_include, CI, SA);
4152*e038c9c4Sjoerg
4153*e038c9c4Sjoerg for (const auto &RF : Opts.RemappedFiles)
4154*e038c9c4Sjoerg GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
4155*e038c9c4Sjoerg
4156*e038c9c4Sjoerg // Don't handle LexEditorPlaceholders. It is implied by the action that is
4157*e038c9c4Sjoerg // generated elsewhere.
4158*e038c9c4Sjoerg }
4159*e038c9c4Sjoerg
ParsePreprocessorArgs(PreprocessorOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action,const FrontendOptions & FrontendOpts)4160*e038c9c4Sjoerg static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
41617330f729Sjoerg DiagnosticsEngine &Diags,
4162*e038c9c4Sjoerg frontend::ActionKind Action,
4163*e038c9c4Sjoerg const FrontendOptions &FrontendOpts) {
4164*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
4165*e038c9c4Sjoerg
4166*e038c9c4Sjoerg PreprocessorOptions *PreprocessorOpts = &Opts;
4167*e038c9c4Sjoerg
4168*e038c9c4Sjoerg #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
4169*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4170*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4171*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4172*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
4173*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
4174*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4175*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4176*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
4177*e038c9c4Sjoerg #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4178*e038c9c4Sjoerg
41797330f729Sjoerg Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
41807330f729Sjoerg Args.hasArg(OPT_pch_through_hdrstop_use);
41817330f729Sjoerg
41827330f729Sjoerg for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
41837330f729Sjoerg Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
41847330f729Sjoerg
4185*e038c9c4Sjoerg for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4186*e038c9c4Sjoerg auto Split = StringRef(A).split('=');
4187*e038c9c4Sjoerg Opts.MacroPrefixMap.insert(
4188*e038c9c4Sjoerg {std::string(Split.first), std::string(Split.second)});
4189*e038c9c4Sjoerg }
4190*e038c9c4Sjoerg
41917330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
41927330f729Sjoerg StringRef Value(A->getValue());
41937330f729Sjoerg size_t Comma = Value.find(',');
41947330f729Sjoerg unsigned Bytes = 0;
41957330f729Sjoerg unsigned EndOfLine = 0;
41967330f729Sjoerg
41977330f729Sjoerg if (Comma == StringRef::npos ||
41987330f729Sjoerg Value.substr(0, Comma).getAsInteger(10, Bytes) ||
41997330f729Sjoerg Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
42007330f729Sjoerg Diags.Report(diag::err_drv_preamble_format);
42017330f729Sjoerg else {
42027330f729Sjoerg Opts.PrecompiledPreambleBytes.first = Bytes;
42037330f729Sjoerg Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
42047330f729Sjoerg }
42057330f729Sjoerg }
42067330f729Sjoerg
42077330f729Sjoerg // Add the __CET__ macro if a CFProtection option is set.
42087330f729Sjoerg if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
42097330f729Sjoerg StringRef Name = A->getValue();
42107330f729Sjoerg if (Name == "branch")
42117330f729Sjoerg Opts.addMacroDef("__CET__=1");
42127330f729Sjoerg else if (Name == "return")
42137330f729Sjoerg Opts.addMacroDef("__CET__=2");
42147330f729Sjoerg else if (Name == "full")
42157330f729Sjoerg Opts.addMacroDef("__CET__=3");
42167330f729Sjoerg }
42177330f729Sjoerg
42187330f729Sjoerg // Add macros from the command line.
42197330f729Sjoerg for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
42207330f729Sjoerg if (A->getOption().matches(OPT_D))
42217330f729Sjoerg Opts.addMacroDef(A->getValue());
42227330f729Sjoerg else
42237330f729Sjoerg Opts.addMacroUndef(A->getValue());
42247330f729Sjoerg }
42257330f729Sjoerg
42267330f729Sjoerg // Add the ordered list of -includes.
42277330f729Sjoerg for (const auto *A : Args.filtered(OPT_include))
42287330f729Sjoerg Opts.Includes.emplace_back(A->getValue());
42297330f729Sjoerg
42307330f729Sjoerg for (const auto *A : Args.filtered(OPT_chain_include))
42317330f729Sjoerg Opts.ChainedIncludes.emplace_back(A->getValue());
42327330f729Sjoerg
42337330f729Sjoerg for (const auto *A : Args.filtered(OPT_remap_file)) {
42347330f729Sjoerg std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
42357330f729Sjoerg
42367330f729Sjoerg if (Split.second.empty()) {
42377330f729Sjoerg Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
42387330f729Sjoerg continue;
42397330f729Sjoerg }
42407330f729Sjoerg
42417330f729Sjoerg Opts.addRemappedFile(Split.first, Split.second);
42427330f729Sjoerg }
42437330f729Sjoerg
42447330f729Sjoerg // Always avoid lexing editor placeholders when we're just running the
42457330f729Sjoerg // preprocessor as we never want to emit the
42467330f729Sjoerg // "editor placeholder in source file" error in PP only mode.
42477330f729Sjoerg if (isStrictlyPreprocessorAction(Action))
42487330f729Sjoerg Opts.LexEditorPlaceholders = false;
42497330f729Sjoerg
4250*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
42517330f729Sjoerg }
42527330f729Sjoerg
GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA,frontend::ActionKind Action)4253*e038c9c4Sjoerg static void GeneratePreprocessorOutputArgs(
4254*e038c9c4Sjoerg const PreprocessorOutputOptions &Opts, SmallVectorImpl<const char *> &Args,
4255*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
4256*e038c9c4Sjoerg const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4257*e038c9c4Sjoerg
4258*e038c9c4Sjoerg #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
4259*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4260*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4261*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4262*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
4263*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
4264*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4265*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4266*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
4267*e038c9c4Sjoerg #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4268*e038c9c4Sjoerg
4269*e038c9c4Sjoerg bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4270*e038c9c4Sjoerg if (Generate_dM)
4271*e038c9c4Sjoerg GenerateArg(Args, OPT_dM, SA);
4272*e038c9c4Sjoerg if (!Generate_dM && Opts.ShowMacros)
4273*e038c9c4Sjoerg GenerateArg(Args, OPT_dD, SA);
4274*e038c9c4Sjoerg }
4275*e038c9c4Sjoerg
ParsePreprocessorOutputArgs(PreprocessorOutputOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action)4276*e038c9c4Sjoerg static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4277*e038c9c4Sjoerg ArgList &Args, DiagnosticsEngine &Diags,
42787330f729Sjoerg frontend::ActionKind Action) {
4279*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
42807330f729Sjoerg
4281*e038c9c4Sjoerg PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4282*e038c9c4Sjoerg
4283*e038c9c4Sjoerg #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
4284*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4285*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4286*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4287*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
4288*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
4289*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4290*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4291*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
4292*e038c9c4Sjoerg #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4293*e038c9c4Sjoerg
4294*e038c9c4Sjoerg Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
42957330f729Sjoerg Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4296*e038c9c4Sjoerg
4297*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
42987330f729Sjoerg }
42997330f729Sjoerg
GenerateTargetArgs(const TargetOptions & Opts,SmallVectorImpl<const char * > & Args,CompilerInvocation::StringAllocator SA)4300*e038c9c4Sjoerg static void GenerateTargetArgs(const TargetOptions &Opts,
4301*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args,
4302*e038c9c4Sjoerg CompilerInvocation::StringAllocator SA) {
4303*e038c9c4Sjoerg const TargetOptions *TargetOpts = &Opts;
4304*e038c9c4Sjoerg #define TARGET_OPTION_WITH_MARSHALLING( \
4305*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4306*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4307*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4308*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
4309*e038c9c4Sjoerg GENERATE_OPTION_WITH_MARSHALLING( \
4310*e038c9c4Sjoerg Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4311*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4312*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
4313*e038c9c4Sjoerg #undef TARGET_OPTION_WITH_MARSHALLING
4314*e038c9c4Sjoerg
4315*e038c9c4Sjoerg if (!Opts.SDKVersion.empty())
4316*e038c9c4Sjoerg GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
4317*e038c9c4Sjoerg SA);
43187330f729Sjoerg }
4319*e038c9c4Sjoerg
ParseTargetArgs(TargetOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)4320*e038c9c4Sjoerg static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4321*e038c9c4Sjoerg DiagnosticsEngine &Diags) {
4322*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
4323*e038c9c4Sjoerg
4324*e038c9c4Sjoerg TargetOptions *TargetOpts = &Opts;
4325*e038c9c4Sjoerg
4326*e038c9c4Sjoerg #define TARGET_OPTION_WITH_MARSHALLING( \
4327*e038c9c4Sjoerg PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4328*e038c9c4Sjoerg HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4329*e038c9c4Sjoerg DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4330*e038c9c4Sjoerg MERGER, EXTRACTOR, TABLE_INDEX) \
4331*e038c9c4Sjoerg PARSE_OPTION_WITH_MARSHALLING( \
4332*e038c9c4Sjoerg Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4333*e038c9c4Sjoerg IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4334*e038c9c4Sjoerg #include "clang/Driver/Options.inc"
4335*e038c9c4Sjoerg #undef TARGET_OPTION_WITH_MARSHALLING
4336*e038c9c4Sjoerg
43377330f729Sjoerg if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
43387330f729Sjoerg llvm::VersionTuple Version;
43397330f729Sjoerg if (Version.tryParse(A->getValue()))
43407330f729Sjoerg Diags.Report(diag::err_drv_invalid_value)
43417330f729Sjoerg << A->getAsString(Args) << A->getValue();
43427330f729Sjoerg else
43437330f729Sjoerg Opts.SDKVersion = Version;
43447330f729Sjoerg }
4345*e038c9c4Sjoerg
4346*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
43477330f729Sjoerg }
43487330f729Sjoerg
CreateFromArgsImpl(CompilerInvocation & Res,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0)4349*e038c9c4Sjoerg bool CompilerInvocation::CreateFromArgsImpl(
4350*e038c9c4Sjoerg CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4351*e038c9c4Sjoerg DiagnosticsEngine &Diags, const char *Argv0) {
4352*e038c9c4Sjoerg unsigned NumErrorsBefore = Diags.getNumErrors();
43537330f729Sjoerg
43547330f729Sjoerg // Parse the arguments.
43557330f729Sjoerg const OptTable &Opts = getDriverOptTable();
43567330f729Sjoerg const unsigned IncludedFlagsBitmask = options::CC1Option;
43577330f729Sjoerg unsigned MissingArgIndex, MissingArgCount;
43587330f729Sjoerg InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
43597330f729Sjoerg MissingArgCount, IncludedFlagsBitmask);
43607330f729Sjoerg LangOptions &LangOpts = *Res.getLangOpts();
43617330f729Sjoerg
43627330f729Sjoerg // Check for missing argument error.
4363*e038c9c4Sjoerg if (MissingArgCount)
43647330f729Sjoerg Diags.Report(diag::err_drv_missing_argument)
43657330f729Sjoerg << Args.getArgString(MissingArgIndex) << MissingArgCount;
43667330f729Sjoerg
43677330f729Sjoerg // Issue errors on unknown arguments.
43687330f729Sjoerg for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
43697330f729Sjoerg auto ArgString = A->getAsString(Args);
43707330f729Sjoerg std::string Nearest;
43717330f729Sjoerg if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
43727330f729Sjoerg Diags.Report(diag::err_drv_unknown_argument) << ArgString;
43737330f729Sjoerg else
43747330f729Sjoerg Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
43757330f729Sjoerg << ArgString << Nearest;
43767330f729Sjoerg }
43777330f729Sjoerg
4378*e038c9c4Sjoerg ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4379*e038c9c4Sjoerg ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4380*e038c9c4Sjoerg ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
43817330f729Sjoerg ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4382*e038c9c4Sjoerg /*DefaultDiagColor=*/false);
4383*e038c9c4Sjoerg ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
43847330f729Sjoerg // FIXME: We shouldn't have to pass the DashX option around here
4385*e038c9c4Sjoerg InputKind DashX = Res.getFrontendOpts().DashX;
43867330f729Sjoerg ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
43877330f729Sjoerg llvm::Triple T(Res.getTargetOpts().Triple);
4388*e038c9c4Sjoerg ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4389*e038c9c4Sjoerg Res.getFileSystemOpts().WorkingDir);
4390*e038c9c4Sjoerg
4391*e038c9c4Sjoerg ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4392*e038c9c4Sjoerg Diags);
43937330f729Sjoerg if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
43947330f729Sjoerg LangOpts.ObjCExceptions = 1;
43957330f729Sjoerg
43967330f729Sjoerg if (LangOpts.CUDA) {
43977330f729Sjoerg // During CUDA device-side compilation, the aux triple is the
43987330f729Sjoerg // triple used for host compilation.
43997330f729Sjoerg if (LangOpts.CUDAIsDevice)
44007330f729Sjoerg Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
44017330f729Sjoerg }
44027330f729Sjoerg
44037330f729Sjoerg // Set the triple of the host for OpenMP device compile.
44047330f729Sjoerg if (LangOpts.OpenMPIsDevice)
44057330f729Sjoerg Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
44067330f729Sjoerg
4407*e038c9c4Sjoerg ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4408*e038c9c4Sjoerg Res.getFrontendOpts().OutputFile, LangOpts);
4409*e038c9c4Sjoerg
44107330f729Sjoerg // FIXME: Override value name discarding when asan or msan is used because the
44117330f729Sjoerg // backend passes depend on the name of the alloca in order to print out
44127330f729Sjoerg // names.
44137330f729Sjoerg Res.getCodeGenOpts().DiscardValueNames &=
44147330f729Sjoerg !LangOpts.Sanitize.has(SanitizerKind::Address) &&
44157330f729Sjoerg !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
44167330f729Sjoerg !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
44177330f729Sjoerg !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
44187330f729Sjoerg
44197330f729Sjoerg ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4420*e038c9c4Sjoerg Res.getFrontendOpts().ProgramAction,
4421*e038c9c4Sjoerg Res.getFrontendOpts());
4422*e038c9c4Sjoerg ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
44237330f729Sjoerg Res.getFrontendOpts().ProgramAction);
44247330f729Sjoerg
4425*e038c9c4Sjoerg ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
4426*e038c9c4Sjoerg Res.getFrontendOpts().ProgramAction,
4427*e038c9c4Sjoerg Res.getPreprocessorOutputOpts().ShowLineMarkers);
4428*e038c9c4Sjoerg if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4429*e038c9c4Sjoerg Res.getDependencyOutputOpts().Targets.empty())
4430*e038c9c4Sjoerg Diags.Report(diag::err_fe_dependency_file_requires_MT);
44317330f729Sjoerg
44327330f729Sjoerg // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
44337330f729Sjoerg if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
44347330f729Sjoerg !Res.getLangOpts()->Sanitize.empty()) {
44357330f729Sjoerg Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
44367330f729Sjoerg Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
44377330f729Sjoerg }
4438*e038c9c4Sjoerg
4439*e038c9c4Sjoerg // Store the command-line for using in the CodeView backend.
4440*e038c9c4Sjoerg Res.getCodeGenOpts().Argv0 = Argv0;
4441*e038c9c4Sjoerg Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs;
4442*e038c9c4Sjoerg
4443*e038c9c4Sjoerg FixupInvocation(Res, Diags, Args, DashX);
4444*e038c9c4Sjoerg
4445*e038c9c4Sjoerg return Diags.getNumErrors() == NumErrorsBefore;
4446*e038c9c4Sjoerg }
4447*e038c9c4Sjoerg
CreateFromArgs(CompilerInvocation & Invocation,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0)4448*e038c9c4Sjoerg bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
4449*e038c9c4Sjoerg ArrayRef<const char *> CommandLineArgs,
4450*e038c9c4Sjoerg DiagnosticsEngine &Diags,
4451*e038c9c4Sjoerg const char *Argv0) {
4452*e038c9c4Sjoerg CompilerInvocation DummyInvocation;
4453*e038c9c4Sjoerg
4454*e038c9c4Sjoerg return RoundTrip(
4455*e038c9c4Sjoerg [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4456*e038c9c4Sjoerg DiagnosticsEngine &Diags, const char *Argv0) {
4457*e038c9c4Sjoerg return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4458*e038c9c4Sjoerg },
4459*e038c9c4Sjoerg [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4460*e038c9c4Sjoerg StringAllocator SA) { Invocation.generateCC1CommandLine(Args, SA); },
4461*e038c9c4Sjoerg Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
44627330f729Sjoerg }
44637330f729Sjoerg
getModuleHash() const44647330f729Sjoerg std::string CompilerInvocation::getModuleHash() const {
44657330f729Sjoerg // Note: For QoI reasons, the things we use as a hash here should all be
44667330f729Sjoerg // dumped via the -module-info flag.
44677330f729Sjoerg using llvm::hash_code;
44687330f729Sjoerg using llvm::hash_value;
44697330f729Sjoerg using llvm::hash_combine;
44707330f729Sjoerg using llvm::hash_combine_range;
44717330f729Sjoerg
44727330f729Sjoerg // Start the signature with the compiler version.
44737330f729Sjoerg // FIXME: We'd rather use something more cryptographically sound than
44747330f729Sjoerg // CityHash, but this will do for now.
44757330f729Sjoerg hash_code code = hash_value(getClangFullRepositoryVersion());
44767330f729Sjoerg
4477*e038c9c4Sjoerg // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4478*e038c9c4Sjoerg // and getClangFullRepositoryVersion() doesn't include git revision.
4479*e038c9c4Sjoerg code = hash_combine(code, serialization::VERSION_MAJOR,
4480*e038c9c4Sjoerg serialization::VERSION_MINOR);
4481*e038c9c4Sjoerg
44827330f729Sjoerg // Extend the signature with the language options
44837330f729Sjoerg #define LANGOPT(Name, Bits, Default, Description) \
44847330f729Sjoerg code = hash_combine(code, LangOpts->Name);
44857330f729Sjoerg #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
44867330f729Sjoerg code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
44877330f729Sjoerg #define BENIGN_LANGOPT(Name, Bits, Default, Description)
44887330f729Sjoerg #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
44897330f729Sjoerg #include "clang/Basic/LangOptions.def"
44907330f729Sjoerg
44917330f729Sjoerg for (StringRef Feature : LangOpts->ModuleFeatures)
44927330f729Sjoerg code = hash_combine(code, Feature);
44937330f729Sjoerg
4494*e038c9c4Sjoerg code = hash_combine(code, LangOpts->ObjCRuntime);
4495*e038c9c4Sjoerg const auto &BCN = LangOpts->CommentOpts.BlockCommandNames;
4496*e038c9c4Sjoerg code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end()));
4497*e038c9c4Sjoerg
44987330f729Sjoerg // Extend the signature with the target options.
44997330f729Sjoerg code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
4500*e038c9c4Sjoerg TargetOpts->TuneCPU, TargetOpts->ABI);
45017330f729Sjoerg for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
45027330f729Sjoerg code = hash_combine(code, FeatureAsWritten);
45037330f729Sjoerg
45047330f729Sjoerg // Extend the signature with preprocessor options.
45057330f729Sjoerg const PreprocessorOptions &ppOpts = getPreprocessorOpts();
45067330f729Sjoerg const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
45077330f729Sjoerg code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
45087330f729Sjoerg
45097330f729Sjoerg for (const auto &I : getPreprocessorOpts().Macros) {
45107330f729Sjoerg // If we're supposed to ignore this macro for the purposes of modules,
45117330f729Sjoerg // don't put it into the hash.
45127330f729Sjoerg if (!hsOpts.ModulesIgnoreMacros.empty()) {
45137330f729Sjoerg // Check whether we're ignoring this macro.
45147330f729Sjoerg StringRef MacroDef = I.first;
45157330f729Sjoerg if (hsOpts.ModulesIgnoreMacros.count(
45167330f729Sjoerg llvm::CachedHashString(MacroDef.split('=').first)))
45177330f729Sjoerg continue;
45187330f729Sjoerg }
45197330f729Sjoerg
45207330f729Sjoerg code = hash_combine(code, I.first, I.second);
45217330f729Sjoerg }
45227330f729Sjoerg
45237330f729Sjoerg // Extend the signature with the sysroot and other header search options.
45247330f729Sjoerg code = hash_combine(code, hsOpts.Sysroot,
45257330f729Sjoerg hsOpts.ModuleFormat,
45267330f729Sjoerg hsOpts.UseDebugInfo,
45277330f729Sjoerg hsOpts.UseBuiltinIncludes,
45287330f729Sjoerg hsOpts.UseStandardSystemIncludes,
45297330f729Sjoerg hsOpts.UseStandardCXXIncludes,
45307330f729Sjoerg hsOpts.UseLibcxx,
45317330f729Sjoerg hsOpts.ModulesValidateDiagnosticOptions);
45327330f729Sjoerg code = hash_combine(code, hsOpts.ResourceDir);
45337330f729Sjoerg
45347330f729Sjoerg if (hsOpts.ModulesStrictContextHash) {
45357330f729Sjoerg hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
45367330f729Sjoerg hsOpts.SystemHeaderPrefixes.end());
45377330f729Sjoerg hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
45387330f729Sjoerg hsOpts.UserEntries.end());
45397330f729Sjoerg code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
45407330f729Sjoerg hsOpts.UserEntries.size(), UEC);
45417330f729Sjoerg
45427330f729Sjoerg const DiagnosticOptions &diagOpts = getDiagnosticOpts();
45437330f729Sjoerg #define DIAGOPT(Name, Bits, Default) \
45447330f729Sjoerg code = hash_combine(code, diagOpts.Name);
45457330f729Sjoerg #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
45467330f729Sjoerg code = hash_combine(code, diagOpts.get##Name());
45477330f729Sjoerg #include "clang/Basic/DiagnosticOptions.def"
45487330f729Sjoerg #undef DIAGOPT
45497330f729Sjoerg #undef ENUM_DIAGOPT
45507330f729Sjoerg }
45517330f729Sjoerg
45527330f729Sjoerg // Extend the signature with the user build path.
45537330f729Sjoerg code = hash_combine(code, hsOpts.ModuleUserBuildPath);
45547330f729Sjoerg
45557330f729Sjoerg // Extend the signature with the module file extensions.
45567330f729Sjoerg const FrontendOptions &frontendOpts = getFrontendOpts();
45577330f729Sjoerg for (const auto &ext : frontendOpts.ModuleFileExtensions) {
45587330f729Sjoerg code = ext->hashExtension(code);
45597330f729Sjoerg }
45607330f729Sjoerg
45617330f729Sjoerg // When compiling with -gmodules, also hash -fdebug-prefix-map as it
45627330f729Sjoerg // affects the debug info in the PCM.
45637330f729Sjoerg if (getCodeGenOpts().DebugTypeExtRefs)
45647330f729Sjoerg for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
45657330f729Sjoerg code = hash_combine(code, KeyValue.first, KeyValue.second);
45667330f729Sjoerg
45677330f729Sjoerg // Extend the signature with the enabled sanitizers, if at least one is
45687330f729Sjoerg // enabled. Sanitizers which cannot affect AST generation aren't hashed.
45697330f729Sjoerg SanitizerSet SanHash = LangOpts->Sanitize;
45707330f729Sjoerg SanHash.clear(getPPTransparentSanitizers());
45717330f729Sjoerg if (!SanHash.empty())
45727330f729Sjoerg code = hash_combine(code, SanHash.Mask);
45737330f729Sjoerg
45747330f729Sjoerg return llvm::APInt(64, code).toString(36, /*Signed=*/false);
45757330f729Sjoerg }
45767330f729Sjoerg
generateCC1CommandLine(SmallVectorImpl<const char * > & Args,StringAllocator SA) const4577*e038c9c4Sjoerg void CompilerInvocation::generateCC1CommandLine(
4578*e038c9c4Sjoerg SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
4579*e038c9c4Sjoerg llvm::Triple T(TargetOpts->Triple);
45807330f729Sjoerg
4581*e038c9c4Sjoerg GenerateFileSystemArgs(FileSystemOpts, Args, SA);
4582*e038c9c4Sjoerg GenerateMigratorArgs(MigratorOpts, Args, SA);
4583*e038c9c4Sjoerg GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
4584*e038c9c4Sjoerg GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
4585*e038c9c4Sjoerg GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
4586*e038c9c4Sjoerg GenerateTargetArgs(*TargetOpts, Args, SA);
4587*e038c9c4Sjoerg GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
4588*e038c9c4Sjoerg GenerateLangArgs(*LangOpts, Args, SA, T, FrontendOpts.DashX);
4589*e038c9c4Sjoerg GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
4590*e038c9c4Sjoerg &*LangOpts);
4591*e038c9c4Sjoerg GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts, FrontendOpts,
4592*e038c9c4Sjoerg CodeGenOpts);
4593*e038c9c4Sjoerg GeneratePreprocessorOutputArgs(PreprocessorOutputOpts, Args, SA,
4594*e038c9c4Sjoerg FrontendOpts.ProgramAction);
4595*e038c9c4Sjoerg GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
45967330f729Sjoerg }
45977330f729Sjoerg
45987330f729Sjoerg IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags)4599*e038c9c4Sjoerg clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
46007330f729Sjoerg DiagnosticsEngine &Diags) {
46017330f729Sjoerg return createVFSFromCompilerInvocation(CI, Diags,
46027330f729Sjoerg llvm::vfs::getRealFileSystem());
46037330f729Sjoerg }
46047330f729Sjoerg
4605*e038c9c4Sjoerg IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags,IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)4606*e038c9c4Sjoerg clang::createVFSFromCompilerInvocation(
46077330f729Sjoerg const CompilerInvocation &CI, DiagnosticsEngine &Diags,
46087330f729Sjoerg IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
46097330f729Sjoerg if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
46107330f729Sjoerg return BaseFS;
46117330f729Sjoerg
46127330f729Sjoerg IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
46137330f729Sjoerg // earlier vfs files are on the bottom
46147330f729Sjoerg for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
46157330f729Sjoerg llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
46167330f729Sjoerg Result->getBufferForFile(File);
46177330f729Sjoerg if (!Buffer) {
46187330f729Sjoerg Diags.Report(diag::err_missing_vfs_overlay_file) << File;
46197330f729Sjoerg continue;
46207330f729Sjoerg }
46217330f729Sjoerg
46227330f729Sjoerg IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
46237330f729Sjoerg std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
46247330f729Sjoerg /*DiagContext*/ nullptr, Result);
46257330f729Sjoerg if (!FS) {
46267330f729Sjoerg Diags.Report(diag::err_invalid_vfs_overlay) << File;
46277330f729Sjoerg continue;
46287330f729Sjoerg }
46297330f729Sjoerg
46307330f729Sjoerg Result = FS;
46317330f729Sjoerg }
46327330f729Sjoerg return Result;
46337330f729Sjoerg }
4634