10b57cec5SDimitry Andric //===- CompilerInvocation.cpp ---------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric
90b57cec5SDimitry Andric #include "clang/Frontend/CompilerInvocation.h"
100b57cec5SDimitry Andric #include "TestModuleFileExtension.h"
110b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
120b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
130b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
140b57cec5SDimitry Andric #include "clang/Basic/CommentOptions.h"
150b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
16e8d8bef9SDimitry Andric #include "clang/Basic/DiagnosticDriver.h"
170b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.h"
180b57cec5SDimitry Andric #include "clang/Basic/FileSystemOptions.h"
190b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
200b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
21a7dea167SDimitry Andric #include "clang/Basic/LangStandard.h"
220b57cec5SDimitry Andric #include "clang/Basic/ObjCRuntime.h"
230b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.h"
240b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
250b57cec5SDimitry Andric #include "clang/Basic/TargetOptions.h"
260b57cec5SDimitry Andric #include "clang/Basic/Version.h"
270b57cec5SDimitry Andric #include "clang/Basic/Visibility.h"
280b57cec5SDimitry Andric #include "clang/Basic/XRayInstr.h"
290b57cec5SDimitry Andric #include "clang/Config/config.h"
300b57cec5SDimitry Andric #include "clang/Driver/Driver.h"
310b57cec5SDimitry Andric #include "clang/Driver/DriverDiagnostic.h"
320b57cec5SDimitry Andric #include "clang/Driver/Options.h"
330b57cec5SDimitry Andric #include "clang/Frontend/CommandLineSourceLoc.h"
340b57cec5SDimitry Andric #include "clang/Frontend/DependencyOutputOptions.h"
350b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
360b57cec5SDimitry Andric #include "clang/Frontend/FrontendOptions.h"
370b57cec5SDimitry Andric #include "clang/Frontend/FrontendPluginRegistry.h"
380b57cec5SDimitry Andric #include "clang/Frontend/MigratorOptions.h"
390b57cec5SDimitry Andric #include "clang/Frontend/PreprocessorOutputOptions.h"
40fe6060f1SDimitry Andric #include "clang/Frontend/TextDiagnosticBuffer.h"
410b57cec5SDimitry Andric #include "clang/Frontend/Utils.h"
420b57cec5SDimitry Andric #include "clang/Lex/HeaderSearchOptions.h"
430b57cec5SDimitry Andric #include "clang/Lex/PreprocessorOptions.h"
440b57cec5SDimitry Andric #include "clang/Sema/CodeCompleteOptions.h"
455ffd83dbSDimitry Andric #include "clang/Serialization/ASTBitCodes.h"
460b57cec5SDimitry Andric #include "clang/Serialization/ModuleFileExtension.h"
470b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
480b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
490b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
500b57cec5SDimitry Andric #include "llvm/ADT/CachedHashString.h"
515ffd83dbSDimitry Andric #include "llvm/ADT/FloatingPointMode.h"
520b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
53fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h"
540b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
550b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
560b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
570b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
580b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
59e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
60fe013be4SDimitry Andric #include "llvm/Frontend/Debug/Options.h"
610b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
620b57cec5SDimitry Andric #include "llvm/Linker/Linker.h"
630b57cec5SDimitry Andric #include "llvm/MC/MCTargetOptions.h"
640b57cec5SDimitry Andric #include "llvm/Option/Arg.h"
650b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
660b57cec5SDimitry Andric #include "llvm/Option/OptSpecifier.h"
670b57cec5SDimitry Andric #include "llvm/Option/OptTable.h"
680b57cec5SDimitry Andric #include "llvm/Option/Option.h"
690b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
70e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h"
710b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
720b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
730b57cec5SDimitry Andric #include "llvm/Support/Error.h"
740b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
750b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
760b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
77349cc55cSDimitry Andric #include "llvm/Support/HashBuilder.h"
780b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
790b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
800b57cec5SDimitry Andric #include "llvm/Support/Path.h"
810b57cec5SDimitry Andric #include "llvm/Support/Process.h"
820b57cec5SDimitry Andric #include "llvm/Support/Regex.h"
830b57cec5SDimitry Andric #include "llvm/Support/VersionTuple.h"
840b57cec5SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
850b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
860b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
87fe013be4SDimitry Andric #include "llvm/TargetParser/Host.h"
88fe013be4SDimitry Andric #include "llvm/TargetParser/Triple.h"
890b57cec5SDimitry Andric #include <algorithm>
900b57cec5SDimitry Andric #include <atomic>
910b57cec5SDimitry Andric #include <cassert>
920b57cec5SDimitry Andric #include <cstddef>
930b57cec5SDimitry Andric #include <cstring>
94bdd1243dSDimitry Andric #include <ctime>
9581ad6265SDimitry Andric #include <fstream>
96bdd1243dSDimitry Andric #include <limits>
970b57cec5SDimitry Andric #include <memory>
98bdd1243dSDimitry Andric #include <optional>
990b57cec5SDimitry Andric #include <string>
1000b57cec5SDimitry Andric #include <tuple>
101e8d8bef9SDimitry Andric #include <type_traits>
1020b57cec5SDimitry Andric #include <utility>
1030b57cec5SDimitry Andric #include <vector>
1040b57cec5SDimitry Andric
1050b57cec5SDimitry Andric using namespace clang;
1060b57cec5SDimitry Andric using namespace driver;
1070b57cec5SDimitry Andric using namespace options;
1080b57cec5SDimitry Andric using namespace llvm::opt;
1090b57cec5SDimitry Andric
1100b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11181ad6265SDimitry Andric // Helpers.
11281ad6265SDimitry Andric //===----------------------------------------------------------------------===//
11381ad6265SDimitry Andric
11481ad6265SDimitry Andric // Parse misexpect tolerance argument value.
11581ad6265SDimitry Andric // Valid option values are integers in the range [0, 100)
parseToleranceOption(StringRef Arg)116bdd1243dSDimitry Andric static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) {
117bdd1243dSDimitry Andric uint32_t Val;
11881ad6265SDimitry Andric if (Arg.getAsInteger(10, Val))
11981ad6265SDimitry Andric return llvm::createStringError(llvm::inconvertibleErrorCode(),
12081ad6265SDimitry Andric "Not an integer: %s", Arg.data());
12181ad6265SDimitry Andric return Val;
12281ad6265SDimitry Andric }
12381ad6265SDimitry Andric
12481ad6265SDimitry Andric //===----------------------------------------------------------------------===//
1250b57cec5SDimitry Andric // Initialization.
1260b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1270b57cec5SDimitry Andric
128c9157d92SDimitry Andric namespace {
make_shared_copy(const T & X)129c9157d92SDimitry Andric template <class T> std::shared_ptr<T> make_shared_copy(const T &X) {
130c9157d92SDimitry Andric return std::make_shared<T>(X);
131c9157d92SDimitry Andric }
1320b57cec5SDimitry Andric
133c9157d92SDimitry Andric template <class T>
makeIntrusiveRefCntCopy(const T & X)134c9157d92SDimitry Andric llvm::IntrusiveRefCntPtr<T> makeIntrusiveRefCntCopy(const T &X) {
135c9157d92SDimitry Andric return llvm::makeIntrusiveRefCnt<T>(X);
136c9157d92SDimitry Andric }
137c9157d92SDimitry Andric } // namespace
1380b57cec5SDimitry Andric
CompilerInvocationBase()139c9157d92SDimitry Andric CompilerInvocationBase::CompilerInvocationBase()
140c9157d92SDimitry Andric : LangOpts(std::make_shared<LangOptions>()),
141c9157d92SDimitry Andric TargetOpts(std::make_shared<TargetOptions>()),
142c9157d92SDimitry Andric DiagnosticOpts(llvm::makeIntrusiveRefCnt<DiagnosticOptions>()),
143c9157d92SDimitry Andric HSOpts(std::make_shared<HeaderSearchOptions>()),
144c9157d92SDimitry Andric PPOpts(std::make_shared<PreprocessorOptions>()),
145c9157d92SDimitry Andric AnalyzerOpts(llvm::makeIntrusiveRefCnt<AnalyzerOptions>()),
146c9157d92SDimitry Andric MigratorOpts(std::make_shared<MigratorOptions>()),
147c9157d92SDimitry Andric APINotesOpts(std::make_shared<APINotesOptions>()),
148c9157d92SDimitry Andric CodeGenOpts(std::make_shared<CodeGenOptions>()),
149c9157d92SDimitry Andric FSOpts(std::make_shared<FileSystemOptions>()),
150c9157d92SDimitry Andric FrontendOpts(std::make_shared<FrontendOptions>()),
151c9157d92SDimitry Andric DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()),
152c9157d92SDimitry Andric PreprocessorOutputOpts(std::make_shared<PreprocessorOutputOptions>()) {}
153fe6060f1SDimitry Andric
154c9157d92SDimitry Andric CompilerInvocationBase &
deep_copy_assign(const CompilerInvocationBase & X)155c9157d92SDimitry Andric CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) {
156c9157d92SDimitry Andric if (this != &X) {
157c9157d92SDimitry Andric LangOpts = make_shared_copy(X.getLangOpts());
158c9157d92SDimitry Andric TargetOpts = make_shared_copy(X.getTargetOpts());
159c9157d92SDimitry Andric DiagnosticOpts = makeIntrusiveRefCntCopy(X.getDiagnosticOpts());
160c9157d92SDimitry Andric HSOpts = make_shared_copy(X.getHeaderSearchOpts());
161c9157d92SDimitry Andric PPOpts = make_shared_copy(X.getPreprocessorOpts());
162c9157d92SDimitry Andric AnalyzerOpts = makeIntrusiveRefCntCopy(X.getAnalyzerOpts());
163c9157d92SDimitry Andric MigratorOpts = make_shared_copy(X.getMigratorOpts());
164c9157d92SDimitry Andric APINotesOpts = make_shared_copy(X.getAPINotesOpts());
165c9157d92SDimitry Andric CodeGenOpts = make_shared_copy(X.getCodeGenOpts());
166c9157d92SDimitry Andric FSOpts = make_shared_copy(X.getFileSystemOpts());
167c9157d92SDimitry Andric FrontendOpts = make_shared_copy(X.getFrontendOpts());
168c9157d92SDimitry Andric DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts());
169c9157d92SDimitry Andric PreprocessorOutputOpts = make_shared_copy(X.getPreprocessorOutputOpts());
170c9157d92SDimitry Andric }
171fe6060f1SDimitry Andric return *this;
172fe6060f1SDimitry Andric }
173fe6060f1SDimitry Andric
174c9157d92SDimitry Andric CompilerInvocationBase &
shallow_copy_assign(const CompilerInvocationBase & X)175c9157d92SDimitry Andric CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) {
176c9157d92SDimitry Andric if (this != &X) {
177c9157d92SDimitry Andric LangOpts = X.LangOpts;
178c9157d92SDimitry Andric TargetOpts = X.TargetOpts;
179c9157d92SDimitry Andric DiagnosticOpts = X.DiagnosticOpts;
180c9157d92SDimitry Andric HSOpts = X.HSOpts;
181c9157d92SDimitry Andric PPOpts = X.PPOpts;
182c9157d92SDimitry Andric AnalyzerOpts = X.AnalyzerOpts;
183c9157d92SDimitry Andric MigratorOpts = X.MigratorOpts;
184c9157d92SDimitry Andric APINotesOpts = X.APINotesOpts;
185c9157d92SDimitry Andric CodeGenOpts = X.CodeGenOpts;
186c9157d92SDimitry Andric FSOpts = X.FSOpts;
187c9157d92SDimitry Andric FrontendOpts = X.FrontendOpts;
188c9157d92SDimitry Andric DependencyOutputOpts = X.DependencyOutputOpts;
189c9157d92SDimitry Andric PreprocessorOutputOpts = X.PreprocessorOutputOpts;
190c9157d92SDimitry Andric }
191c9157d92SDimitry Andric return *this;
192c9157d92SDimitry Andric }
193fe6060f1SDimitry Andric
194c9157d92SDimitry Andric namespace {
195c9157d92SDimitry Andric template <typename T>
ensureOwned(std::shared_ptr<T> & Storage)196c9157d92SDimitry Andric T &ensureOwned(std::shared_ptr<T> &Storage) {
197c9157d92SDimitry Andric if (Storage.use_count() > 1)
198c9157d92SDimitry Andric Storage = std::make_shared<T>(*Storage);
199c9157d92SDimitry Andric return *Storage;
200c9157d92SDimitry Andric }
201c9157d92SDimitry Andric
202c9157d92SDimitry Andric template <typename T>
ensureOwned(llvm::IntrusiveRefCntPtr<T> & Storage)203c9157d92SDimitry Andric T &ensureOwned(llvm::IntrusiveRefCntPtr<T> &Storage) {
204c9157d92SDimitry Andric if (Storage.useCount() > 1)
205c9157d92SDimitry Andric Storage = llvm::makeIntrusiveRefCnt<T>(*Storage);
206c9157d92SDimitry Andric return *Storage;
207c9157d92SDimitry Andric }
208c9157d92SDimitry Andric } // namespace
209c9157d92SDimitry Andric
getMutLangOpts()210c9157d92SDimitry Andric LangOptions &CowCompilerInvocation::getMutLangOpts() {
211c9157d92SDimitry Andric return ensureOwned(LangOpts);
212c9157d92SDimitry Andric }
213c9157d92SDimitry Andric
getMutTargetOpts()214c9157d92SDimitry Andric TargetOptions &CowCompilerInvocation::getMutTargetOpts() {
215c9157d92SDimitry Andric return ensureOwned(TargetOpts);
216c9157d92SDimitry Andric }
217c9157d92SDimitry Andric
getMutDiagnosticOpts()218c9157d92SDimitry Andric DiagnosticOptions &CowCompilerInvocation::getMutDiagnosticOpts() {
219c9157d92SDimitry Andric return ensureOwned(DiagnosticOpts);
220c9157d92SDimitry Andric }
221c9157d92SDimitry Andric
getMutHeaderSearchOpts()222c9157d92SDimitry Andric HeaderSearchOptions &CowCompilerInvocation::getMutHeaderSearchOpts() {
223c9157d92SDimitry Andric return ensureOwned(HSOpts);
224c9157d92SDimitry Andric }
225c9157d92SDimitry Andric
getMutPreprocessorOpts()226c9157d92SDimitry Andric PreprocessorOptions &CowCompilerInvocation::getMutPreprocessorOpts() {
227c9157d92SDimitry Andric return ensureOwned(PPOpts);
228c9157d92SDimitry Andric }
229c9157d92SDimitry Andric
getMutAnalyzerOpts()230c9157d92SDimitry Andric AnalyzerOptions &CowCompilerInvocation::getMutAnalyzerOpts() {
231c9157d92SDimitry Andric return ensureOwned(AnalyzerOpts);
232c9157d92SDimitry Andric }
233c9157d92SDimitry Andric
getMutMigratorOpts()234c9157d92SDimitry Andric MigratorOptions &CowCompilerInvocation::getMutMigratorOpts() {
235c9157d92SDimitry Andric return ensureOwned(MigratorOpts);
236c9157d92SDimitry Andric }
237c9157d92SDimitry Andric
getMutAPINotesOpts()238c9157d92SDimitry Andric APINotesOptions &CowCompilerInvocation::getMutAPINotesOpts() {
239c9157d92SDimitry Andric return ensureOwned(APINotesOpts);
240c9157d92SDimitry Andric }
241c9157d92SDimitry Andric
getMutCodeGenOpts()242c9157d92SDimitry Andric CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() {
243c9157d92SDimitry Andric return ensureOwned(CodeGenOpts);
244c9157d92SDimitry Andric }
245c9157d92SDimitry Andric
getMutFileSystemOpts()246c9157d92SDimitry Andric FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() {
247c9157d92SDimitry Andric return ensureOwned(FSOpts);
248c9157d92SDimitry Andric }
249c9157d92SDimitry Andric
getMutFrontendOpts()250c9157d92SDimitry Andric FrontendOptions &CowCompilerInvocation::getMutFrontendOpts() {
251c9157d92SDimitry Andric return ensureOwned(FrontendOpts);
252c9157d92SDimitry Andric }
253c9157d92SDimitry Andric
getMutDependencyOutputOpts()254c9157d92SDimitry Andric DependencyOutputOptions &CowCompilerInvocation::getMutDependencyOutputOpts() {
255c9157d92SDimitry Andric return ensureOwned(DependencyOutputOpts);
256c9157d92SDimitry Andric }
257c9157d92SDimitry Andric
258c9157d92SDimitry Andric PreprocessorOutputOptions &
getMutPreprocessorOutputOpts()259c9157d92SDimitry Andric CowCompilerInvocation::getMutPreprocessorOutputOpts() {
260c9157d92SDimitry Andric return ensureOwned(PreprocessorOutputOpts);
261c9157d92SDimitry Andric }
2620b57cec5SDimitry Andric
2630b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2645ffd83dbSDimitry Andric // Normalizers
2655ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
2665ffd83dbSDimitry Andric
267c9157d92SDimitry Andric using ArgumentConsumer = CompilerInvocation::ArgumentConsumer;
268c9157d92SDimitry Andric
2695ffd83dbSDimitry Andric #define SIMPLE_ENUM_VALUE_TABLE
2705ffd83dbSDimitry Andric #include "clang/Driver/Options.inc"
2715ffd83dbSDimitry Andric #undef SIMPLE_ENUM_VALUE_TABLE
2725ffd83dbSDimitry Andric
normalizeSimpleFlag(OptSpecifier Opt,unsigned TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)273bdd1243dSDimitry Andric static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
274fe6060f1SDimitry Andric unsigned TableIndex,
275fe6060f1SDimitry Andric const ArgList &Args,
276fe6060f1SDimitry Andric DiagnosticsEngine &Diags) {
277e8d8bef9SDimitry Andric if (Args.hasArg(Opt))
278e8d8bef9SDimitry Andric return true;
279bdd1243dSDimitry Andric return std::nullopt;
280e8d8bef9SDimitry Andric }
281e8d8bef9SDimitry Andric
normalizeSimpleNegativeFlag(OptSpecifier Opt,unsigned,const ArgList & Args,DiagnosticsEngine &)282bdd1243dSDimitry Andric static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt,
283bdd1243dSDimitry Andric unsigned,
2845ffd83dbSDimitry Andric const ArgList &Args,
285fe6060f1SDimitry Andric DiagnosticsEngine &) {
286e8d8bef9SDimitry Andric if (Args.hasArg(Opt))
287e8d8bef9SDimitry Andric return false;
288bdd1243dSDimitry Andric return std::nullopt;
289e8d8bef9SDimitry Andric }
290e8d8bef9SDimitry Andric
291e8d8bef9SDimitry Andric /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
292e8d8bef9SDimitry Andric /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
293e8d8bef9SDimitry Andric /// unnecessary template instantiations and just ignore it with a variadic
294e8d8bef9SDimitry Andric /// argument.
denormalizeSimpleFlag(ArgumentConsumer Consumer,const Twine & Spelling,Option::OptionClass,unsigned,...)295c9157d92SDimitry Andric static void denormalizeSimpleFlag(ArgumentConsumer Consumer,
296c9157d92SDimitry Andric const Twine &Spelling, Option::OptionClass,
297c9157d92SDimitry Andric unsigned, /*T*/...) {
298c9157d92SDimitry Andric Consumer(Spelling);
299e8d8bef9SDimitry Andric }
300e8d8bef9SDimitry Andric
is_uint64_t_convertible()301e8d8bef9SDimitry Andric template <typename T> static constexpr bool is_uint64_t_convertible() {
302bdd1243dSDimitry Andric return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
303e8d8bef9SDimitry Andric }
304e8d8bef9SDimitry Andric
305e8d8bef9SDimitry Andric template <typename T,
306e8d8bef9SDimitry Andric std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
makeFlagToValueNormalizer(T Value)307e8d8bef9SDimitry Andric static auto makeFlagToValueNormalizer(T Value) {
308e8d8bef9SDimitry Andric return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
309bdd1243dSDimitry Andric DiagnosticsEngine &) -> std::optional<T> {
310e8d8bef9SDimitry Andric if (Args.hasArg(Opt))
311e8d8bef9SDimitry Andric return Value;
312bdd1243dSDimitry Andric return std::nullopt;
313e8d8bef9SDimitry Andric };
314e8d8bef9SDimitry Andric }
315e8d8bef9SDimitry Andric
316e8d8bef9SDimitry Andric template <typename T,
317e8d8bef9SDimitry Andric std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
makeFlagToValueNormalizer(T Value)318e8d8bef9SDimitry Andric static auto makeFlagToValueNormalizer(T Value) {
319e8d8bef9SDimitry Andric return makeFlagToValueNormalizer(uint64_t(Value));
320e8d8bef9SDimitry Andric }
321e8d8bef9SDimitry Andric
makeBooleanOptionNormalizer(bool Value,bool OtherValue,OptSpecifier OtherOpt)322e8d8bef9SDimitry Andric static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
323e8d8bef9SDimitry Andric OptSpecifier OtherOpt) {
324bdd1243dSDimitry Andric return [Value, OtherValue,
325bdd1243dSDimitry Andric OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args,
326bdd1243dSDimitry Andric DiagnosticsEngine &) -> std::optional<bool> {
327e8d8bef9SDimitry Andric if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
328e8d8bef9SDimitry Andric return A->getOption().matches(Opt) ? Value : OtherValue;
329e8d8bef9SDimitry Andric }
330bdd1243dSDimitry Andric return std::nullopt;
331e8d8bef9SDimitry Andric };
332e8d8bef9SDimitry Andric }
333e8d8bef9SDimitry Andric
makeBooleanOptionDenormalizer(bool Value)334e8d8bef9SDimitry Andric static auto makeBooleanOptionDenormalizer(bool Value) {
335c9157d92SDimitry Andric return [Value](ArgumentConsumer Consumer, const Twine &Spelling,
336c9157d92SDimitry Andric Option::OptionClass, unsigned, bool KeyPath) {
337e8d8bef9SDimitry Andric if (KeyPath == Value)
338c9157d92SDimitry Andric Consumer(Spelling);
339e8d8bef9SDimitry Andric };
340e8d8bef9SDimitry Andric }
341e8d8bef9SDimitry Andric
denormalizeStringImpl(ArgumentConsumer Consumer,const Twine & Spelling,Option::OptionClass OptClass,unsigned,const Twine & Value)342c9157d92SDimitry Andric static void denormalizeStringImpl(ArgumentConsumer Consumer,
343c9157d92SDimitry Andric const Twine &Spelling,
344e8d8bef9SDimitry Andric Option::OptionClass OptClass, unsigned,
345fe6060f1SDimitry Andric const Twine &Value) {
346e8d8bef9SDimitry Andric switch (OptClass) {
347e8d8bef9SDimitry Andric case Option::SeparateClass:
348e8d8bef9SDimitry Andric case Option::JoinedOrSeparateClass:
349fe6060f1SDimitry Andric case Option::JoinedAndSeparateClass:
350c9157d92SDimitry Andric Consumer(Spelling);
351c9157d92SDimitry Andric Consumer(Value);
352e8d8bef9SDimitry Andric break;
353e8d8bef9SDimitry Andric case Option::JoinedClass:
354fe6060f1SDimitry Andric case Option::CommaJoinedClass:
355c9157d92SDimitry Andric Consumer(Spelling + Value);
356e8d8bef9SDimitry Andric break;
357e8d8bef9SDimitry Andric default:
358e8d8bef9SDimitry Andric llvm_unreachable("Cannot denormalize an option with option class "
359e8d8bef9SDimitry Andric "incompatible with string denormalization.");
360e8d8bef9SDimitry Andric }
361e8d8bef9SDimitry Andric }
362e8d8bef9SDimitry Andric
363e8d8bef9SDimitry Andric template <typename T>
denormalizeString(ArgumentConsumer Consumer,const Twine & Spelling,Option::OptionClass OptClass,unsigned TableIndex,T Value)364c9157d92SDimitry Andric static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling,
365c9157d92SDimitry Andric Option::OptionClass OptClass, unsigned TableIndex,
366c9157d92SDimitry Andric T Value) {
367c9157d92SDimitry Andric denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Twine(Value));
368e8d8bef9SDimitry Andric }
369e8d8bef9SDimitry Andric
370bdd1243dSDimitry Andric static std::optional<SimpleEnumValue>
findValueTableByName(const SimpleEnumValueTable & Table,StringRef Name)371e8d8bef9SDimitry Andric findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
372e8d8bef9SDimitry Andric for (int I = 0, E = Table.Size; I != E; ++I)
373e8d8bef9SDimitry Andric if (Name == Table.Table[I].Name)
374e8d8bef9SDimitry Andric return Table.Table[I];
375e8d8bef9SDimitry Andric
376bdd1243dSDimitry Andric return std::nullopt;
377e8d8bef9SDimitry Andric }
378e8d8bef9SDimitry Andric
379bdd1243dSDimitry Andric static std::optional<SimpleEnumValue>
findValueTableByValue(const SimpleEnumValueTable & Table,unsigned Value)380e8d8bef9SDimitry Andric findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
381e8d8bef9SDimitry Andric for (int I = 0, E = Table.Size; I != E; ++I)
382e8d8bef9SDimitry Andric if (Value == Table.Table[I].Value)
383e8d8bef9SDimitry Andric return Table.Table[I];
384e8d8bef9SDimitry Andric
385bdd1243dSDimitry Andric return std::nullopt;
386e8d8bef9SDimitry Andric }
387e8d8bef9SDimitry Andric
normalizeSimpleEnum(OptSpecifier Opt,unsigned TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)388bdd1243dSDimitry Andric static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
389fe6060f1SDimitry Andric unsigned TableIndex,
390fe6060f1SDimitry Andric const ArgList &Args,
391fe6060f1SDimitry Andric DiagnosticsEngine &Diags) {
3925ffd83dbSDimitry Andric assert(TableIndex < SimpleEnumValueTablesSize);
3935ffd83dbSDimitry Andric const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
3945ffd83dbSDimitry Andric
3955ffd83dbSDimitry Andric auto *Arg = Args.getLastArg(Opt);
3965ffd83dbSDimitry Andric if (!Arg)
397bdd1243dSDimitry Andric return std::nullopt;
3985ffd83dbSDimitry Andric
3995ffd83dbSDimitry Andric StringRef ArgValue = Arg->getValue();
400e8d8bef9SDimitry Andric if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
401e8d8bef9SDimitry Andric return MaybeEnumVal->Value;
4025ffd83dbSDimitry Andric
4035ffd83dbSDimitry Andric Diags.Report(diag::err_drv_invalid_value)
4045ffd83dbSDimitry Andric << Arg->getAsString(Args) << ArgValue;
405bdd1243dSDimitry Andric return std::nullopt;
4065ffd83dbSDimitry Andric }
4075ffd83dbSDimitry Andric
denormalizeSimpleEnumImpl(ArgumentConsumer Consumer,const Twine & Spelling,Option::OptionClass OptClass,unsigned TableIndex,unsigned Value)408c9157d92SDimitry Andric static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer,
409c9157d92SDimitry Andric const Twine &Spelling,
410e8d8bef9SDimitry Andric Option::OptionClass OptClass,
4115ffd83dbSDimitry Andric unsigned TableIndex, unsigned Value) {
4125ffd83dbSDimitry Andric assert(TableIndex < SimpleEnumValueTablesSize);
4135ffd83dbSDimitry Andric const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
414e8d8bef9SDimitry Andric if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
415c9157d92SDimitry Andric denormalizeString(Consumer, Spelling, OptClass, TableIndex,
416e8d8bef9SDimitry Andric MaybeEnumVal->Name);
417e8d8bef9SDimitry Andric } else {
4185ffd83dbSDimitry Andric llvm_unreachable("The simple enum value was not correctly defined in "
4195ffd83dbSDimitry Andric "the tablegen option description");
4205ffd83dbSDimitry Andric }
421e8d8bef9SDimitry Andric }
4225ffd83dbSDimitry Andric
423e8d8bef9SDimitry Andric template <typename T>
denormalizeSimpleEnum(ArgumentConsumer Consumer,const Twine & Spelling,Option::OptionClass OptClass,unsigned TableIndex,T Value)424c9157d92SDimitry Andric static void denormalizeSimpleEnum(ArgumentConsumer Consumer,
425c9157d92SDimitry Andric const Twine &Spelling,
426e8d8bef9SDimitry Andric Option::OptionClass OptClass,
427e8d8bef9SDimitry Andric unsigned TableIndex, T Value) {
428c9157d92SDimitry Andric return denormalizeSimpleEnumImpl(Consumer, Spelling, OptClass, TableIndex,
429e8d8bef9SDimitry Andric static_cast<unsigned>(Value));
430e8d8bef9SDimitry Andric }
431e8d8bef9SDimitry Andric
normalizeString(OptSpecifier Opt,int TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)432bdd1243dSDimitry Andric static std::optional<std::string> normalizeString(OptSpecifier Opt,
433bdd1243dSDimitry Andric int TableIndex,
434e8d8bef9SDimitry Andric const ArgList &Args,
435fe6060f1SDimitry Andric DiagnosticsEngine &Diags) {
436e8d8bef9SDimitry Andric auto *Arg = Args.getLastArg(Opt);
437e8d8bef9SDimitry Andric if (!Arg)
438bdd1243dSDimitry Andric return std::nullopt;
439e8d8bef9SDimitry Andric return std::string(Arg->getValue());
440e8d8bef9SDimitry Andric }
441e8d8bef9SDimitry Andric
442e8d8bef9SDimitry Andric template <typename IntTy>
normalizeStringIntegral(OptSpecifier Opt,int,const ArgList & Args,DiagnosticsEngine & Diags)443bdd1243dSDimitry Andric static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
444fe6060f1SDimitry Andric const ArgList &Args,
445fe6060f1SDimitry Andric DiagnosticsEngine &Diags) {
446e8d8bef9SDimitry Andric auto *Arg = Args.getLastArg(Opt);
447e8d8bef9SDimitry Andric if (!Arg)
448bdd1243dSDimitry Andric return std::nullopt;
449e8d8bef9SDimitry Andric IntTy Res;
450e8d8bef9SDimitry Andric if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
451e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_invalid_int_value)
452e8d8bef9SDimitry Andric << Arg->getAsString(Args) << Arg->getValue();
453bdd1243dSDimitry Andric return std::nullopt;
454e8d8bef9SDimitry Andric }
455e8d8bef9SDimitry Andric return Res;
456e8d8bef9SDimitry Andric }
457e8d8bef9SDimitry Andric
458bdd1243dSDimitry Andric static std::optional<std::vector<std::string>>
normalizeStringVector(OptSpecifier Opt,int,const ArgList & Args,DiagnosticsEngine &)459e8d8bef9SDimitry Andric normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
460fe6060f1SDimitry Andric DiagnosticsEngine &) {
461e8d8bef9SDimitry Andric return Args.getAllArgValues(Opt);
462e8d8bef9SDimitry Andric }
463e8d8bef9SDimitry Andric
denormalizeStringVector(ArgumentConsumer Consumer,const Twine & Spelling,Option::OptionClass OptClass,unsigned TableIndex,const std::vector<std::string> & Values)464c9157d92SDimitry Andric static void denormalizeStringVector(ArgumentConsumer Consumer,
465c9157d92SDimitry Andric const Twine &Spelling,
466e8d8bef9SDimitry Andric Option::OptionClass OptClass,
4675ffd83dbSDimitry Andric unsigned TableIndex,
468e8d8bef9SDimitry Andric const std::vector<std::string> &Values) {
469e8d8bef9SDimitry Andric switch (OptClass) {
470e8d8bef9SDimitry Andric case Option::CommaJoinedClass: {
471e8d8bef9SDimitry Andric std::string CommaJoinedValue;
472e8d8bef9SDimitry Andric if (!Values.empty()) {
473e8d8bef9SDimitry Andric CommaJoinedValue.append(Values.front());
474e8d8bef9SDimitry Andric for (const std::string &Value : llvm::drop_begin(Values, 1)) {
475e8d8bef9SDimitry Andric CommaJoinedValue.append(",");
476e8d8bef9SDimitry Andric CommaJoinedValue.append(Value);
477e8d8bef9SDimitry Andric }
478e8d8bef9SDimitry Andric }
479c9157d92SDimitry Andric denormalizeString(Consumer, Spelling, Option::OptionClass::JoinedClass,
480e8d8bef9SDimitry Andric TableIndex, CommaJoinedValue);
481e8d8bef9SDimitry Andric break;
482e8d8bef9SDimitry Andric }
483e8d8bef9SDimitry Andric case Option::JoinedClass:
484e8d8bef9SDimitry Andric case Option::SeparateClass:
485e8d8bef9SDimitry Andric case Option::JoinedOrSeparateClass:
486e8d8bef9SDimitry Andric for (const std::string &Value : Values)
487c9157d92SDimitry Andric denormalizeString(Consumer, Spelling, OptClass, TableIndex, Value);
488e8d8bef9SDimitry Andric break;
489e8d8bef9SDimitry Andric default:
490e8d8bef9SDimitry Andric llvm_unreachable("Cannot denormalize an option with option class "
491e8d8bef9SDimitry Andric "incompatible with string vector denormalization.");
492e8d8bef9SDimitry Andric }
4935ffd83dbSDimitry Andric }
4945ffd83dbSDimitry Andric
normalizeTriple(OptSpecifier Opt,int TableIndex,const ArgList & Args,DiagnosticsEngine & Diags)495bdd1243dSDimitry Andric static std::optional<std::string> normalizeTriple(OptSpecifier Opt,
496bdd1243dSDimitry Andric int TableIndex,
4975ffd83dbSDimitry Andric const ArgList &Args,
498fe6060f1SDimitry Andric DiagnosticsEngine &Diags) {
4995ffd83dbSDimitry Andric auto *Arg = Args.getLastArg(Opt);
5005ffd83dbSDimitry Andric if (!Arg)
501bdd1243dSDimitry Andric return std::nullopt;
5025ffd83dbSDimitry Andric return llvm::Triple::normalize(Arg->getValue());
5035ffd83dbSDimitry Andric }
5045ffd83dbSDimitry Andric
505e8d8bef9SDimitry Andric template <typename T, typename U>
mergeForwardValue(T KeyPath,U Value)506e8d8bef9SDimitry Andric static T mergeForwardValue(T KeyPath, U Value) {
507e8d8bef9SDimitry Andric return static_cast<T>(Value);
508e8d8bef9SDimitry Andric }
509e8d8bef9SDimitry Andric
mergeMaskValue(T KeyPath,U Value)510e8d8bef9SDimitry Andric template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
511e8d8bef9SDimitry Andric return KeyPath | Value;
512e8d8bef9SDimitry Andric }
513e8d8bef9SDimitry Andric
extractForwardValue(T KeyPath)514e8d8bef9SDimitry Andric template <typename T> static T extractForwardValue(T KeyPath) {
515e8d8bef9SDimitry Andric return KeyPath;
516e8d8bef9SDimitry Andric }
517e8d8bef9SDimitry Andric
518e8d8bef9SDimitry Andric template <typename T, typename U, U Value>
extractMaskValue(T KeyPath)519e8d8bef9SDimitry Andric static T extractMaskValue(T KeyPath) {
520fe6060f1SDimitry Andric return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
521e8d8bef9SDimitry Andric }
522e8d8bef9SDimitry Andric
523fe6060f1SDimitry Andric #define PARSE_OPTION_WITH_MARSHALLING( \
524c9157d92SDimitry Andric ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, \
525c9157d92SDimitry Andric FLAGS, VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, \
526c9157d92SDimitry Andric ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, \
527c9157d92SDimitry Andric NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
528c9157d92SDimitry Andric if ((VISIBILITY)&options::CC1Option) { \
529e8d8bef9SDimitry Andric KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
530e8d8bef9SDimitry Andric if (IMPLIED_CHECK) \
531e8d8bef9SDimitry Andric KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
532e8d8bef9SDimitry Andric if (SHOULD_PARSE) \
533fe6060f1SDimitry Andric if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
534e8d8bef9SDimitry Andric KEYPATH = \
535e8d8bef9SDimitry Andric MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
536e8d8bef9SDimitry Andric }
537e8d8bef9SDimitry Andric
538fe6060f1SDimitry Andric // Capture the extracted value as a lambda argument to avoid potential issues
539fe6060f1SDimitry Andric // with lifetime extension of the reference.
540fe6060f1SDimitry Andric #define GENERATE_OPTION_WITH_MARSHALLING( \
541c9157d92SDimitry Andric CONSUMER, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
542c9157d92SDimitry Andric VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT, \
543c9157d92SDimitry Andric KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \
544c9157d92SDimitry Andric DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
545c9157d92SDimitry Andric if ((VISIBILITY)&options::CC1Option) { \
546fe6060f1SDimitry Andric [&](const auto &Extracted) { \
547fe6060f1SDimitry Andric if (ALWAYS_EMIT || \
548fe6060f1SDimitry Andric (Extracted != \
549fe6060f1SDimitry Andric static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
550fe6060f1SDimitry Andric : (DEFAULT_VALUE)))) \
551c9157d92SDimitry Andric DENORMALIZER(CONSUMER, SPELLING, Option::KIND##Class, TABLE_INDEX, \
552c9157d92SDimitry Andric Extracted); \
553fe6060f1SDimitry Andric }(EXTRACTOR(KEYPATH)); \
554fe6060f1SDimitry Andric }
555fe6060f1SDimitry Andric
55604eeddc0SDimitry Andric static StringRef GetInputKindName(InputKind IK);
557e8d8bef9SDimitry Andric
FixupInvocation(CompilerInvocation & Invocation,DiagnosticsEngine & Diags,const ArgList & Args,InputKind IK)558fe6060f1SDimitry Andric static bool FixupInvocation(CompilerInvocation &Invocation,
559fe6060f1SDimitry Andric DiagnosticsEngine &Diags, const ArgList &Args,
560e8d8bef9SDimitry Andric InputKind IK) {
561fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
562fe6060f1SDimitry Andric
563c9157d92SDimitry Andric LangOptions &LangOpts = Invocation.getLangOpts();
564e8d8bef9SDimitry Andric CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
565e8d8bef9SDimitry Andric TargetOptions &TargetOpts = Invocation.getTargetOpts();
566e8d8bef9SDimitry Andric FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
567e8d8bef9SDimitry Andric CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
568e8d8bef9SDimitry Andric CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
569e8d8bef9SDimitry Andric CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
570e8d8bef9SDimitry Andric CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
571e8d8bef9SDimitry Andric FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
572349cc55cSDimitry Andric if (FrontendOpts.ShowStats)
573349cc55cSDimitry Andric CodeGenOpts.ClearASTBeforeBackend = false;
574fe6060f1SDimitry Andric LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
575e8d8bef9SDimitry Andric LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
576e8d8bef9SDimitry Andric LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
577e8d8bef9SDimitry Andric LangOpts.CurrentModule = LangOpts.ModuleName;
578e8d8bef9SDimitry Andric
579e8d8bef9SDimitry Andric llvm::Triple T(TargetOpts.Triple);
580e8d8bef9SDimitry Andric llvm::Triple::ArchType Arch = T.getArch();
581e8d8bef9SDimitry Andric
582e8d8bef9SDimitry Andric CodeGenOpts.CodeModel = TargetOpts.CodeModel;
583c9157d92SDimitry Andric CodeGenOpts.LargeDataThreshold = TargetOpts.LargeDataThreshold;
584e8d8bef9SDimitry Andric
585fe6060f1SDimitry Andric if (LangOpts.getExceptionHandling() !=
586fe6060f1SDimitry Andric LangOptions::ExceptionHandlingKind::None &&
587e8d8bef9SDimitry Andric T.isWindowsMSVCEnvironment())
588e8d8bef9SDimitry Andric Diags.Report(diag::err_fe_invalid_exception_model)
589e8d8bef9SDimitry Andric << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
590e8d8bef9SDimitry Andric
591e8d8bef9SDimitry Andric if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
592e8d8bef9SDimitry Andric Diags.Report(diag::warn_c_kext);
593e8d8bef9SDimitry Andric
594e8d8bef9SDimitry Andric if (LangOpts.NewAlignOverride &&
595e8d8bef9SDimitry Andric !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
596e8d8bef9SDimitry Andric Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
597e8d8bef9SDimitry Andric Diags.Report(diag::err_fe_invalid_alignment)
598e8d8bef9SDimitry Andric << A->getAsString(Args) << A->getValue();
599e8d8bef9SDimitry Andric LangOpts.NewAlignOverride = 0;
600e8d8bef9SDimitry Andric }
601e8d8bef9SDimitry Andric
602fe6060f1SDimitry Andric // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
603fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
604fe6060f1SDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
605fe6060f1SDimitry Andric << "-fsycl-is-host";
606fe6060f1SDimitry Andric
607e8d8bef9SDimitry Andric if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
608e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
609e8d8bef9SDimitry Andric << "-fgnu89-inline" << GetInputKindName(IK);
610e8d8bef9SDimitry Andric
611bdd1243dSDimitry Andric if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
612bdd1243dSDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
613bdd1243dSDimitry Andric << "-hlsl-entry" << GetInputKindName(IK);
614bdd1243dSDimitry Andric
615e8d8bef9SDimitry Andric if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
616e8d8bef9SDimitry Andric Diags.Report(diag::warn_ignored_hip_only_option)
617e8d8bef9SDimitry Andric << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
618e8d8bef9SDimitry Andric
619e8d8bef9SDimitry Andric if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
620e8d8bef9SDimitry Andric Diags.Report(diag::warn_ignored_hip_only_option)
621e8d8bef9SDimitry Andric << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
622e8d8bef9SDimitry Andric
62381ad6265SDimitry Andric // When these options are used, the compiler is allowed to apply
62481ad6265SDimitry Andric // optimizations that may affect the final result. For example
62581ad6265SDimitry Andric // (x+y)+z is transformed to x+(y+z) but may not give the same
62681ad6265SDimitry Andric // final result; it's not value safe.
62781ad6265SDimitry Andric // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
62881ad6265SDimitry Andric // or NaN. Final result may then differ. An error is issued when the eval
62981ad6265SDimitry Andric // method is set with one of these options.
63081ad6265SDimitry Andric if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
63181ad6265SDimitry Andric if (LangOpts.ApproxFunc)
63281ad6265SDimitry Andric Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
63381ad6265SDimitry Andric if (LangOpts.AllowFPReassoc)
63481ad6265SDimitry Andric Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
63581ad6265SDimitry Andric if (LangOpts.AllowRecip)
63681ad6265SDimitry Andric Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
63781ad6265SDimitry Andric }
63881ad6265SDimitry Andric
639e8d8bef9SDimitry Andric // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
640e8d8bef9SDimitry Andric // This option should be deprecated for CL > 1.0 because
641e8d8bef9SDimitry Andric // this option was added for compatibility with OpenCL 1.0.
642349cc55cSDimitry Andric if (Args.getLastArg(OPT_cl_strict_aliasing) &&
643349cc55cSDimitry Andric (LangOpts.getOpenCLCompatibleVersion() > 100))
644e8d8bef9SDimitry Andric Diags.Report(diag::warn_option_invalid_ocl_version)
645349cc55cSDimitry Andric << LangOpts.getOpenCLVersionString()
646e8d8bef9SDimitry Andric << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
647e8d8bef9SDimitry Andric
648e8d8bef9SDimitry Andric if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
649e8d8bef9SDimitry Andric auto DefaultCC = LangOpts.getDefaultCallingConv();
650e8d8bef9SDimitry Andric
651e8d8bef9SDimitry Andric bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
652e8d8bef9SDimitry Andric DefaultCC == LangOptions::DCC_StdCall) &&
653e8d8bef9SDimitry Andric Arch != llvm::Triple::x86;
654e8d8bef9SDimitry Andric emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
655e8d8bef9SDimitry Andric DefaultCC == LangOptions::DCC_RegCall) &&
656e8d8bef9SDimitry Andric !T.isX86();
657c9157d92SDimitry Andric emitError |= DefaultCC == LangOptions::DCC_RtdCall && Arch != llvm::Triple::m68k;
658e8d8bef9SDimitry Andric if (emitError)
659e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
660e8d8bef9SDimitry Andric << A->getSpelling() << T.getTriple();
661e8d8bef9SDimitry Andric }
662e8d8bef9SDimitry Andric
663fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
664e8d8bef9SDimitry Andric }
665e8d8bef9SDimitry Andric
6665ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
6670b57cec5SDimitry Andric // Deserialization (from args)
6680b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6690b57cec5SDimitry Andric
getOptimizationLevel(ArgList & Args,InputKind IK,DiagnosticsEngine & Diags)6700b57cec5SDimitry Andric static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
6710b57cec5SDimitry Andric DiagnosticsEngine &Diags) {
672c9157d92SDimitry Andric unsigned DefaultOpt = 0;
673fe6060f1SDimitry Andric if ((IK.getLanguage() == Language::OpenCL ||
674fe6060f1SDimitry Andric IK.getLanguage() == Language::OpenCLCXX) &&
675fe6060f1SDimitry Andric !Args.hasArg(OPT_cl_opt_disable))
676c9157d92SDimitry Andric DefaultOpt = 2;
6770b57cec5SDimitry Andric
6780b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
6790b57cec5SDimitry Andric if (A->getOption().matches(options::OPT_O0))
680c9157d92SDimitry Andric return 0;
6810b57cec5SDimitry Andric
6820b57cec5SDimitry Andric if (A->getOption().matches(options::OPT_Ofast))
683c9157d92SDimitry Andric return 3;
6840b57cec5SDimitry Andric
6850b57cec5SDimitry Andric assert(A->getOption().matches(options::OPT_O));
6860b57cec5SDimitry Andric
6870b57cec5SDimitry Andric StringRef S(A->getValue());
6885ffd83dbSDimitry Andric if (S == "s" || S == "z")
689c9157d92SDimitry Andric return 2;
6900b57cec5SDimitry Andric
6910b57cec5SDimitry Andric if (S == "g")
692c9157d92SDimitry Andric return 1;
6930b57cec5SDimitry Andric
6940b57cec5SDimitry Andric return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric
6970b57cec5SDimitry Andric return DefaultOpt;
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric
getOptimizationLevelSize(ArgList & Args)7000b57cec5SDimitry Andric static unsigned getOptimizationLevelSize(ArgList &Args) {
7010b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
7020b57cec5SDimitry Andric if (A->getOption().matches(options::OPT_O)) {
7030b57cec5SDimitry Andric switch (A->getValue()[0]) {
7040b57cec5SDimitry Andric default:
7050b57cec5SDimitry Andric return 0;
7060b57cec5SDimitry Andric case 's':
7070b57cec5SDimitry Andric return 1;
7080b57cec5SDimitry Andric case 'z':
7090b57cec5SDimitry Andric return 2;
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric }
7130b57cec5SDimitry Andric return 0;
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric
GenerateArg(ArgumentConsumer Consumer,llvm::opt::OptSpecifier OptSpecifier)716c9157d92SDimitry Andric static void GenerateArg(ArgumentConsumer Consumer,
717c9157d92SDimitry Andric llvm::opt::OptSpecifier OptSpecifier) {
718fe6060f1SDimitry Andric Option Opt = getDriverOptTable().getOption(OptSpecifier);
719c9157d92SDimitry Andric denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
720fe6060f1SDimitry Andric Option::OptionClass::FlagClass, 0);
721fe6060f1SDimitry Andric }
722fe6060f1SDimitry Andric
GenerateArg(ArgumentConsumer Consumer,llvm::opt::OptSpecifier OptSpecifier,const Twine & Value)723c9157d92SDimitry Andric static void GenerateArg(ArgumentConsumer Consumer,
724fe6060f1SDimitry Andric llvm::opt::OptSpecifier OptSpecifier,
725c9157d92SDimitry Andric const Twine &Value) {
726fe6060f1SDimitry Andric Option Opt = getDriverOptTable().getOption(OptSpecifier);
727c9157d92SDimitry Andric denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
728fe6060f1SDimitry Andric }
729fe6060f1SDimitry Andric
730fe6060f1SDimitry Andric // Parse command line arguments into CompilerInvocation.
731fe6060f1SDimitry Andric using ParseFn =
732fe6060f1SDimitry Andric llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
733fe6060f1SDimitry Andric DiagnosticsEngine &, const char *)>;
734fe6060f1SDimitry Andric
735fe6060f1SDimitry Andric // Generate command line arguments from CompilerInvocation.
736fe6060f1SDimitry Andric using GenerateFn = llvm::function_ref<void(
737fe6060f1SDimitry Andric CompilerInvocation &, SmallVectorImpl<const char *> &,
738fe6060f1SDimitry Andric CompilerInvocation::StringAllocator)>;
739fe6060f1SDimitry Andric
740fe013be4SDimitry Andric /// May perform round-trip of command line arguments. By default, the round-trip
741fe013be4SDimitry Andric /// is enabled in assert builds. This can be overwritten at run-time via the
742fe013be4SDimitry Andric /// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the
743fe013be4SDimitry Andric /// ForceRoundTrip parameter.
744fe013be4SDimitry Andric ///
745fe013be4SDimitry Andric /// During round-trip, the command line arguments are parsed into a dummy
746fe013be4SDimitry Andric /// CompilerInvocation, which is used to generate the command line arguments
747fe013be4SDimitry Andric /// again. The real CompilerInvocation is then created by parsing the generated
748fe013be4SDimitry Andric /// arguments, not the original ones. This (in combination with tests covering
749fe013be4SDimitry Andric /// argument behavior) ensures the generated command line is complete (doesn't
750fe013be4SDimitry Andric /// drop/mangle any arguments).
751fe013be4SDimitry Andric ///
752fe013be4SDimitry Andric /// Finally, we check the command line that was used to create the real
753fe013be4SDimitry Andric /// CompilerInvocation instance. By default, we compare it to the command line
754fe013be4SDimitry Andric /// the real CompilerInvocation generates. This checks whether the generator is
755fe013be4SDimitry Andric /// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead
756fe013be4SDimitry Andric /// compare it to the original command line to verify the original command-line
757fe013be4SDimitry Andric /// was canonical and can round-trip exactly.
RoundTrip(ParseFn Parse,GenerateFn Generate,CompilerInvocation & RealInvocation,CompilerInvocation & DummyInvocation,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0,bool CheckAgainstOriginalInvocation=false,bool ForceRoundTrip=false)758fe6060f1SDimitry Andric static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
759fe6060f1SDimitry Andric CompilerInvocation &RealInvocation,
760fe6060f1SDimitry Andric CompilerInvocation &DummyInvocation,
761fe6060f1SDimitry Andric ArrayRef<const char *> CommandLineArgs,
762fe013be4SDimitry Andric DiagnosticsEngine &Diags, const char *Argv0,
763fe013be4SDimitry Andric bool CheckAgainstOriginalInvocation = false,
764fe013be4SDimitry Andric bool ForceRoundTrip = false) {
765349cc55cSDimitry Andric #ifndef NDEBUG
766fe6060f1SDimitry Andric bool DoRoundTripDefault = true;
767fe6060f1SDimitry Andric #else
768fe6060f1SDimitry Andric bool DoRoundTripDefault = false;
769fe6060f1SDimitry Andric #endif
770fe6060f1SDimitry Andric
771fe6060f1SDimitry Andric bool DoRoundTrip = DoRoundTripDefault;
772fe013be4SDimitry Andric if (ForceRoundTrip) {
773fe013be4SDimitry Andric DoRoundTrip = true;
774fe013be4SDimitry Andric } else {
775fe6060f1SDimitry Andric for (const auto *Arg : CommandLineArgs) {
776fe6060f1SDimitry Andric if (Arg == StringRef("-round-trip-args"))
777fe6060f1SDimitry Andric DoRoundTrip = true;
778fe6060f1SDimitry Andric if (Arg == StringRef("-no-round-trip-args"))
779fe6060f1SDimitry Andric DoRoundTrip = false;
780fe6060f1SDimitry Andric }
781fe013be4SDimitry Andric }
782fe6060f1SDimitry Andric
783fe6060f1SDimitry Andric // If round-trip was not requested, simply run the parser with the real
784fe6060f1SDimitry Andric // invocation diagnostics.
785fe6060f1SDimitry Andric if (!DoRoundTrip)
786fe6060f1SDimitry Andric return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
787fe6060f1SDimitry Andric
788fe6060f1SDimitry Andric // Serializes quoted (and potentially escaped) arguments.
789fe6060f1SDimitry Andric auto SerializeArgs = [](ArrayRef<const char *> Args) {
790fe6060f1SDimitry Andric std::string Buffer;
791fe6060f1SDimitry Andric llvm::raw_string_ostream OS(Buffer);
792fe6060f1SDimitry Andric for (const char *Arg : Args) {
793fe6060f1SDimitry Andric llvm::sys::printArg(OS, Arg, /*Quote=*/true);
794fe6060f1SDimitry Andric OS << ' ';
795fe6060f1SDimitry Andric }
796fe6060f1SDimitry Andric OS.flush();
797fe6060f1SDimitry Andric return Buffer;
798fe6060f1SDimitry Andric };
799fe6060f1SDimitry Andric
800fe6060f1SDimitry Andric // Setup a dummy DiagnosticsEngine.
801fe6060f1SDimitry Andric DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
802fe6060f1SDimitry Andric DummyDiags.setClient(new TextDiagnosticBuffer());
803fe6060f1SDimitry Andric
804fe6060f1SDimitry Andric // Run the first parse on the original arguments with the dummy invocation and
805fe6060f1SDimitry Andric // diagnostics.
806fe6060f1SDimitry Andric if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
807fe6060f1SDimitry Andric DummyDiags.getNumWarnings() != 0) {
808fe6060f1SDimitry Andric // If the first parse did not succeed, it must be user mistake (invalid
809fe6060f1SDimitry Andric // command line arguments). We won't be able to generate arguments that
810fe6060f1SDimitry Andric // would reproduce the same result. Let's fail again with the real
811fe6060f1SDimitry Andric // invocation and diagnostics, so all side-effects of parsing are visible.
812fe6060f1SDimitry Andric unsigned NumWarningsBefore = Diags.getNumWarnings();
813fe6060f1SDimitry Andric auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
814fe6060f1SDimitry Andric if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
815fe6060f1SDimitry Andric return Success;
816fe6060f1SDimitry Andric
817fe6060f1SDimitry Andric // Parse with original options and diagnostics succeeded even though it
818fe6060f1SDimitry Andric // shouldn't have. Something is off.
819fe6060f1SDimitry Andric Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
820fe6060f1SDimitry Andric Diags.Report(diag::note_cc1_round_trip_original)
821fe6060f1SDimitry Andric << SerializeArgs(CommandLineArgs);
822fe6060f1SDimitry Andric return false;
823fe6060f1SDimitry Andric }
824fe6060f1SDimitry Andric
825fe6060f1SDimitry Andric // Setup string allocator.
826fe6060f1SDimitry Andric llvm::BumpPtrAllocator Alloc;
827fe6060f1SDimitry Andric llvm::StringSaver StringPool(Alloc);
828fe6060f1SDimitry Andric auto SA = [&StringPool](const Twine &Arg) {
829fe6060f1SDimitry Andric return StringPool.save(Arg).data();
830fe6060f1SDimitry Andric };
831fe6060f1SDimitry Andric
832fe6060f1SDimitry Andric // Generate arguments from the dummy invocation. If Generate is the
833fe6060f1SDimitry Andric // inverse of Parse, the newly generated arguments must have the same
834fe6060f1SDimitry Andric // semantics as the original.
835fe013be4SDimitry Andric SmallVector<const char *> GeneratedArgs;
836fe013be4SDimitry Andric Generate(DummyInvocation, GeneratedArgs, SA);
837fe6060f1SDimitry Andric
838fe6060f1SDimitry Andric // Run the second parse, now on the generated arguments, and with the real
839fe6060f1SDimitry Andric // invocation and diagnostics. The result is what we will end up using for the
840fe6060f1SDimitry Andric // rest of compilation, so if Generate is not inverse of Parse, something down
841fe6060f1SDimitry Andric // the line will break.
842fe013be4SDimitry Andric bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
843fe6060f1SDimitry Andric
844fe6060f1SDimitry Andric // The first parse on original arguments succeeded, but second parse of
845fe6060f1SDimitry Andric // generated arguments failed. Something must be wrong with the generator.
846fe6060f1SDimitry Andric if (!Success2) {
847fe6060f1SDimitry Andric Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
848fe6060f1SDimitry Andric Diags.Report(diag::note_cc1_round_trip_generated)
849fe013be4SDimitry Andric << 1 << SerializeArgs(GeneratedArgs);
850fe6060f1SDimitry Andric return false;
851fe6060f1SDimitry Andric }
852fe6060f1SDimitry Andric
853fe013be4SDimitry Andric SmallVector<const char *> ComparisonArgs;
854fe013be4SDimitry Andric if (CheckAgainstOriginalInvocation)
855fe013be4SDimitry Andric // Compare against original arguments.
856fe013be4SDimitry Andric ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end());
857fe013be4SDimitry Andric else
858fe6060f1SDimitry Andric // Generate arguments again, this time from the options we will end up using
859fe6060f1SDimitry Andric // for the rest of the compilation.
860fe013be4SDimitry Andric Generate(RealInvocation, ComparisonArgs, SA);
861fe6060f1SDimitry Andric
862fe013be4SDimitry Andric // Compares two lists of arguments.
863fe6060f1SDimitry Andric auto Equal = [](const ArrayRef<const char *> A,
864fe6060f1SDimitry Andric const ArrayRef<const char *> B) {
865fe6060f1SDimitry Andric return std::equal(A.begin(), A.end(), B.begin(), B.end(),
866fe6060f1SDimitry Andric [](const char *AElem, const char *BElem) {
867fe6060f1SDimitry Andric return StringRef(AElem) == StringRef(BElem);
868fe6060f1SDimitry Andric });
869fe6060f1SDimitry Andric };
870fe6060f1SDimitry Andric
871fe6060f1SDimitry Andric // If we generated different arguments from what we assume are two
872fe6060f1SDimitry Andric // semantically equivalent CompilerInvocations, the Generate function may
873fe6060f1SDimitry Andric // be non-deterministic.
874fe013be4SDimitry Andric if (!Equal(GeneratedArgs, ComparisonArgs)) {
875fe6060f1SDimitry Andric Diags.Report(diag::err_cc1_round_trip_mismatch);
876fe6060f1SDimitry Andric Diags.Report(diag::note_cc1_round_trip_generated)
877fe013be4SDimitry Andric << 1 << SerializeArgs(GeneratedArgs);
878fe6060f1SDimitry Andric Diags.Report(diag::note_cc1_round_trip_generated)
879fe013be4SDimitry Andric << 2 << SerializeArgs(ComparisonArgs);
880fe6060f1SDimitry Andric return false;
881fe6060f1SDimitry Andric }
882fe6060f1SDimitry Andric
883fe6060f1SDimitry Andric Diags.Report(diag::remark_cc1_round_trip_generated)
884fe013be4SDimitry Andric << 1 << SerializeArgs(GeneratedArgs);
885fe6060f1SDimitry Andric Diags.Report(diag::remark_cc1_round_trip_generated)
886fe013be4SDimitry Andric << 2 << SerializeArgs(ComparisonArgs);
887fe6060f1SDimitry Andric
888fe6060f1SDimitry Andric return Success2;
889e8d8bef9SDimitry Andric }
890e8d8bef9SDimitry Andric
checkCC1RoundTrip(ArrayRef<const char * > Args,DiagnosticsEngine & Diags,const char * Argv0)891fe013be4SDimitry Andric bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args,
892fe013be4SDimitry Andric DiagnosticsEngine &Diags,
893fe013be4SDimitry Andric const char *Argv0) {
894fe013be4SDimitry Andric CompilerInvocation DummyInvocation1, DummyInvocation2;
895fe013be4SDimitry Andric return RoundTrip(
896fe013be4SDimitry Andric [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
897fe013be4SDimitry Andric DiagnosticsEngine &Diags, const char *Argv0) {
898fe013be4SDimitry Andric return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
899fe013be4SDimitry Andric },
900fe013be4SDimitry Andric [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
901fe013be4SDimitry Andric StringAllocator SA) {
902fe013be4SDimitry Andric Args.push_back("-cc1");
903fe013be4SDimitry Andric Invocation.generateCC1CommandLine(Args, SA);
904fe013be4SDimitry Andric },
905fe013be4SDimitry Andric DummyInvocation1, DummyInvocation2, Args, Diags, Argv0,
906fe013be4SDimitry Andric /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true);
907fe013be4SDimitry Andric }
908fe013be4SDimitry Andric
addDiagnosticArgs(ArgList & Args,OptSpecifier Group,OptSpecifier GroupWithValue,std::vector<std::string> & Diagnostics)9090b57cec5SDimitry Andric static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
9100b57cec5SDimitry Andric OptSpecifier GroupWithValue,
9110b57cec5SDimitry Andric std::vector<std::string> &Diagnostics) {
9120b57cec5SDimitry Andric for (auto *A : Args.filtered(Group)) {
9130b57cec5SDimitry Andric if (A->getOption().getKind() == Option::FlagClass) {
9140b57cec5SDimitry Andric // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
915fe6060f1SDimitry Andric // its name (minus the "W" or "R" at the beginning) to the diagnostics.
9165ffd83dbSDimitry Andric Diagnostics.push_back(
9175ffd83dbSDimitry Andric std::string(A->getOption().getName().drop_front(1)));
9180b57cec5SDimitry Andric } else if (A->getOption().matches(GroupWithValue)) {
919fe6060f1SDimitry Andric // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
920fe6060f1SDimitry Andric // group. Add only the group name to the diagnostics.
9215ffd83dbSDimitry Andric Diagnostics.push_back(
9225ffd83dbSDimitry Andric std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
9230b57cec5SDimitry Andric } else {
9240b57cec5SDimitry Andric // Otherwise, add its value (for OPT_W_Joined and similar).
925fe6060f1SDimitry Andric Diagnostics.push_back(A->getValue());
9260b57cec5SDimitry Andric }
9270b57cec5SDimitry Andric }
9280b57cec5SDimitry Andric }
9290b57cec5SDimitry Andric
9300b57cec5SDimitry Andric // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
9310b57cec5SDimitry Andric // it won't verify the input.
9320b57cec5SDimitry Andric static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
9330b57cec5SDimitry Andric DiagnosticsEngine *Diags);
9340b57cec5SDimitry Andric
getAllNoBuiltinFuncValues(ArgList & Args,std::vector<std::string> & Funcs)9350b57cec5SDimitry Andric static void getAllNoBuiltinFuncValues(ArgList &Args,
9360b57cec5SDimitry Andric std::vector<std::string> &Funcs) {
937fe6060f1SDimitry Andric std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
9380eae32dcSDimitry Andric auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
939fe6060f1SDimitry Andric Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
940fe6060f1SDimitry Andric }
941fe6060f1SDimitry Andric
GenerateAnalyzerArgs(const AnalyzerOptions & Opts,ArgumentConsumer Consumer)942c9157d92SDimitry Andric static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts,
943c9157d92SDimitry Andric ArgumentConsumer Consumer) {
944fe6060f1SDimitry Andric const AnalyzerOptions *AnalyzerOpts = &Opts;
945fe6060f1SDimitry Andric
946fe013be4SDimitry Andric #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
947c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
948fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
949fe6060f1SDimitry Andric #undef ANALYZER_OPTION_WITH_MARSHALLING
950fe6060f1SDimitry Andric
951fe6060f1SDimitry Andric if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
952fe6060f1SDimitry Andric switch (Opts.AnalysisConstraintsOpt) {
953fe6060f1SDimitry Andric #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
954fe6060f1SDimitry Andric case NAME##Model: \
955c9157d92SDimitry Andric GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \
956fe6060f1SDimitry Andric break;
957fe6060f1SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
958fe6060f1SDimitry Andric default:
959fe6060f1SDimitry Andric llvm_unreachable("Tried to generate unknown analysis constraint.");
960fe6060f1SDimitry Andric }
961fe6060f1SDimitry Andric }
962fe6060f1SDimitry Andric
963fe6060f1SDimitry Andric if (Opts.AnalysisDiagOpt != PD_HTML) {
964fe6060f1SDimitry Andric switch (Opts.AnalysisDiagOpt) {
965fe6060f1SDimitry Andric #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
966fe6060f1SDimitry Andric case PD_##NAME: \
967c9157d92SDimitry Andric GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \
968fe6060f1SDimitry Andric break;
969fe6060f1SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
970fe6060f1SDimitry Andric default:
971fe6060f1SDimitry Andric llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
972fe6060f1SDimitry Andric }
973fe6060f1SDimitry Andric }
974fe6060f1SDimitry Andric
975fe6060f1SDimitry Andric if (Opts.AnalysisPurgeOpt != PurgeStmt) {
976fe6060f1SDimitry Andric switch (Opts.AnalysisPurgeOpt) {
977fe6060f1SDimitry Andric #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
978fe6060f1SDimitry Andric case NAME: \
979c9157d92SDimitry Andric GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \
980fe6060f1SDimitry Andric break;
981fe6060f1SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
982fe6060f1SDimitry Andric default:
983fe6060f1SDimitry Andric llvm_unreachable("Tried to generate unknown analysis purge mode.");
984fe6060f1SDimitry Andric }
985fe6060f1SDimitry Andric }
986fe6060f1SDimitry Andric
987fe6060f1SDimitry Andric if (Opts.InliningMode != NoRedundancy) {
988fe6060f1SDimitry Andric switch (Opts.InliningMode) {
989fe6060f1SDimitry Andric #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
990fe6060f1SDimitry Andric case NAME: \
991c9157d92SDimitry Andric GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \
992fe6060f1SDimitry Andric break;
993fe6060f1SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
994fe6060f1SDimitry Andric default:
995fe6060f1SDimitry Andric llvm_unreachable("Tried to generate unknown analysis inlining mode.");
996fe6060f1SDimitry Andric }
997fe6060f1SDimitry Andric }
998fe6060f1SDimitry Andric
999fe6060f1SDimitry Andric for (const auto &CP : Opts.CheckersAndPackages) {
1000fe6060f1SDimitry Andric OptSpecifier Opt =
1001fe6060f1SDimitry Andric CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
1002c9157d92SDimitry Andric GenerateArg(Consumer, Opt, CP.first);
1003fe6060f1SDimitry Andric }
1004fe6060f1SDimitry Andric
1005fe6060f1SDimitry Andric AnalyzerOptions ConfigOpts;
1006fe6060f1SDimitry Andric parseAnalyzerConfigs(ConfigOpts, nullptr);
1007fe6060f1SDimitry Andric
1008fe013be4SDimitry Andric // Sort options by key to avoid relying on StringMap iteration order.
1009fe013be4SDimitry Andric SmallVector<std::pair<StringRef, StringRef>, 4> SortedConfigOpts;
1010fe013be4SDimitry Andric for (const auto &C : Opts.Config)
1011fe013be4SDimitry Andric SortedConfigOpts.emplace_back(C.getKey(), C.getValue());
1012fe013be4SDimitry Andric llvm::sort(SortedConfigOpts, llvm::less_first());
1013fe013be4SDimitry Andric
1014fe013be4SDimitry Andric for (const auto &[Key, Value] : SortedConfigOpts) {
1015fe6060f1SDimitry Andric // Don't generate anything that came from parseAnalyzerConfigs. It would be
1016fe6060f1SDimitry Andric // redundant and may not be valid on the command line.
1017fe013be4SDimitry Andric auto Entry = ConfigOpts.Config.find(Key);
1018fe013be4SDimitry Andric if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value)
1019fe6060f1SDimitry Andric continue;
1020fe6060f1SDimitry Andric
1021c9157d92SDimitry Andric GenerateArg(Consumer, OPT_analyzer_config, Key + "=" + Value);
1022fe6060f1SDimitry Andric }
1023fe6060f1SDimitry Andric
1024fe6060f1SDimitry Andric // Nothing to generate for FullCompilerInvocation.
10250b57cec5SDimitry Andric }
10260b57cec5SDimitry Andric
ParseAnalyzerArgs(AnalyzerOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)10270b57cec5SDimitry Andric static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
10280b57cec5SDimitry Andric DiagnosticsEngine &Diags) {
1029fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
1030fe6060f1SDimitry Andric
1031fe6060f1SDimitry Andric AnalyzerOptions *AnalyzerOpts = &Opts;
1032fe6060f1SDimitry Andric
1033fe013be4SDimitry Andric #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
1034fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1035fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
1036fe6060f1SDimitry Andric #undef ANALYZER_OPTION_WITH_MARSHALLING
1037fe6060f1SDimitry Andric
10380b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
10390b57cec5SDimitry Andric StringRef Name = A->getValue();
10400b57cec5SDimitry Andric AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
10410b57cec5SDimitry Andric #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
10420b57cec5SDimitry Andric .Case(CMDFLAG, NAME##Model)
10430b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
10440b57cec5SDimitry Andric .Default(NumConstraints);
10450b57cec5SDimitry Andric if (Value == NumConstraints) {
10460b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
10470b57cec5SDimitry Andric << A->getAsString(Args) << Name;
10480b57cec5SDimitry Andric } else {
104981ad6265SDimitry Andric #ifndef LLVM_WITH_Z3
105081ad6265SDimitry Andric if (Value == AnalysisConstraints::Z3ConstraintsModel) {
105181ad6265SDimitry Andric Diags.Report(diag::err_analyzer_not_built_with_z3);
105281ad6265SDimitry Andric }
105381ad6265SDimitry Andric #endif // LLVM_WITH_Z3
10540b57cec5SDimitry Andric Opts.AnalysisConstraintsOpt = Value;
10550b57cec5SDimitry Andric }
10560b57cec5SDimitry Andric }
10570b57cec5SDimitry Andric
10580b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
10590b57cec5SDimitry Andric StringRef Name = A->getValue();
10600b57cec5SDimitry Andric AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
10610b57cec5SDimitry Andric #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
10620b57cec5SDimitry Andric .Case(CMDFLAG, PD_##NAME)
10630b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
10640b57cec5SDimitry Andric .Default(NUM_ANALYSIS_DIAG_CLIENTS);
10650b57cec5SDimitry Andric if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
10660b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
10670b57cec5SDimitry Andric << A->getAsString(Args) << Name;
10680b57cec5SDimitry Andric } else {
10690b57cec5SDimitry Andric Opts.AnalysisDiagOpt = Value;
10700b57cec5SDimitry Andric }
10710b57cec5SDimitry Andric }
10720b57cec5SDimitry Andric
10730b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
10740b57cec5SDimitry Andric StringRef Name = A->getValue();
10750b57cec5SDimitry Andric AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
10760b57cec5SDimitry Andric #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
10770b57cec5SDimitry Andric .Case(CMDFLAG, NAME)
10780b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
10790b57cec5SDimitry Andric .Default(NumPurgeModes);
10800b57cec5SDimitry Andric if (Value == NumPurgeModes) {
10810b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
10820b57cec5SDimitry Andric << A->getAsString(Args) << Name;
10830b57cec5SDimitry Andric } else {
10840b57cec5SDimitry Andric Opts.AnalysisPurgeOpt = Value;
10850b57cec5SDimitry Andric }
10860b57cec5SDimitry Andric }
10870b57cec5SDimitry Andric
10880b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
10890b57cec5SDimitry Andric StringRef Name = A->getValue();
10900b57cec5SDimitry Andric AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
10910b57cec5SDimitry Andric #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
10920b57cec5SDimitry Andric .Case(CMDFLAG, NAME)
10930b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
10940b57cec5SDimitry Andric .Default(NumInliningModes);
10950b57cec5SDimitry Andric if (Value == NumInliningModes) {
10960b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
10970b57cec5SDimitry Andric << A->getAsString(Args) << Name;
10980b57cec5SDimitry Andric } else {
10990b57cec5SDimitry Andric Opts.InliningMode = Value;
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric }
11020b57cec5SDimitry Andric
1103a7dea167SDimitry Andric Opts.CheckersAndPackages.clear();
11040b57cec5SDimitry Andric for (const Arg *A :
11050b57cec5SDimitry Andric Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
11060b57cec5SDimitry Andric A->claim();
1107a7dea167SDimitry Andric bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
11080b57cec5SDimitry Andric // We can have a list of comma separated checker names, e.g:
11090b57cec5SDimitry Andric // '-analyzer-checker=cocoa,unix'
1110a7dea167SDimitry Andric StringRef CheckerAndPackageList = A->getValue();
1111a7dea167SDimitry Andric SmallVector<StringRef, 16> CheckersAndPackages;
1112a7dea167SDimitry Andric CheckerAndPackageList.split(CheckersAndPackages, ",");
1113480093f4SDimitry Andric for (const StringRef &CheckerOrPackage : CheckersAndPackages)
11145ffd83dbSDimitry Andric Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
11155ffd83dbSDimitry Andric IsEnabled);
11160b57cec5SDimitry Andric }
11170b57cec5SDimitry Andric
11180b57cec5SDimitry Andric // Go through the analyzer configuration options.
11190b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_analyzer_config)) {
11200b57cec5SDimitry Andric
11210b57cec5SDimitry Andric // We can have a list of comma separated config names, e.g:
11220b57cec5SDimitry Andric // '-analyzer-config key1=val1,key2=val2'
11230b57cec5SDimitry Andric StringRef configList = A->getValue();
11240b57cec5SDimitry Andric SmallVector<StringRef, 4> configVals;
11250b57cec5SDimitry Andric configList.split(configVals, ",");
11260b57cec5SDimitry Andric for (const auto &configVal : configVals) {
11270b57cec5SDimitry Andric StringRef key, val;
11280b57cec5SDimitry Andric std::tie(key, val) = configVal.split("=");
11290b57cec5SDimitry Andric if (val.empty()) {
11300b57cec5SDimitry Andric Diags.Report(SourceLocation(),
11310b57cec5SDimitry Andric diag::err_analyzer_config_no_value) << configVal;
11320b57cec5SDimitry Andric break;
11330b57cec5SDimitry Andric }
1134349cc55cSDimitry Andric if (val.contains('=')) {
11350b57cec5SDimitry Andric Diags.Report(SourceLocation(),
11360b57cec5SDimitry Andric diag::err_analyzer_config_multiple_values)
11370b57cec5SDimitry Andric << configVal;
11380b57cec5SDimitry Andric break;
11390b57cec5SDimitry Andric }
11400b57cec5SDimitry Andric
11410b57cec5SDimitry Andric // TODO: Check checker options too, possibly in CheckerRegistry.
11420b57cec5SDimitry Andric // Leave unknown non-checker configs unclaimed.
11430b57cec5SDimitry Andric if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
11440b57cec5SDimitry Andric if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
11450b57cec5SDimitry Andric Diags.Report(diag::err_analyzer_config_unknown) << key;
11460b57cec5SDimitry Andric continue;
11470b57cec5SDimitry Andric }
11480b57cec5SDimitry Andric
11490b57cec5SDimitry Andric A->claim();
11505ffd83dbSDimitry Andric Opts.Config[key] = std::string(val);
11510b57cec5SDimitry Andric }
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric
11540b57cec5SDimitry Andric if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
11550b57cec5SDimitry Andric parseAnalyzerConfigs(Opts, &Diags);
11560b57cec5SDimitry Andric else
11570b57cec5SDimitry Andric parseAnalyzerConfigs(Opts, nullptr);
11580b57cec5SDimitry Andric
11590b57cec5SDimitry Andric llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
11600b57cec5SDimitry Andric for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
11610b57cec5SDimitry Andric if (i != 0)
11620b57cec5SDimitry Andric os << " ";
11630b57cec5SDimitry Andric os << Args.getArgString(i);
11640b57cec5SDimitry Andric }
11650b57cec5SDimitry Andric os.flush();
11660b57cec5SDimitry Andric
1167fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric
getStringOption(AnalyzerOptions::ConfigTable & Config,StringRef OptionName,StringRef DefaultVal)11700b57cec5SDimitry Andric static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
11710b57cec5SDimitry Andric StringRef OptionName, StringRef DefaultVal) {
11725ffd83dbSDimitry Andric return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
11730b57cec5SDimitry Andric }
11740b57cec5SDimitry Andric
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,StringRef & OptionField,StringRef Name,StringRef DefaultVal)11750b57cec5SDimitry Andric static void initOption(AnalyzerOptions::ConfigTable &Config,
11760b57cec5SDimitry Andric DiagnosticsEngine *Diags,
11770b57cec5SDimitry Andric StringRef &OptionField, StringRef Name,
11780b57cec5SDimitry Andric StringRef DefaultVal) {
11790b57cec5SDimitry Andric // String options may be known to invalid (e.g. if the expected string is a
11800b57cec5SDimitry Andric // file name, but the file does not exist), those will have to be checked in
11810b57cec5SDimitry Andric // parseConfigs.
11820b57cec5SDimitry Andric OptionField = getStringOption(Config, Name, DefaultVal);
11830b57cec5SDimitry Andric }
11840b57cec5SDimitry Andric
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,bool & OptionField,StringRef Name,bool DefaultVal)11850b57cec5SDimitry Andric static void initOption(AnalyzerOptions::ConfigTable &Config,
11860b57cec5SDimitry Andric DiagnosticsEngine *Diags,
11870b57cec5SDimitry Andric bool &OptionField, StringRef Name, bool DefaultVal) {
1188bdd1243dSDimitry Andric auto PossiblyInvalidVal =
1189bdd1243dSDimitry Andric llvm::StringSwitch<std::optional<bool>>(
11900b57cec5SDimitry Andric getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
11910b57cec5SDimitry Andric .Case("true", true)
11920b57cec5SDimitry Andric .Case("false", false)
1193bdd1243dSDimitry Andric .Default(std::nullopt);
11940b57cec5SDimitry Andric
11950b57cec5SDimitry Andric if (!PossiblyInvalidVal) {
11960b57cec5SDimitry Andric if (Diags)
11970b57cec5SDimitry Andric Diags->Report(diag::err_analyzer_config_invalid_input)
11980b57cec5SDimitry Andric << Name << "a boolean";
11990b57cec5SDimitry Andric else
12000b57cec5SDimitry Andric OptionField = DefaultVal;
12010b57cec5SDimitry Andric } else
120281ad6265SDimitry Andric OptionField = *PossiblyInvalidVal;
12030b57cec5SDimitry Andric }
12040b57cec5SDimitry Andric
initOption(AnalyzerOptions::ConfigTable & Config,DiagnosticsEngine * Diags,unsigned & OptionField,StringRef Name,unsigned DefaultVal)12050b57cec5SDimitry Andric static void initOption(AnalyzerOptions::ConfigTable &Config,
12060b57cec5SDimitry Andric DiagnosticsEngine *Diags,
12070b57cec5SDimitry Andric unsigned &OptionField, StringRef Name,
12080b57cec5SDimitry Andric unsigned DefaultVal) {
12090b57cec5SDimitry Andric
12100b57cec5SDimitry Andric OptionField = DefaultVal;
12110b57cec5SDimitry Andric bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
12120b57cec5SDimitry Andric .getAsInteger(0, OptionField);
12130b57cec5SDimitry Andric if (Diags && HasFailed)
12140b57cec5SDimitry Andric Diags->Report(diag::err_analyzer_config_invalid_input)
12150b57cec5SDimitry Andric << Name << "an unsigned";
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric
parseAnalyzerConfigs(AnalyzerOptions & AnOpts,DiagnosticsEngine * Diags)12180b57cec5SDimitry Andric static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
12190b57cec5SDimitry Andric DiagnosticsEngine *Diags) {
12200b57cec5SDimitry Andric // TODO: There's no need to store the entire configtable, it'd be plenty
12210b57cec5SDimitry Andric // enough to store checker options.
12220b57cec5SDimitry Andric
12230b57cec5SDimitry Andric #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
12240b57cec5SDimitry Andric initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
122581ad6265SDimitry Andric #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
122681ad6265SDimitry Andric #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
12270b57cec5SDimitry Andric
122881ad6265SDimitry Andric assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
122981ad6265SDimitry Andric const bool InShallowMode = AnOpts.UserMode == "shallow";
123081ad6265SDimitry Andric
123181ad6265SDimitry Andric #define ANALYZER_OPTION(...)
12320b57cec5SDimitry Andric #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
12330b57cec5SDimitry Andric SHALLOW_VAL, DEEP_VAL) \
123481ad6265SDimitry Andric initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
123581ad6265SDimitry Andric InShallowMode ? SHALLOW_VAL : DEEP_VAL);
12360b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
12370b57cec5SDimitry Andric
12380b57cec5SDimitry Andric // At this point, AnalyzerOptions is configured. Let's validate some options.
12390b57cec5SDimitry Andric
1240a7dea167SDimitry Andric // FIXME: Here we try to validate the silenced checkers or packages are valid.
1241a7dea167SDimitry Andric // The current approach only validates the registered checkers which does not
1242a7dea167SDimitry Andric // contain the runtime enabled checkers and optimally we would validate both.
1243a7dea167SDimitry Andric if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1244a7dea167SDimitry Andric std::vector<StringRef> Checkers =
1245a7dea167SDimitry Andric AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1246a7dea167SDimitry Andric std::vector<StringRef> Packages =
1247a7dea167SDimitry Andric AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1248a7dea167SDimitry Andric
1249a7dea167SDimitry Andric SmallVector<StringRef, 16> CheckersAndPackages;
1250a7dea167SDimitry Andric AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1251a7dea167SDimitry Andric
1252480093f4SDimitry Andric for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1253a7dea167SDimitry Andric if (Diags) {
1254a7dea167SDimitry Andric bool IsChecker = CheckerOrPackage.contains('.');
1255349cc55cSDimitry Andric bool IsValidName = IsChecker
1256349cc55cSDimitry Andric ? llvm::is_contained(Checkers, CheckerOrPackage)
1257349cc55cSDimitry Andric : llvm::is_contained(Packages, CheckerOrPackage);
1258a7dea167SDimitry Andric
1259a7dea167SDimitry Andric if (!IsValidName)
1260a7dea167SDimitry Andric Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1261a7dea167SDimitry Andric << CheckerOrPackage;
1262a7dea167SDimitry Andric }
1263a7dea167SDimitry Andric
1264a7dea167SDimitry Andric AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1265a7dea167SDimitry Andric }
1266a7dea167SDimitry Andric }
1267a7dea167SDimitry Andric
12680b57cec5SDimitry Andric if (!Diags)
12690b57cec5SDimitry Andric return;
12700b57cec5SDimitry Andric
12710b57cec5SDimitry Andric if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
12720b57cec5SDimitry Andric Diags->Report(diag::err_analyzer_config_invalid_input)
12730b57cec5SDimitry Andric << "track-conditions-debug" << "'track-conditions' to also be enabled";
12740b57cec5SDimitry Andric
12750b57cec5SDimitry Andric if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
12760b57cec5SDimitry Andric Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
12770b57cec5SDimitry Andric << "a filename";
12780b57cec5SDimitry Andric
12790b57cec5SDimitry Andric if (!AnOpts.ModelPath.empty() &&
12800b57cec5SDimitry Andric !llvm::sys::fs::is_directory(AnOpts.ModelPath))
12810b57cec5SDimitry Andric Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
12820b57cec5SDimitry Andric << "a filename";
12830b57cec5SDimitry Andric }
12840b57cec5SDimitry Andric
1285fe6060f1SDimitry Andric /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1286fe6060f1SDimitry Andric static void
GenerateOptimizationRemark(ArgumentConsumer Consumer,OptSpecifier OptEQ,StringRef Name,const CodeGenOptions::OptRemark & Remark)1287c9157d92SDimitry Andric GenerateOptimizationRemark(ArgumentConsumer Consumer, OptSpecifier OptEQ,
1288c9157d92SDimitry Andric StringRef Name,
1289fe6060f1SDimitry Andric const CodeGenOptions::OptRemark &Remark) {
1290fe6060f1SDimitry Andric if (Remark.hasValidPattern()) {
1291c9157d92SDimitry Andric GenerateArg(Consumer, OptEQ, Remark.Pattern);
1292fe6060f1SDimitry Andric } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1293c9157d92SDimitry Andric GenerateArg(Consumer, OPT_R_Joined, Name);
1294fe6060f1SDimitry Andric } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1295c9157d92SDimitry Andric GenerateArg(Consumer, OPT_R_Joined, StringRef("no-") + Name);
12960b57cec5SDimitry Andric }
1297fe6060f1SDimitry Andric }
1298fe6060f1SDimitry Andric
1299fe6060f1SDimitry Andric /// Parse a remark command line argument. It may be missing, disabled/enabled by
1300fe6060f1SDimitry Andric /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1301fe6060f1SDimitry Andric /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1302fe6060f1SDimitry Andric static CodeGenOptions::OptRemark
ParseOptimizationRemark(DiagnosticsEngine & Diags,ArgList & Args,OptSpecifier OptEQ,StringRef Name)1303fe6060f1SDimitry Andric ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1304fe6060f1SDimitry Andric OptSpecifier OptEQ, StringRef Name) {
1305fe6060f1SDimitry Andric CodeGenOptions::OptRemark Result;
1306fe6060f1SDimitry Andric
1307349cc55cSDimitry Andric auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1308349cc55cSDimitry Andric StringRef Pattern) {
1309349cc55cSDimitry Andric Result.Pattern = Pattern.str();
1310fe6060f1SDimitry Andric
1311fe6060f1SDimitry Andric std::string RegexError;
1312fe6060f1SDimitry Andric Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1313fe6060f1SDimitry Andric if (!Result.Regex->isValid(RegexError)) {
1314fe6060f1SDimitry Andric Diags.Report(diag::err_drv_optimization_remark_pattern)
1315fe6060f1SDimitry Andric << RegexError << A->getAsString(Args);
1316fe6060f1SDimitry Andric return false;
1317fe6060f1SDimitry Andric }
1318fe6060f1SDimitry Andric
1319fe6060f1SDimitry Andric return true;
1320fe6060f1SDimitry Andric };
1321fe6060f1SDimitry Andric
1322fe6060f1SDimitry Andric for (Arg *A : Args) {
1323fe6060f1SDimitry Andric if (A->getOption().matches(OPT_R_Joined)) {
1324fe6060f1SDimitry Andric StringRef Value = A->getValue();
1325fe6060f1SDimitry Andric
1326fe6060f1SDimitry Andric if (Value == Name)
1327fe6060f1SDimitry Andric Result.Kind = CodeGenOptions::RK_Enabled;
1328fe6060f1SDimitry Andric else if (Value == "everything")
1329fe6060f1SDimitry Andric Result.Kind = CodeGenOptions::RK_EnabledEverything;
1330fe6060f1SDimitry Andric else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1331fe6060f1SDimitry Andric Result.Kind = CodeGenOptions::RK_Disabled;
1332fe6060f1SDimitry Andric else if (Value == "no-everything")
1333fe6060f1SDimitry Andric Result.Kind = CodeGenOptions::RK_DisabledEverything;
1334349cc55cSDimitry Andric else
1335349cc55cSDimitry Andric continue;
1336fe6060f1SDimitry Andric
1337fe6060f1SDimitry Andric if (Result.Kind == CodeGenOptions::RK_Disabled ||
1338fe6060f1SDimitry Andric Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1339fe6060f1SDimitry Andric Result.Pattern = "";
1340fe6060f1SDimitry Andric Result.Regex = nullptr;
1341349cc55cSDimitry Andric } else {
1342349cc55cSDimitry Andric InitializeResultPattern(A, ".*");
1343349cc55cSDimitry Andric }
1344349cc55cSDimitry Andric } else if (A->getOption().matches(OptEQ)) {
1345349cc55cSDimitry Andric Result.Kind = CodeGenOptions::RK_WithPattern;
1346349cc55cSDimitry Andric if (!InitializeResultPattern(A, A->getValue()))
1347349cc55cSDimitry Andric return CodeGenOptions::OptRemark();
1348349cc55cSDimitry Andric }
1349fe6060f1SDimitry Andric }
1350fe6060f1SDimitry Andric
1351fe6060f1SDimitry Andric return Result;
13520b57cec5SDimitry Andric }
13530b57cec5SDimitry Andric
parseDiagnosticLevelMask(StringRef FlagName,const std::vector<std::string> & Levels,DiagnosticsEngine & Diags,DiagnosticLevelMask & M)13540b57cec5SDimitry Andric static bool parseDiagnosticLevelMask(StringRef FlagName,
13550b57cec5SDimitry Andric const std::vector<std::string> &Levels,
1356e8d8bef9SDimitry Andric DiagnosticsEngine &Diags,
13570b57cec5SDimitry Andric DiagnosticLevelMask &M) {
13580b57cec5SDimitry Andric bool Success = true;
13590b57cec5SDimitry Andric for (const auto &Level : Levels) {
13600b57cec5SDimitry Andric DiagnosticLevelMask const PM =
13610b57cec5SDimitry Andric llvm::StringSwitch<DiagnosticLevelMask>(Level)
13620b57cec5SDimitry Andric .Case("note", DiagnosticLevelMask::Note)
13630b57cec5SDimitry Andric .Case("remark", DiagnosticLevelMask::Remark)
13640b57cec5SDimitry Andric .Case("warning", DiagnosticLevelMask::Warning)
13650b57cec5SDimitry Andric .Case("error", DiagnosticLevelMask::Error)
13660b57cec5SDimitry Andric .Default(DiagnosticLevelMask::None);
13670b57cec5SDimitry Andric if (PM == DiagnosticLevelMask::None) {
13680b57cec5SDimitry Andric Success = false;
1369e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
13700b57cec5SDimitry Andric }
13710b57cec5SDimitry Andric M = M | PM;
13720b57cec5SDimitry Andric }
13730b57cec5SDimitry Andric return Success;
13740b57cec5SDimitry Andric }
13750b57cec5SDimitry Andric
parseSanitizerKinds(StringRef FlagName,const std::vector<std::string> & Sanitizers,DiagnosticsEngine & Diags,SanitizerSet & S)13760b57cec5SDimitry Andric static void parseSanitizerKinds(StringRef FlagName,
13770b57cec5SDimitry Andric const std::vector<std::string> &Sanitizers,
13780b57cec5SDimitry Andric DiagnosticsEngine &Diags, SanitizerSet &S) {
13790b57cec5SDimitry Andric for (const auto &Sanitizer : Sanitizers) {
13800b57cec5SDimitry Andric SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
13810b57cec5SDimitry Andric if (K == SanitizerMask())
13820b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
13830b57cec5SDimitry Andric else
13840b57cec5SDimitry Andric S.set(K, true);
13850b57cec5SDimitry Andric }
13860b57cec5SDimitry Andric }
13870b57cec5SDimitry Andric
serializeSanitizerKinds(SanitizerSet S)1388fe6060f1SDimitry Andric static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1389fe6060f1SDimitry Andric SmallVector<StringRef, 4> Values;
1390fe6060f1SDimitry Andric serializeSanitizerSet(S, Values);
1391fe6060f1SDimitry Andric return Values;
1392fe6060f1SDimitry Andric }
1393fe6060f1SDimitry Andric
parseXRayInstrumentationBundle(StringRef FlagName,StringRef Bundle,ArgList & Args,DiagnosticsEngine & D,XRayInstrSet & S)13940b57cec5SDimitry Andric static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
13950b57cec5SDimitry Andric ArgList &Args, DiagnosticsEngine &D,
13960b57cec5SDimitry Andric XRayInstrSet &S) {
13970b57cec5SDimitry Andric llvm::SmallVector<StringRef, 2> BundleParts;
13980b57cec5SDimitry Andric llvm::SplitString(Bundle, BundleParts, ",");
1399480093f4SDimitry Andric for (const auto &B : BundleParts) {
14000b57cec5SDimitry Andric auto Mask = parseXRayInstrValue(B);
14010b57cec5SDimitry Andric if (Mask == XRayInstrKind::None)
14020b57cec5SDimitry Andric if (B != "none")
14030b57cec5SDimitry Andric D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
14040b57cec5SDimitry Andric else
14050b57cec5SDimitry Andric S.Mask = Mask;
14060b57cec5SDimitry Andric else if (Mask == XRayInstrKind::All)
14070b57cec5SDimitry Andric S.Mask = Mask;
14080b57cec5SDimitry Andric else
14090b57cec5SDimitry Andric S.set(Mask, true);
14100b57cec5SDimitry Andric }
14110b57cec5SDimitry Andric }
14120b57cec5SDimitry Andric
serializeXRayInstrumentationBundle(const XRayInstrSet & S)1413fe6060f1SDimitry Andric static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1414fe6060f1SDimitry Andric llvm::SmallVector<StringRef, 2> BundleParts;
1415fe6060f1SDimitry Andric serializeXRayInstrValue(S, BundleParts);
1416fe6060f1SDimitry Andric std::string Buffer;
1417fe6060f1SDimitry Andric llvm::raw_string_ostream OS(Buffer);
1418fe6060f1SDimitry Andric llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
14190eae32dcSDimitry Andric return Buffer;
1420fe6060f1SDimitry Andric }
1421fe6060f1SDimitry Andric
14220b57cec5SDimitry Andric // Set the profile kind using fprofile-instrument-use-path.
setPGOUseInstrumentor(CodeGenOptions & Opts,const Twine & ProfileName,llvm::vfs::FileSystem & FS,DiagnosticsEngine & Diags)14230b57cec5SDimitry Andric static void setPGOUseInstrumentor(CodeGenOptions &Opts,
1424bdd1243dSDimitry Andric const Twine &ProfileName,
1425fe013be4SDimitry Andric llvm::vfs::FileSystem &FS,
1426bdd1243dSDimitry Andric DiagnosticsEngine &Diags) {
1427fe013be4SDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS);
14280b57cec5SDimitry Andric if (auto E = ReaderOrErr.takeError()) {
1429bdd1243dSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1430bdd1243dSDimitry Andric "Error in reading profile %0: %1");
1431bdd1243dSDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1432bdd1243dSDimitry Andric Diags.Report(DiagID) << ProfileName.str() << EI.message();
1433bdd1243dSDimitry Andric });
14340b57cec5SDimitry Andric return;
14350b57cec5SDimitry Andric }
14360b57cec5SDimitry Andric std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
14370b57cec5SDimitry Andric std::move(ReaderOrErr.get());
1438bdd1243dSDimitry Andric // Currently memprof profiles are only added at the IR level. Mark the profile
1439bdd1243dSDimitry Andric // type as IR in that case as well and the subsequent matching needs to detect
1440bdd1243dSDimitry Andric // which is available (might be one or both).
1441bdd1243dSDimitry Andric if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
14420b57cec5SDimitry Andric if (PGOReader->hasCSIRLevelProfile())
14430b57cec5SDimitry Andric Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
14440b57cec5SDimitry Andric else
14450b57cec5SDimitry Andric Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
14460b57cec5SDimitry Andric } else
14470b57cec5SDimitry Andric Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
14480b57cec5SDimitry Andric }
14490b57cec5SDimitry Andric
GenerateCodeGenArgs(const CodeGenOptions & Opts,ArgumentConsumer Consumer,const llvm::Triple & T,const std::string & OutputFile,const LangOptions * LangOpts)1450c9157d92SDimitry Andric void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
1451c9157d92SDimitry Andric ArgumentConsumer Consumer,
1452c9157d92SDimitry Andric const llvm::Triple &T,
1453c9157d92SDimitry Andric const std::string &OutputFile,
1454fe6060f1SDimitry Andric const LangOptions *LangOpts) {
1455fe6060f1SDimitry Andric const CodeGenOptions &CodeGenOpts = Opts;
1456fe6060f1SDimitry Andric
1457fe6060f1SDimitry Andric if (Opts.OptimizationLevel == 0)
1458c9157d92SDimitry Andric GenerateArg(Consumer, OPT_O0);
1459fe6060f1SDimitry Andric else
1460c9157d92SDimitry Andric GenerateArg(Consumer, OPT_O, Twine(Opts.OptimizationLevel));
1461fe6060f1SDimitry Andric
1462fe013be4SDimitry Andric #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1463c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
1464fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
1465fe6060f1SDimitry Andric #undef CODEGEN_OPTION_WITH_MARSHALLING
1466fe6060f1SDimitry Andric
1467fe6060f1SDimitry Andric if (Opts.OptimizationLevel > 0) {
1468fe6060f1SDimitry Andric if (Opts.Inlining == CodeGenOptions::NormalInlining)
1469c9157d92SDimitry Andric GenerateArg(Consumer, OPT_finline_functions);
1470fe6060f1SDimitry Andric else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1471c9157d92SDimitry Andric GenerateArg(Consumer, OPT_finline_hint_functions);
1472fe6060f1SDimitry Andric else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1473c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_inline);
1474fe6060f1SDimitry Andric }
1475fe6060f1SDimitry Andric
1476fe6060f1SDimitry Andric if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1477c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdirect_access_external_data);
1478fe6060f1SDimitry Andric else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1479c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_direct_access_external_data);
1480fe6060f1SDimitry Andric
1481bdd1243dSDimitry Andric std::optional<StringRef> DebugInfoVal;
1482fe6060f1SDimitry Andric switch (Opts.DebugInfo) {
1483fe013be4SDimitry Andric case llvm::codegenoptions::DebugLineTablesOnly:
1484fe6060f1SDimitry Andric DebugInfoVal = "line-tables-only";
1485fe6060f1SDimitry Andric break;
1486fe013be4SDimitry Andric case llvm::codegenoptions::DebugDirectivesOnly:
1487fe6060f1SDimitry Andric DebugInfoVal = "line-directives-only";
1488fe6060f1SDimitry Andric break;
1489fe013be4SDimitry Andric case llvm::codegenoptions::DebugInfoConstructor:
1490fe6060f1SDimitry Andric DebugInfoVal = "constructor";
1491fe6060f1SDimitry Andric break;
1492fe013be4SDimitry Andric case llvm::codegenoptions::LimitedDebugInfo:
1493fe6060f1SDimitry Andric DebugInfoVal = "limited";
1494fe6060f1SDimitry Andric break;
1495fe013be4SDimitry Andric case llvm::codegenoptions::FullDebugInfo:
1496fe6060f1SDimitry Andric DebugInfoVal = "standalone";
1497fe6060f1SDimitry Andric break;
1498fe013be4SDimitry Andric case llvm::codegenoptions::UnusedTypeInfo:
1499fe6060f1SDimitry Andric DebugInfoVal = "unused-types";
1500fe6060f1SDimitry Andric break;
1501fe013be4SDimitry Andric case llvm::codegenoptions::NoDebugInfo: // default value
1502bdd1243dSDimitry Andric DebugInfoVal = std::nullopt;
1503fe6060f1SDimitry Andric break;
1504fe013be4SDimitry Andric case llvm::codegenoptions::LocTrackingOnly: // implied value
1505bdd1243dSDimitry Andric DebugInfoVal = std::nullopt;
1506fe6060f1SDimitry Andric break;
1507fe6060f1SDimitry Andric }
1508fe6060f1SDimitry Andric if (DebugInfoVal)
1509c9157d92SDimitry Andric GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal);
1510fe6060f1SDimitry Andric
1511fe6060f1SDimitry Andric for (const auto &Prefix : Opts.DebugPrefixMap)
1512c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ,
1513c9157d92SDimitry Andric Prefix.first + "=" + Prefix.second);
1514fe6060f1SDimitry Andric
1515fe6060f1SDimitry Andric for (const auto &Prefix : Opts.CoveragePrefixMap)
1516c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ,
1517c9157d92SDimitry Andric Prefix.first + "=" + Prefix.second);
1518fe6060f1SDimitry Andric
1519fe6060f1SDimitry Andric if (Opts.NewStructPathTBAA)
1520c9157d92SDimitry Andric GenerateArg(Consumer, OPT_new_struct_path_tbaa);
1521fe6060f1SDimitry Andric
1522fe6060f1SDimitry Andric if (Opts.OptimizeSize == 1)
1523c9157d92SDimitry Andric GenerateArg(Consumer, OPT_O, "s");
1524fe6060f1SDimitry Andric else if (Opts.OptimizeSize == 2)
1525c9157d92SDimitry Andric GenerateArg(Consumer, OPT_O, "z");
1526fe6060f1SDimitry Andric
1527fe6060f1SDimitry Andric // SimplifyLibCalls is set only in the absence of -fno-builtin and
1528fe6060f1SDimitry Andric // -ffreestanding. We'll consider that when generating them.
1529fe6060f1SDimitry Andric
1530fe6060f1SDimitry Andric // NoBuiltinFuncs are generated by LangOptions.
1531fe6060f1SDimitry Andric
1532fe6060f1SDimitry Andric if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1533c9157d92SDimitry Andric GenerateArg(Consumer, OPT_funroll_loops);
1534fe6060f1SDimitry Andric else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1535c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_unroll_loops);
1536fe6060f1SDimitry Andric
1537fe6060f1SDimitry Andric if (!Opts.BinutilsVersion.empty())
1538c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fbinutils_version_EQ, Opts.BinutilsVersion);
1539fe6060f1SDimitry Andric
1540fe6060f1SDimitry Andric if (Opts.DebugNameTable ==
1541fe6060f1SDimitry Andric static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1542c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ggnu_pubnames);
1543fe6060f1SDimitry Andric else if (Opts.DebugNameTable ==
1544fe6060f1SDimitry Andric static_cast<unsigned>(
1545fe6060f1SDimitry Andric llvm::DICompileUnit::DebugNameTableKind::Default))
1546c9157d92SDimitry Andric GenerateArg(Consumer, OPT_gpubnames);
1547fe6060f1SDimitry Andric
1548349cc55cSDimitry Andric auto TNK = Opts.getDebugSimpleTemplateNames();
1549fe013be4SDimitry Andric if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1550fe013be4SDimitry Andric if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1551c9157d92SDimitry Andric GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple");
1552fe013be4SDimitry Andric else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1553c9157d92SDimitry Andric GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled");
1554349cc55cSDimitry Andric }
1555fe6060f1SDimitry Andric // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1556fe6060f1SDimitry Andric // it or PGOUseInstrumentor.
1557fe6060f1SDimitry Andric
1558fe6060f1SDimitry Andric if (Opts.TimePasses) {
1559fe6060f1SDimitry Andric if (Opts.TimePassesPerRun)
1560c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ftime_report_EQ, "per-pass-run");
1561fe6060f1SDimitry Andric else
1562c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ftime_report);
1563fe6060f1SDimitry Andric }
1564fe6060f1SDimitry Andric
1565fe6060f1SDimitry Andric if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1566c9157d92SDimitry Andric GenerateArg(Consumer, OPT_flto_EQ, "full");
1567fe6060f1SDimitry Andric
1568fe6060f1SDimitry Andric if (Opts.PrepareForThinLTO)
1569c9157d92SDimitry Andric GenerateArg(Consumer, OPT_flto_EQ, "thin");
1570fe6060f1SDimitry Andric
1571fe6060f1SDimitry Andric if (!Opts.ThinLTOIndexFile.empty())
1572c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile);
1573fe6060f1SDimitry Andric
1574fe6060f1SDimitry Andric if (Opts.SaveTempsFilePrefix == OutputFile)
1575c9157d92SDimitry Andric GenerateArg(Consumer, OPT_save_temps_EQ, "obj");
1576fe6060f1SDimitry Andric
1577fe6060f1SDimitry Andric StringRef MemProfileBasename("memprof.profraw");
1578fe6060f1SDimitry Andric if (!Opts.MemoryProfileOutput.empty()) {
1579fe6060f1SDimitry Andric if (Opts.MemoryProfileOutput == MemProfileBasename) {
1580c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fmemory_profile);
1581fe6060f1SDimitry Andric } else {
1582fe6060f1SDimitry Andric size_t ArgLength =
1583fe6060f1SDimitry Andric Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1584c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fmemory_profile_EQ,
1585c9157d92SDimitry Andric Opts.MemoryProfileOutput.substr(0, ArgLength));
1586fe6060f1SDimitry Andric }
1587fe6060f1SDimitry Andric }
1588fe6060f1SDimitry Andric
1589fe6060f1SDimitry Andric if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1590c9157d92SDimitry Andric GenerateArg(Consumer, OPT_coverage_version_EQ,
1591c9157d92SDimitry Andric StringRef(Opts.CoverageVersion, 4));
1592fe6060f1SDimitry Andric
1593fe6060f1SDimitry Andric // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1594fe6060f1SDimitry Andric // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1595fe6060f1SDimitry Andric // won't be generated.)
1596fe6060f1SDimitry Andric
1597fe6060f1SDimitry Andric if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1598fe6060f1SDimitry Andric std::string InstrBundle =
1599fe6060f1SDimitry Andric serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
1600fe6060f1SDimitry Andric if (!InstrBundle.empty())
1601c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fxray_instrumentation_bundle, InstrBundle);
1602fe6060f1SDimitry Andric }
1603fe6060f1SDimitry Andric
1604fe6060f1SDimitry Andric if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1605c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fcf_protection_EQ, "full");
1606fe6060f1SDimitry Andric else if (Opts.CFProtectionReturn)
1607c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fcf_protection_EQ, "return");
1608fe6060f1SDimitry Andric else if (Opts.CFProtectionBranch)
1609c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fcf_protection_EQ, "branch");
1610fe6060f1SDimitry Andric
1611753f127fSDimitry Andric if (Opts.FunctionReturnThunks)
1612c9157d92SDimitry Andric GenerateArg(Consumer, OPT_mfunction_return_EQ, "thunk-extern");
1613753f127fSDimitry Andric
1614fe6060f1SDimitry Andric for (const auto &F : Opts.LinkBitcodeFiles) {
1615fe6060f1SDimitry Andric bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1616fe6060f1SDimitry Andric F.PropagateAttrs && F.Internalize;
1617c9157d92SDimitry Andric GenerateArg(Consumer,
1618fe6060f1SDimitry Andric Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1619c9157d92SDimitry Andric F.Filename);
1620fe6060f1SDimitry Andric }
1621fe6060f1SDimitry Andric
1622fe013be4SDimitry Andric if (Opts.EmulatedTLS)
1623c9157d92SDimitry Andric GenerateArg(Consumer, OPT_femulated_tls);
1624fe6060f1SDimitry Andric
1625fe6060f1SDimitry Andric if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1626c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str());
1627fe6060f1SDimitry Andric
162881ad6265SDimitry Andric if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
162981ad6265SDimitry Andric (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1630c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdenormal_fp_math_f32_EQ,
1631c9157d92SDimitry Andric Opts.FP32DenormalMode.str());
1632fe6060f1SDimitry Andric
1633fe6060f1SDimitry Andric if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1634fe6060f1SDimitry Andric OptSpecifier Opt =
1635fe6060f1SDimitry Andric T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1636c9157d92SDimitry Andric GenerateArg(Consumer, Opt);
1637fe6060f1SDimitry Andric } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1638fe6060f1SDimitry Andric OptSpecifier Opt =
1639fe6060f1SDimitry Andric T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1640c9157d92SDimitry Andric GenerateArg(Consumer, Opt);
1641fe6060f1SDimitry Andric }
1642fe6060f1SDimitry Andric
1643fe6060f1SDimitry Andric if (Opts.EnableAIXExtendedAltivecABI)
1644c9157d92SDimitry Andric GenerateArg(Consumer, OPT_mabi_EQ_vec_extabi);
1645fe6060f1SDimitry Andric
1646fe013be4SDimitry Andric if (Opts.XCOFFReadOnlyPointers)
1647c9157d92SDimitry Andric GenerateArg(Consumer, OPT_mxcoff_roptr);
1648fe013be4SDimitry Andric
1649fe6060f1SDimitry Andric if (!Opts.OptRecordPasses.empty())
1650c9157d92SDimitry Andric GenerateArg(Consumer, OPT_opt_record_passes, Opts.OptRecordPasses);
1651fe6060f1SDimitry Andric
1652fe6060f1SDimitry Andric if (!Opts.OptRecordFormat.empty())
1653c9157d92SDimitry Andric GenerateArg(Consumer, OPT_opt_record_format, Opts.OptRecordFormat);
1654fe6060f1SDimitry Andric
1655c9157d92SDimitry Andric GenerateOptimizationRemark(Consumer, OPT_Rpass_EQ, "pass",
1656fe6060f1SDimitry Andric Opts.OptimizationRemark);
1657fe6060f1SDimitry Andric
1658c9157d92SDimitry Andric GenerateOptimizationRemark(Consumer, OPT_Rpass_missed_EQ, "pass-missed",
1659fe6060f1SDimitry Andric Opts.OptimizationRemarkMissed);
1660fe6060f1SDimitry Andric
1661c9157d92SDimitry Andric GenerateOptimizationRemark(Consumer, OPT_Rpass_analysis_EQ, "pass-analysis",
1662fe6060f1SDimitry Andric Opts.OptimizationRemarkAnalysis);
1663fe6060f1SDimitry Andric
1664c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdiagnostics_hotness_threshold_EQ,
1665fe6060f1SDimitry Andric Opts.DiagnosticsHotnessThreshold
1666fe6060f1SDimitry Andric ? Twine(*Opts.DiagnosticsHotnessThreshold)
1667c9157d92SDimitry Andric : "auto");
1668fe6060f1SDimitry Andric
1669c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdiagnostics_misexpect_tolerance_EQ,
1670c9157d92SDimitry Andric Twine(*Opts.DiagnosticsMisExpectTolerance));
167181ad6265SDimitry Andric
1672fe6060f1SDimitry Andric for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1673c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fsanitize_recover_EQ, Sanitizer);
1674fe6060f1SDimitry Andric
1675fe6060f1SDimitry Andric for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1676c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fsanitize_trap_EQ, Sanitizer);
1677fe6060f1SDimitry Andric
1678fe6060f1SDimitry Andric if (!Opts.EmitVersionIdentMetadata)
1679c9157d92SDimitry Andric GenerateArg(Consumer, OPT_Qn);
1680fe6060f1SDimitry Andric
1681fe6060f1SDimitry Andric switch (Opts.FiniteLoops) {
1682fe6060f1SDimitry Andric case CodeGenOptions::FiniteLoopsKind::Language:
1683fe6060f1SDimitry Andric break;
1684fe6060f1SDimitry Andric case CodeGenOptions::FiniteLoopsKind::Always:
1685c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ffinite_loops);
1686fe6060f1SDimitry Andric break;
1687fe6060f1SDimitry Andric case CodeGenOptions::FiniteLoopsKind::Never:
1688c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_finite_loops);
1689fe6060f1SDimitry Andric break;
1690fe6060f1SDimitry Andric }
1691fe6060f1SDimitry Andric }
1692fe6060f1SDimitry Andric
ParseCodeGenArgs(CodeGenOptions & Opts,ArgList & Args,InputKind IK,DiagnosticsEngine & Diags,const llvm::Triple & T,const std::string & OutputFile,const LangOptions & LangOptsRef)1693e8d8bef9SDimitry Andric bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1694e8d8bef9SDimitry Andric InputKind IK,
16950b57cec5SDimitry Andric DiagnosticsEngine &Diags,
1696e8d8bef9SDimitry Andric const llvm::Triple &T,
1697e8d8bef9SDimitry Andric const std::string &OutputFile,
1698e8d8bef9SDimitry Andric const LangOptions &LangOptsRef) {
1699fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
17000b57cec5SDimitry Andric
17010b57cec5SDimitry Andric unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
17020b57cec5SDimitry Andric // TODO: This could be done in Driver
17030b57cec5SDimitry Andric unsigned MaxOptLevel = 3;
17040b57cec5SDimitry Andric if (OptimizationLevel > MaxOptLevel) {
17050b57cec5SDimitry Andric // If the optimization level is not supported, fall back on the default
17060b57cec5SDimitry Andric // optimization
17070b57cec5SDimitry Andric Diags.Report(diag::warn_drv_optimization_value)
17080b57cec5SDimitry Andric << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
17090b57cec5SDimitry Andric OptimizationLevel = MaxOptLevel;
17100b57cec5SDimitry Andric }
17110b57cec5SDimitry Andric Opts.OptimizationLevel = OptimizationLevel;
17120b57cec5SDimitry Andric
1713e8d8bef9SDimitry Andric // The key paths of codegen options defined in Options.td start with
1714e8d8bef9SDimitry Andric // "CodeGenOpts.". Let's provide the expected variable name and type.
1715e8d8bef9SDimitry Andric CodeGenOptions &CodeGenOpts = Opts;
1716e8d8bef9SDimitry Andric // Some codegen options depend on language options. Let's provide the expected
1717e8d8bef9SDimitry Andric // variable name and type.
1718e8d8bef9SDimitry Andric const LangOptions *LangOpts = &LangOptsRef;
1719e8d8bef9SDimitry Andric
1720fe013be4SDimitry Andric #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1721fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1722e8d8bef9SDimitry Andric #include "clang/Driver/Options.inc"
1723e8d8bef9SDimitry Andric #undef CODEGEN_OPTION_WITH_MARSHALLING
1724e8d8bef9SDimitry Andric
17250b57cec5SDimitry Andric // At O0 we want to fully disable inlining outside of cases marked with
17260b57cec5SDimitry Andric // 'alwaysinline' that are required for correctness.
172781ad6265SDimitry Andric if (Opts.OptimizationLevel == 0) {
172881ad6265SDimitry Andric Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
172981ad6265SDimitry Andric } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
173081ad6265SDimitry Andric options::OPT_finline_hint_functions,
173181ad6265SDimitry Andric options::OPT_fno_inline_functions,
173281ad6265SDimitry Andric options::OPT_fno_inline)) {
17330b57cec5SDimitry Andric // Explicit inlining flags can disable some or all inlining even at
17340b57cec5SDimitry Andric // optimization levels above zero.
173581ad6265SDimitry Andric if (A->getOption().matches(options::OPT_finline_functions))
17360b57cec5SDimitry Andric Opts.setInlining(CodeGenOptions::NormalInlining);
173781ad6265SDimitry Andric else if (A->getOption().matches(options::OPT_finline_hint_functions))
17380b57cec5SDimitry Andric Opts.setInlining(CodeGenOptions::OnlyHintInlining);
17390b57cec5SDimitry Andric else
17400b57cec5SDimitry Andric Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
174181ad6265SDimitry Andric } else {
174281ad6265SDimitry Andric Opts.setInlining(CodeGenOptions::NormalInlining);
17430b57cec5SDimitry Andric }
17440b57cec5SDimitry Andric
1745e8d8bef9SDimitry Andric // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1746e8d8bef9SDimitry Andric // -fdirect-access-external-data.
1747e8d8bef9SDimitry Andric Opts.DirectAccessExternalData =
1748e8d8bef9SDimitry Andric Args.hasArg(OPT_fdirect_access_external_data) ||
1749e8d8bef9SDimitry Andric (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1750fe6060f1SDimitry Andric LangOpts->PICLevel == 0);
1751fe6060f1SDimitry Andric
1752fe6060f1SDimitry Andric if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1753fe6060f1SDimitry Andric unsigned Val =
1754fe6060f1SDimitry Andric llvm::StringSwitch<unsigned>(A->getValue())
1755fe013be4SDimitry Andric .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
1756fe013be4SDimitry Andric .Case("line-directives-only",
1757fe013be4SDimitry Andric llvm::codegenoptions::DebugDirectivesOnly)
1758fe013be4SDimitry Andric .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
1759fe013be4SDimitry Andric .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
1760fe013be4SDimitry Andric .Case("standalone", llvm::codegenoptions::FullDebugInfo)
1761fe013be4SDimitry Andric .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
1762fe6060f1SDimitry Andric .Default(~0U);
1763fe6060f1SDimitry Andric if (Val == ~0U)
1764fe6060f1SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1765fe6060f1SDimitry Andric << A->getValue();
1766fe6060f1SDimitry Andric else
1767fe013be4SDimitry Andric Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
1768fe6060f1SDimitry Andric }
17690b57cec5SDimitry Andric
1770e8d8bef9SDimitry Andric // If -fuse-ctor-homing is set and limited debug info is already on, then use
1771fe6060f1SDimitry Andric // constructor homing, and vice versa for -fno-use-ctor-homing.
1772fe6060f1SDimitry Andric if (const Arg *A =
1773fe6060f1SDimitry Andric Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1774fe6060f1SDimitry Andric if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1775fe013be4SDimitry Andric Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1776fe013be4SDimitry Andric Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1777fe6060f1SDimitry Andric if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1778fe013be4SDimitry Andric Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1779fe013be4SDimitry Andric Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1780fe6060f1SDimitry Andric }
17810b57cec5SDimitry Andric
17825ffd83dbSDimitry Andric for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
17835ffd83dbSDimitry Andric auto Split = StringRef(Arg).split('=');
1784fe013be4SDimitry Andric Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);
17855ffd83dbSDimitry Andric }
17860b57cec5SDimitry Andric
1787fe6060f1SDimitry Andric for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1788e8d8bef9SDimitry Andric auto Split = StringRef(Arg).split('=');
1789fe013be4SDimitry Andric Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second);
1790e8d8bef9SDimitry Andric }
17910b57cec5SDimitry Andric
1792a7dea167SDimitry Andric const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1793a7dea167SDimitry Andric llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
17945ffd83dbSDimitry Andric llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
17955ffd83dbSDimitry Andric llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1796a7dea167SDimitry Andric
1797480093f4SDimitry Andric if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1798a7dea167SDimitry Andric llvm::is_contained(DebugEntryValueArchs, T.getArch()))
17995ffd83dbSDimitry Andric Opts.EmitCallSiteInfo = true;
18000b57cec5SDimitry Andric
1801fe6060f1SDimitry Andric if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1802fe6060f1SDimitry Andric Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1803fe6060f1SDimitry Andric << Opts.DIBugsReportFilePath;
1804fe6060f1SDimitry Andric Opts.DIBugsReportFilePath = "";
1805fe6060f1SDimitry Andric }
1806fe6060f1SDimitry Andric
18070b57cec5SDimitry Andric Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
18080b57cec5SDimitry Andric Args.hasArg(OPT_new_struct_path_tbaa);
18090b57cec5SDimitry Andric Opts.OptimizeSize = getOptimizationLevelSize(Args);
1810fe6060f1SDimitry Andric Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
18110b57cec5SDimitry Andric if (Opts.SimplifyLibCalls)
1812fe6060f1SDimitry Andric Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
18130b57cec5SDimitry Andric Opts.UnrollLoops =
18140b57cec5SDimitry Andric Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
18150b57cec5SDimitry Andric (Opts.OptimizationLevel > 1));
1816e8d8bef9SDimitry Andric Opts.BinutilsVersion =
1817e8d8bef9SDimitry Andric std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1818e8d8bef9SDimitry Andric
18190b57cec5SDimitry Andric Opts.DebugNameTable = static_cast<unsigned>(
18200b57cec5SDimitry Andric Args.hasArg(OPT_ggnu_pubnames)
18210b57cec5SDimitry Andric ? llvm::DICompileUnit::DebugNameTableKind::GNU
18220b57cec5SDimitry Andric : Args.hasArg(OPT_gpubnames)
18230b57cec5SDimitry Andric ? llvm::DICompileUnit::DebugNameTableKind::Default
18240b57cec5SDimitry Andric : llvm::DICompileUnit::DebugNameTableKind::None);
1825349cc55cSDimitry Andric if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1826349cc55cSDimitry Andric StringRef Value = A->getValue();
1827349cc55cSDimitry Andric if (Value != "simple" && Value != "mangled")
1828349cc55cSDimitry Andric Diags.Report(diag::err_drv_unsupported_option_argument)
1829bdd1243dSDimitry Andric << A->getSpelling() << A->getValue();
1830349cc55cSDimitry Andric Opts.setDebugSimpleTemplateNames(
1831349cc55cSDimitry Andric StringRef(A->getValue()) == "simple"
1832fe013be4SDimitry Andric ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1833fe013be4SDimitry Andric : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1834349cc55cSDimitry Andric }
18350b57cec5SDimitry Andric
1836e8d8bef9SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1837e8d8bef9SDimitry Andric Opts.TimePasses = true;
1838e8d8bef9SDimitry Andric
1839e8d8bef9SDimitry Andric // -ftime-report= is only for new pass manager.
1840e8d8bef9SDimitry Andric if (A->getOption().getID() == OPT_ftime_report_EQ) {
1841e8d8bef9SDimitry Andric StringRef Val = A->getValue();
1842e8d8bef9SDimitry Andric if (Val == "per-pass")
1843e8d8bef9SDimitry Andric Opts.TimePassesPerRun = false;
1844e8d8bef9SDimitry Andric else if (Val == "per-pass-run")
1845e8d8bef9SDimitry Andric Opts.TimePassesPerRun = true;
1846e8d8bef9SDimitry Andric else
18470b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
1848e8d8bef9SDimitry Andric << A->getAsString(Args) << A->getValue();
1849e8d8bef9SDimitry Andric }
1850e8d8bef9SDimitry Andric }
18515ffd83dbSDimitry Andric
1852349cc55cSDimitry Andric Opts.PrepareForLTO = false;
18530b57cec5SDimitry Andric Opts.PrepareForThinLTO = false;
18540b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1855349cc55cSDimitry Andric Opts.PrepareForLTO = true;
18560b57cec5SDimitry Andric StringRef S = A->getValue();
18570b57cec5SDimitry Andric if (S == "thin")
18580b57cec5SDimitry Andric Opts.PrepareForThinLTO = true;
18590b57cec5SDimitry Andric else if (S != "full")
18600b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1861fe013be4SDimitry Andric if (Args.hasArg(OPT_funified_lto))
1862fe013be4SDimitry Andric Opts.PrepareForThinLTO = true;
18630b57cec5SDimitry Andric }
18640b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1865a7dea167SDimitry Andric if (IK.getLanguage() != Language::LLVM_IR)
18660b57cec5SDimitry Andric Diags.Report(diag::err_drv_argument_only_allowed_with)
18670b57cec5SDimitry Andric << A->getAsString(Args) << "-x ir";
18685ffd83dbSDimitry Andric Opts.ThinLTOIndexFile =
18695ffd83dbSDimitry Andric std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
18700b57cec5SDimitry Andric }
18710b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
18720b57cec5SDimitry Andric Opts.SaveTempsFilePrefix =
18730b57cec5SDimitry Andric llvm::StringSwitch<std::string>(A->getValue())
1874e8d8bef9SDimitry Andric .Case("obj", OutputFile)
1875e8d8bef9SDimitry Andric .Default(llvm::sys::path::filename(OutputFile).str());
18760b57cec5SDimitry Andric
1877e8d8bef9SDimitry Andric // The memory profile runtime appends the pid to make this name more unique.
1878e8d8bef9SDimitry Andric const char *MemProfileBasename = "memprof.profraw";
1879e8d8bef9SDimitry Andric if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1880e8d8bef9SDimitry Andric SmallString<128> Path(
1881e8d8bef9SDimitry Andric std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1882e8d8bef9SDimitry Andric llvm::sys::path::append(Path, MemProfileBasename);
1883e8d8bef9SDimitry Andric Opts.MemoryProfileOutput = std::string(Path);
1884e8d8bef9SDimitry Andric } else if (Args.hasArg(OPT_fmemory_profile))
1885e8d8bef9SDimitry Andric Opts.MemoryProfileOutput = MemProfileBasename;
18860b57cec5SDimitry Andric
1887fe6060f1SDimitry Andric memcpy(Opts.CoverageVersion, "408*", 4);
1888fe013be4SDimitry Andric if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) {
18890b57cec5SDimitry Andric if (Args.hasArg(OPT_coverage_version_EQ)) {
18900b57cec5SDimitry Andric StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
18910b57cec5SDimitry Andric if (CoverageVersion.size() != 4) {
18920b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
18930b57cec5SDimitry Andric << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
18940b57cec5SDimitry Andric << CoverageVersion;
18950b57cec5SDimitry Andric } else {
18960b57cec5SDimitry Andric memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
18970b57cec5SDimitry Andric }
18980b57cec5SDimitry Andric }
18990b57cec5SDimitry Andric }
19000b57cec5SDimitry Andric // FIXME: For backend options that are not yet recorded as function
19010b57cec5SDimitry Andric // attributes in the IR, keep track of them so we can embed them in a
19020b57cec5SDimitry Andric // separate data section and use them when building the bitcode.
19030b57cec5SDimitry Andric for (const auto &A : Args) {
19040b57cec5SDimitry Andric // Do not encode output and input.
19050b57cec5SDimitry Andric if (A->getOption().getID() == options::OPT_o ||
19060b57cec5SDimitry Andric A->getOption().getID() == options::OPT_INPUT ||
19070b57cec5SDimitry Andric A->getOption().getID() == options::OPT_x ||
19080b57cec5SDimitry Andric A->getOption().getID() == options::OPT_fembed_bitcode ||
19095ffd83dbSDimitry Andric A->getOption().matches(options::OPT_W_Group))
19100b57cec5SDimitry Andric continue;
19110b57cec5SDimitry Andric ArgStringList ASL;
19120b57cec5SDimitry Andric A->render(Args, ASL);
19130b57cec5SDimitry Andric for (const auto &arg : ASL) {
19140b57cec5SDimitry Andric StringRef ArgStr(arg);
19150b57cec5SDimitry Andric Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
19160b57cec5SDimitry Andric // using \00 to separate each commandline options.
19170b57cec5SDimitry Andric Opts.CmdArgs.push_back('\0');
19180b57cec5SDimitry Andric }
19190b57cec5SDimitry Andric }
19200b57cec5SDimitry Andric
19210b57cec5SDimitry Andric auto XRayInstrBundles =
19220b57cec5SDimitry Andric Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
19230b57cec5SDimitry Andric if (XRayInstrBundles.empty())
19240b57cec5SDimitry Andric Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
19250b57cec5SDimitry Andric else
19260b57cec5SDimitry Andric for (const auto &A : XRayInstrBundles)
19270b57cec5SDimitry Andric parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
19280b57cec5SDimitry Andric Diags, Opts.XRayInstrumentationBundle);
19290b57cec5SDimitry Andric
19300b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
19310b57cec5SDimitry Andric StringRef Name = A->getValue();
19320b57cec5SDimitry Andric if (Name == "full") {
19330b57cec5SDimitry Andric Opts.CFProtectionReturn = 1;
19340b57cec5SDimitry Andric Opts.CFProtectionBranch = 1;
19350b57cec5SDimitry Andric } else if (Name == "return")
19360b57cec5SDimitry Andric Opts.CFProtectionReturn = 1;
19370b57cec5SDimitry Andric else if (Name == "branch")
19380b57cec5SDimitry Andric Opts.CFProtectionBranch = 1;
1939fe6060f1SDimitry Andric else if (Name != "none")
19400b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
19410b57cec5SDimitry Andric }
19420b57cec5SDimitry Andric
1943753f127fSDimitry Andric if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
1944753f127fSDimitry Andric auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
1945753f127fSDimitry Andric .Case("keep", llvm::FunctionReturnThunksKind::Keep)
1946753f127fSDimitry Andric .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern)
1947753f127fSDimitry Andric .Default(llvm::FunctionReturnThunksKind::Invalid);
1948753f127fSDimitry Andric // SystemZ might want to add support for "expolines."
1949753f127fSDimitry Andric if (!T.isX86())
1950753f127fSDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
1951753f127fSDimitry Andric << A->getSpelling() << T.getTriple();
1952753f127fSDimitry Andric else if (Val == llvm::FunctionReturnThunksKind::Invalid)
1953753f127fSDimitry Andric Diags.Report(diag::err_drv_invalid_value)
1954753f127fSDimitry Andric << A->getAsString(Args) << A->getValue();
1955753f127fSDimitry Andric else if (Val == llvm::FunctionReturnThunksKind::Extern &&
1956753f127fSDimitry Andric Args.getLastArgValue(OPT_mcmodel_EQ).equals("large"))
1957753f127fSDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
1958753f127fSDimitry Andric << A->getAsString(Args)
1959753f127fSDimitry Andric << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
1960753f127fSDimitry Andric else
1961753f127fSDimitry Andric Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
1962753f127fSDimitry Andric }
1963753f127fSDimitry Andric
19640b57cec5SDimitry Andric for (auto *A :
19650b57cec5SDimitry Andric Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
19660b57cec5SDimitry Andric CodeGenOptions::BitcodeFileToLink F;
19670b57cec5SDimitry Andric F.Filename = A->getValue();
19680b57cec5SDimitry Andric if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
19690b57cec5SDimitry Andric F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
19700b57cec5SDimitry Andric // When linking CUDA bitcode, propagate function attributes so that
19710b57cec5SDimitry Andric // e.g. libdevice gets fast-math attrs if we're building with fast-math.
19720b57cec5SDimitry Andric F.PropagateAttrs = true;
19730b57cec5SDimitry Andric F.Internalize = true;
19740b57cec5SDimitry Andric }
19750b57cec5SDimitry Andric Opts.LinkBitcodeFiles.push_back(F);
19760b57cec5SDimitry Andric }
19770b57cec5SDimitry Andric
1978fe6060f1SDimitry Andric if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1979fe6060f1SDimitry Andric if (T.isOSAIX()) {
1980fe6060f1SDimitry Andric StringRef Name = A->getValue();
1981c9157d92SDimitry Andric if (Name == "local-dynamic")
1982fe6060f1SDimitry Andric Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
1983fe6060f1SDimitry Andric }
1984fe6060f1SDimitry Andric }
1985fe6060f1SDimitry Andric
19860b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
19870b57cec5SDimitry Andric StringRef Val = A->getValue();
1988480093f4SDimitry Andric Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
198981ad6265SDimitry Andric Opts.FP32DenormalMode = Opts.FPDenormalMode;
19905ffd83dbSDimitry Andric if (!Opts.FPDenormalMode.isValid())
19915ffd83dbSDimitry Andric Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
19925ffd83dbSDimitry Andric }
19935ffd83dbSDimitry Andric
19945ffd83dbSDimitry Andric if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
19955ffd83dbSDimitry Andric StringRef Val = A->getValue();
19965ffd83dbSDimitry Andric Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
19975ffd83dbSDimitry Andric if (!Opts.FP32DenormalMode.isValid())
19980b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric
2001e86cf8adSDimitry Andric // X86_32 has -fppc-struct-return and -freg-struct-return.
2002e86cf8adSDimitry Andric // PPC32 has -maix-struct-return and -msvr4-struct-return.
2003e86cf8adSDimitry Andric if (Arg *A =
2004e86cf8adSDimitry Andric Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
2005e86cf8adSDimitry Andric OPT_maix_struct_return, OPT_msvr4_struct_return)) {
20065ffd83dbSDimitry Andric // TODO: We might want to consider enabling these options on AIX in the
20075ffd83dbSDimitry Andric // future.
20085ffd83dbSDimitry Andric if (T.isOSAIX())
20095ffd83dbSDimitry Andric Diags.Report(diag::err_drv_unsupported_opt_for_target)
20105ffd83dbSDimitry Andric << A->getSpelling() << T.str();
20115ffd83dbSDimitry Andric
2012e86cf8adSDimitry Andric const Option &O = A->getOption();
2013e86cf8adSDimitry Andric if (O.matches(OPT_fpcc_struct_return) ||
2014e86cf8adSDimitry Andric O.matches(OPT_maix_struct_return)) {
20150b57cec5SDimitry Andric Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
20160b57cec5SDimitry Andric } else {
2017e86cf8adSDimitry Andric assert(O.matches(OPT_freg_struct_return) ||
2018e86cf8adSDimitry Andric O.matches(OPT_msvr4_struct_return));
20190b57cec5SDimitry Andric Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
20200b57cec5SDimitry Andric }
20210b57cec5SDimitry Andric }
20220b57cec5SDimitry Andric
2023fe013be4SDimitry Andric if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) {
2024e8d8bef9SDimitry Andric if (!T.isOSAIX())
2025e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_unsupported_opt_for_target)
2026e8d8bef9SDimitry Andric << A->getSpelling() << T.str();
2027e8d8bef9SDimitry Andric
2028fe013be4SDimitry Andric // Since the storage mapping class is specified per csect,
2029fe013be4SDimitry Andric // without using data sections, it is less effective to use read-only
2030fe013be4SDimitry Andric // pointers. Using read-only pointers may cause other RO variables in the
2031fe013be4SDimitry Andric // same csect to become RW when the linker acts upon `-bforceimprw`;
2032fe013be4SDimitry Andric // therefore, we require that separate data sections
2033fe013be4SDimitry Andric // are used when `-mxcoff-roptr` is in effect. We respect the setting of
2034fe013be4SDimitry Andric // data-sections since we have not found reasons to do otherwise that
2035fe013be4SDimitry Andric // overcome the user surprise of not respecting the setting.
2036fe013be4SDimitry Andric if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false))
2037fe013be4SDimitry Andric Diags.Report(diag::err_roptr_requires_data_sections);
2038fe013be4SDimitry Andric
2039fe013be4SDimitry Andric Opts.XCOFFReadOnlyPointers = true;
2040e8d8bef9SDimitry Andric }
2041e8d8bef9SDimitry Andric
2042972a253aSDimitry Andric if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
2043972a253aSDimitry Andric if (!T.isOSAIX() || T.isPPC32())
2044972a253aSDimitry Andric Diags.Report(diag::err_drv_unsupported_opt_for_target)
2045972a253aSDimitry Andric << A->getSpelling() << T.str();
2046972a253aSDimitry Andric }
2047972a253aSDimitry Andric
20480b57cec5SDimitry Andric bool NeedLocTracking = false;
20490b57cec5SDimitry Andric
20500b57cec5SDimitry Andric if (!Opts.OptRecordFile.empty())
20510b57cec5SDimitry Andric NeedLocTracking = true;
20520b57cec5SDimitry Andric
20530b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
20540b57cec5SDimitry Andric Opts.OptRecordPasses = A->getValue();
20550b57cec5SDimitry Andric NeedLocTracking = true;
20560b57cec5SDimitry Andric }
20570b57cec5SDimitry Andric
20580b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
20590b57cec5SDimitry Andric Opts.OptRecordFormat = A->getValue();
20600b57cec5SDimitry Andric NeedLocTracking = true;
20610b57cec5SDimitry Andric }
20620b57cec5SDimitry Andric
2063fe6060f1SDimitry Andric Opts.OptimizationRemark =
2064fe6060f1SDimitry Andric ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
20650b57cec5SDimitry Andric
2066fe6060f1SDimitry Andric Opts.OptimizationRemarkMissed =
2067fe6060f1SDimitry Andric ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
20680b57cec5SDimitry Andric
2069fe6060f1SDimitry Andric Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
2070fe6060f1SDimitry Andric Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
2071fe6060f1SDimitry Andric
2072fe6060f1SDimitry Andric NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
2073fe6060f1SDimitry Andric Opts.OptimizationRemarkMissed.hasValidPattern() ||
2074fe6060f1SDimitry Andric Opts.OptimizationRemarkAnalysis.hasValidPattern();
20750b57cec5SDimitry Andric
20760b57cec5SDimitry Andric bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
2077fe013be4SDimitry Andric bool UsingProfile =
2078fe013be4SDimitry Andric UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
20790b57cec5SDimitry Andric
20800b57cec5SDimitry Andric if (Opts.DiagnosticsWithHotness && !UsingProfile &&
20810b57cec5SDimitry Andric // An IR file will contain PGO as metadata
2082a7dea167SDimitry Andric IK.getLanguage() != Language::LLVM_IR)
20830b57cec5SDimitry Andric Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
20840b57cec5SDimitry Andric << "-fdiagnostics-show-hotness";
20850b57cec5SDimitry Andric
2086e8d8bef9SDimitry Andric // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
2087e8d8bef9SDimitry Andric if (auto *arg =
2088e8d8bef9SDimitry Andric Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2089e8d8bef9SDimitry Andric auto ResultOrErr =
2090e8d8bef9SDimitry Andric llvm::remarks::parseHotnessThresholdOption(arg->getValue());
2091e8d8bef9SDimitry Andric
2092e8d8bef9SDimitry Andric if (!ResultOrErr) {
2093e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
2094e8d8bef9SDimitry Andric << "-fdiagnostics-hotness-threshold=";
2095e8d8bef9SDimitry Andric } else {
2096e8d8bef9SDimitry Andric Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
209781ad6265SDimitry Andric if ((!Opts.DiagnosticsHotnessThreshold ||
2098bdd1243dSDimitry Andric *Opts.DiagnosticsHotnessThreshold > 0) &&
2099e8d8bef9SDimitry Andric !UsingProfile)
21000b57cec5SDimitry Andric Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
21010b57cec5SDimitry Andric << "-fdiagnostics-hotness-threshold=";
2102e8d8bef9SDimitry Andric }
2103e8d8bef9SDimitry Andric }
21040b57cec5SDimitry Andric
210581ad6265SDimitry Andric if (auto *arg =
210681ad6265SDimitry Andric Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
210781ad6265SDimitry Andric auto ResultOrErr = parseToleranceOption(arg->getValue());
210881ad6265SDimitry Andric
210981ad6265SDimitry Andric if (!ResultOrErr) {
211081ad6265SDimitry Andric Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
211181ad6265SDimitry Andric << "-fdiagnostics-misexpect-tolerance=";
211281ad6265SDimitry Andric } else {
211381ad6265SDimitry Andric Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
211481ad6265SDimitry Andric if ((!Opts.DiagnosticsMisExpectTolerance ||
2115bdd1243dSDimitry Andric *Opts.DiagnosticsMisExpectTolerance > 0) &&
211681ad6265SDimitry Andric !UsingProfile)
211781ad6265SDimitry Andric Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
211881ad6265SDimitry Andric << "-fdiagnostics-misexpect-tolerance=";
211981ad6265SDimitry Andric }
212081ad6265SDimitry Andric }
212181ad6265SDimitry Andric
21220b57cec5SDimitry Andric // If the user requested to use a sample profile for PGO, then the
21230b57cec5SDimitry Andric // backend will need to track source location information so the profile
21240b57cec5SDimitry Andric // can be incorporated into the IR.
21250b57cec5SDimitry Andric if (UsingSampleProfile)
21260b57cec5SDimitry Andric NeedLocTracking = true;
21270b57cec5SDimitry Andric
2128fe6060f1SDimitry Andric if (!Opts.StackUsageOutput.empty())
2129fe6060f1SDimitry Andric NeedLocTracking = true;
2130fe6060f1SDimitry Andric
21310b57cec5SDimitry Andric // If the user requested a flag that requires source locations available in
21320b57cec5SDimitry Andric // the backend, make sure that the backend tracks source location information.
2133fe013be4SDimitry Andric if (NeedLocTracking &&
2134fe013be4SDimitry Andric Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2135fe013be4SDimitry Andric Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
21360b57cec5SDimitry Andric
21370b57cec5SDimitry Andric // Parse -fsanitize-recover= arguments.
21380b57cec5SDimitry Andric // FIXME: Report unrecoverable sanitizers incorrectly specified here.
21390b57cec5SDimitry Andric parseSanitizerKinds("-fsanitize-recover=",
21400b57cec5SDimitry Andric Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
21410b57cec5SDimitry Andric Opts.SanitizeRecover);
21420b57cec5SDimitry Andric parseSanitizerKinds("-fsanitize-trap=",
21430b57cec5SDimitry Andric Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
21440b57cec5SDimitry Andric Opts.SanitizeTrap);
21450b57cec5SDimitry Andric
21460b57cec5SDimitry Andric Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
21470b57cec5SDimitry Andric
2148d409305fSDimitry Andric if (Args.hasArg(options::OPT_ffinite_loops))
2149d409305fSDimitry Andric Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2150d409305fSDimitry Andric else if (Args.hasArg(options::OPT_fno_finite_loops))
2151d409305fSDimitry Andric Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2152fe6060f1SDimitry Andric
215381ad6265SDimitry Andric Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
215481ad6265SDimitry Andric options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
2155fe6060f1SDimitry Andric if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2156fe6060f1SDimitry Andric Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2157fe6060f1SDimitry Andric
2158fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
21590b57cec5SDimitry Andric }
21600b57cec5SDimitry Andric
GenerateDependencyOutputArgs(const DependencyOutputOptions & Opts,ArgumentConsumer Consumer)2161c9157d92SDimitry Andric static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
2162c9157d92SDimitry Andric ArgumentConsumer Consumer) {
2163fe6060f1SDimitry Andric const DependencyOutputOptions &DependencyOutputOpts = Opts;
2164fe013be4SDimitry Andric #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2165c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2166fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2167fe6060f1SDimitry Andric #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2168fe6060f1SDimitry Andric
2169fe6060f1SDimitry Andric if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
2170c9157d92SDimitry Andric GenerateArg(Consumer, OPT_show_includes);
2171fe6060f1SDimitry Andric
2172fe6060f1SDimitry Andric for (const auto &Dep : Opts.ExtraDeps) {
2173fe6060f1SDimitry Andric switch (Dep.second) {
2174fe6060f1SDimitry Andric case EDK_SanitizeIgnorelist:
2175fe6060f1SDimitry Andric // Sanitizer ignorelist arguments are generated from LanguageOptions.
2176fe6060f1SDimitry Andric continue;
2177fe6060f1SDimitry Andric case EDK_ModuleFile:
2178fe6060f1SDimitry Andric // Module file arguments are generated from FrontendOptions and
2179fe6060f1SDimitry Andric // HeaderSearchOptions.
2180fe6060f1SDimitry Andric continue;
2181fe6060f1SDimitry Andric case EDK_ProfileList:
2182fe6060f1SDimitry Andric // Profile list arguments are generated from LanguageOptions via the
2183fe6060f1SDimitry Andric // marshalling infrastructure.
2184fe6060f1SDimitry Andric continue;
2185fe6060f1SDimitry Andric case EDK_DepFileEntry:
2186c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdepfile_entry, Dep.first);
2187fe6060f1SDimitry Andric break;
2188fe6060f1SDimitry Andric }
2189fe6060f1SDimitry Andric }
2190fe6060f1SDimitry Andric }
2191fe6060f1SDimitry Andric
ParseDependencyOutputArgs(DependencyOutputOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action,bool ShowLineMarkers)2192fe6060f1SDimitry Andric static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
2193fe6060f1SDimitry Andric ArgList &Args, DiagnosticsEngine &Diags,
2194fe6060f1SDimitry Andric frontend::ActionKind Action,
2195fe6060f1SDimitry Andric bool ShowLineMarkers) {
2196fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
2197fe6060f1SDimitry Andric
2198fe6060f1SDimitry Andric DependencyOutputOptions &DependencyOutputOpts = Opts;
2199fe013be4SDimitry Andric #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2200fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2201fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2202fe6060f1SDimitry Andric #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2203fe6060f1SDimitry Andric
22040b57cec5SDimitry Andric if (Args.hasArg(OPT_show_includes)) {
22050b57cec5SDimitry Andric // Writing both /showIncludes and preprocessor output to stdout
22060b57cec5SDimitry Andric // would produce interleaved output, so use stderr for /showIncludes.
22070b57cec5SDimitry Andric // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2208fe6060f1SDimitry Andric if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
22090b57cec5SDimitry Andric Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
22100b57cec5SDimitry Andric else
22110b57cec5SDimitry Andric Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
22120b57cec5SDimitry Andric } else {
22130b57cec5SDimitry Andric Opts.ShowIncludesDest = ShowIncludesDestination::None;
22140b57cec5SDimitry Andric }
2215fe6060f1SDimitry Andric
2216fe6060f1SDimitry Andric // Add sanitizer ignorelists as extra dependencies.
22170b57cec5SDimitry Andric // They won't be discovered by the regular preprocessor, so
22180b57cec5SDimitry Andric // we let make / ninja to know about this implicit dependency.
2219fe6060f1SDimitry Andric if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2220fe6060f1SDimitry Andric for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2221480093f4SDimitry Andric StringRef Val = A->getValue();
2222349cc55cSDimitry Andric if (!Val.contains('='))
2223fe6060f1SDimitry Andric Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2224480093f4SDimitry Andric }
2225480093f4SDimitry Andric if (Opts.IncludeSystemHeaders) {
2226fe6060f1SDimitry Andric for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2227480093f4SDimitry Andric StringRef Val = A->getValue();
2228349cc55cSDimitry Andric if (!Val.contains('='))
2229fe6060f1SDimitry Andric Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2230480093f4SDimitry Andric }
2231480093f4SDimitry Andric }
2232480093f4SDimitry Andric }
2233480093f4SDimitry Andric
2234e8d8bef9SDimitry Andric // -fprofile-list= dependencies.
2235e8d8bef9SDimitry Andric for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2236fe6060f1SDimitry Andric Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2237e8d8bef9SDimitry Andric
2238480093f4SDimitry Andric // Propagate the extra dependencies.
2239fe6060f1SDimitry Andric for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2240fe6060f1SDimitry Andric Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2241480093f4SDimitry Andric
22420b57cec5SDimitry Andric // Only the -fmodule-file=<file> form.
22430b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_fmodule_file)) {
22440b57cec5SDimitry Andric StringRef Val = A->getValue();
2245349cc55cSDimitry Andric if (!Val.contains('='))
2246fe6060f1SDimitry Andric Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
22470b57cec5SDimitry Andric }
2248fe6060f1SDimitry Andric
2249bdd1243dSDimitry Andric // Check for invalid combinations of header-include-format
2250bdd1243dSDimitry Andric // and header-include-filtering.
2251bdd1243dSDimitry Andric if ((Opts.HeaderIncludeFormat == HIFMT_Textual &&
2252bdd1243dSDimitry Andric Opts.HeaderIncludeFiltering != HIFIL_None) ||
2253bdd1243dSDimitry Andric (Opts.HeaderIncludeFormat == HIFMT_JSON &&
2254bdd1243dSDimitry Andric Opts.HeaderIncludeFiltering != HIFIL_Only_Direct_System))
2255bdd1243dSDimitry Andric Diags.Report(diag::err_drv_print_header_env_var_combination_cc1)
2256bdd1243dSDimitry Andric << Args.getLastArg(OPT_header_include_format_EQ)->getValue()
2257bdd1243dSDimitry Andric << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue();
2258bdd1243dSDimitry Andric
2259fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
22600b57cec5SDimitry Andric }
22610b57cec5SDimitry Andric
parseShowColorsArgs(const ArgList & Args,bool DefaultColor)22620b57cec5SDimitry Andric static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
22630b57cec5SDimitry Andric // Color diagnostics default to auto ("on" if terminal supports) in the driver
22640b57cec5SDimitry Andric // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
22650b57cec5SDimitry Andric // Support both clang's -f[no-]color-diagnostics and gcc's
22660b57cec5SDimitry Andric // -f[no-]diagnostics-colors[=never|always|auto].
22670b57cec5SDimitry Andric enum {
22680b57cec5SDimitry Andric Colors_On,
22690b57cec5SDimitry Andric Colors_Off,
22700b57cec5SDimitry Andric Colors_Auto
22710b57cec5SDimitry Andric } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
22720b57cec5SDimitry Andric for (auto *A : Args) {
22730b57cec5SDimitry Andric const Option &O = A->getOption();
227481ad6265SDimitry Andric if (O.matches(options::OPT_fcolor_diagnostics)) {
22750b57cec5SDimitry Andric ShowColors = Colors_On;
227681ad6265SDimitry Andric } else if (O.matches(options::OPT_fno_color_diagnostics)) {
22770b57cec5SDimitry Andric ShowColors = Colors_Off;
22780b57cec5SDimitry Andric } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
22790b57cec5SDimitry Andric StringRef Value(A->getValue());
22800b57cec5SDimitry Andric if (Value == "always")
22810b57cec5SDimitry Andric ShowColors = Colors_On;
22820b57cec5SDimitry Andric else if (Value == "never")
22830b57cec5SDimitry Andric ShowColors = Colors_Off;
22840b57cec5SDimitry Andric else if (Value == "auto")
22850b57cec5SDimitry Andric ShowColors = Colors_Auto;
22860b57cec5SDimitry Andric }
22870b57cec5SDimitry Andric }
22880b57cec5SDimitry Andric return ShowColors == Colors_On ||
22890b57cec5SDimitry Andric (ShowColors == Colors_Auto &&
22900b57cec5SDimitry Andric llvm::sys::Process::StandardErrHasColors());
22910b57cec5SDimitry Andric }
22920b57cec5SDimitry Andric
checkVerifyPrefixes(const std::vector<std::string> & VerifyPrefixes,DiagnosticsEngine & Diags)22930b57cec5SDimitry Andric static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2294e8d8bef9SDimitry Andric DiagnosticsEngine &Diags) {
22950b57cec5SDimitry Andric bool Success = true;
22960b57cec5SDimitry Andric for (const auto &Prefix : VerifyPrefixes) {
22970b57cec5SDimitry Andric // Every prefix must start with a letter and contain only alphanumeric
22980b57cec5SDimitry Andric // characters, hyphens, and underscores.
22990b57cec5SDimitry Andric auto BadChar = llvm::find_if(Prefix, [](char C) {
23000b57cec5SDimitry Andric return !isAlphanumeric(C) && C != '-' && C != '_';
23010b57cec5SDimitry Andric });
23020b57cec5SDimitry Andric if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
23030b57cec5SDimitry Andric Success = false;
2304e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2305e8d8bef9SDimitry Andric Diags.Report(diag::note_drv_verify_prefix_spelling);
23060b57cec5SDimitry Andric }
23070b57cec5SDimitry Andric }
2308e8d8bef9SDimitry Andric return Success;
23090b57cec5SDimitry Andric }
2310e8d8bef9SDimitry Andric
GenerateFileSystemArgs(const FileSystemOptions & Opts,ArgumentConsumer Consumer)2311fe6060f1SDimitry Andric static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2312c9157d92SDimitry Andric ArgumentConsumer Consumer) {
2313fe6060f1SDimitry Andric const FileSystemOptions &FileSystemOpts = Opts;
2314e8d8bef9SDimitry Andric
2315fe013be4SDimitry Andric #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2316c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2317e8d8bef9SDimitry Andric #include "clang/Driver/Options.inc"
2318fe6060f1SDimitry Andric #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2319fe6060f1SDimitry Andric }
2320e8d8bef9SDimitry Andric
ParseFileSystemArgs(FileSystemOptions & Opts,const ArgList & Args,DiagnosticsEngine & Diags)2321fe6060f1SDimitry Andric static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2322fe6060f1SDimitry Andric DiagnosticsEngine &Diags) {
2323fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
2324fe6060f1SDimitry Andric
2325fe6060f1SDimitry Andric FileSystemOptions &FileSystemOpts = Opts;
2326fe6060f1SDimitry Andric
2327fe013be4SDimitry Andric #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2328fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2329fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2330fe6060f1SDimitry Andric #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2331fe6060f1SDimitry Andric
2332fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
2333fe6060f1SDimitry Andric }
2334fe6060f1SDimitry Andric
GenerateMigratorArgs(const MigratorOptions & Opts,ArgumentConsumer Consumer)2335fe6060f1SDimitry Andric static void GenerateMigratorArgs(const MigratorOptions &Opts,
2336c9157d92SDimitry Andric ArgumentConsumer Consumer) {
2337fe6060f1SDimitry Andric const MigratorOptions &MigratorOpts = Opts;
2338fe013be4SDimitry Andric #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2339c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2340fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2341fe6060f1SDimitry Andric #undef MIGRATOR_OPTION_WITH_MARSHALLING
2342fe6060f1SDimitry Andric }
2343fe6060f1SDimitry Andric
ParseMigratorArgs(MigratorOptions & Opts,const ArgList & Args,DiagnosticsEngine & Diags)2344fe6060f1SDimitry Andric static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2345fe6060f1SDimitry Andric DiagnosticsEngine &Diags) {
2346fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
2347fe6060f1SDimitry Andric
2348fe6060f1SDimitry Andric MigratorOptions &MigratorOpts = Opts;
2349fe6060f1SDimitry Andric
2350fe013be4SDimitry Andric #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2351fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2352fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2353fe6060f1SDimitry Andric #undef MIGRATOR_OPTION_WITH_MARSHALLING
2354fe6060f1SDimitry Andric
2355fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
2356fe6060f1SDimitry Andric }
2357fe6060f1SDimitry Andric
GenerateDiagnosticArgs(const DiagnosticOptions & Opts,ArgumentConsumer Consumer,bool DefaultDiagColor)2358c9157d92SDimitry Andric void CompilerInvocationBase::GenerateDiagnosticArgs(
2359c9157d92SDimitry Andric const DiagnosticOptions &Opts, ArgumentConsumer Consumer,
2360c9157d92SDimitry Andric bool DefaultDiagColor) {
2361fe6060f1SDimitry Andric const DiagnosticOptions *DiagnosticOpts = &Opts;
2362fe013be4SDimitry Andric #define DIAG_OPTION_WITH_MARSHALLING(...) \
2363c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2364fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2365fe6060f1SDimitry Andric #undef DIAG_OPTION_WITH_MARSHALLING
2366fe6060f1SDimitry Andric
2367fe6060f1SDimitry Andric if (!Opts.DiagnosticSerializationFile.empty())
2368c9157d92SDimitry Andric GenerateArg(Consumer, OPT_diagnostic_serialized_file,
2369c9157d92SDimitry Andric Opts.DiagnosticSerializationFile);
2370fe6060f1SDimitry Andric
2371fe6060f1SDimitry Andric if (Opts.ShowColors)
2372c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fcolor_diagnostics);
2373fe6060f1SDimitry Andric
2374fe6060f1SDimitry Andric if (Opts.VerifyDiagnostics &&
2375fe6060f1SDimitry Andric llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2376c9157d92SDimitry Andric GenerateArg(Consumer, OPT_verify);
2377fe6060f1SDimitry Andric
2378fe6060f1SDimitry Andric for (const auto &Prefix : Opts.VerifyPrefixes)
2379fe6060f1SDimitry Andric if (Prefix != "expected")
2380c9157d92SDimitry Andric GenerateArg(Consumer, OPT_verify_EQ, Prefix);
2381fe6060f1SDimitry Andric
2382fe6060f1SDimitry Andric DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2383fe6060f1SDimitry Andric if (VIU == DiagnosticLevelMask::None) {
2384fe6060f1SDimitry Andric // This is the default, don't generate anything.
2385fe6060f1SDimitry Andric } else if (VIU == DiagnosticLevelMask::All) {
2386c9157d92SDimitry Andric GenerateArg(Consumer, OPT_verify_ignore_unexpected);
2387fe6060f1SDimitry Andric } else {
2388fe6060f1SDimitry Andric if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2389c9157d92SDimitry Andric GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "note");
2390fe6060f1SDimitry Andric if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2391c9157d92SDimitry Andric GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "remark");
2392fe6060f1SDimitry Andric if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2393c9157d92SDimitry Andric GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "warning");
2394fe6060f1SDimitry Andric if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2395c9157d92SDimitry Andric GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "error");
2396fe6060f1SDimitry Andric }
2397fe6060f1SDimitry Andric
2398fe6060f1SDimitry Andric for (const auto &Warning : Opts.Warnings) {
2399fe6060f1SDimitry Andric // This option is automatically generated from UndefPrefixes.
2400fe6060f1SDimitry Andric if (Warning == "undef-prefix")
2401fe6060f1SDimitry Andric continue;
2402c9157d92SDimitry Andric Consumer(StringRef("-W") + Warning);
2403fe6060f1SDimitry Andric }
2404fe6060f1SDimitry Andric
2405fe6060f1SDimitry Andric for (const auto &Remark : Opts.Remarks) {
2406fe6060f1SDimitry Andric // These arguments are generated from OptimizationRemark fields of
2407fe6060f1SDimitry Andric // CodeGenOptions.
2408fe6060f1SDimitry Andric StringRef IgnoredRemarks[] = {"pass", "no-pass",
2409fe6060f1SDimitry Andric "pass-analysis", "no-pass-analysis",
2410fe6060f1SDimitry Andric "pass-missed", "no-pass-missed"};
2411fe6060f1SDimitry Andric if (llvm::is_contained(IgnoredRemarks, Remark))
2412fe6060f1SDimitry Andric continue;
2413fe6060f1SDimitry Andric
2414c9157d92SDimitry Andric Consumer(StringRef("-R") + Remark);
2415fe6060f1SDimitry Andric }
24160b57cec5SDimitry Andric }
24170b57cec5SDimitry Andric
2418349cc55cSDimitry Andric std::unique_ptr<DiagnosticOptions>
CreateAndPopulateDiagOpts(ArrayRef<const char * > Argv)2419349cc55cSDimitry Andric clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
2420349cc55cSDimitry Andric auto DiagOpts = std::make_unique<DiagnosticOptions>();
2421349cc55cSDimitry Andric unsigned MissingArgIndex, MissingArgCount;
2422349cc55cSDimitry Andric InputArgList Args = getDriverOptTable().ParseArgs(
2423349cc55cSDimitry Andric Argv.slice(1), MissingArgIndex, MissingArgCount);
2424fe013be4SDimitry Andric
2425fe013be4SDimitry Andric bool ShowColors = true;
2426fe013be4SDimitry Andric if (std::optional<std::string> NoColor =
2427fe013be4SDimitry Andric llvm::sys::Process::GetEnv("NO_COLOR");
2428fe013be4SDimitry Andric NoColor && !NoColor->empty()) {
2429fe013be4SDimitry Andric // If the user set the NO_COLOR environment variable, we'll honor that
2430fe013be4SDimitry Andric // unless the command line overrides it.
2431fe013be4SDimitry Andric ShowColors = false;
2432fe013be4SDimitry Andric }
2433fe013be4SDimitry Andric
2434349cc55cSDimitry Andric // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2435349cc55cSDimitry Andric // Any errors that would be diagnosed here will also be diagnosed later,
2436349cc55cSDimitry Andric // when the DiagnosticsEngine actually exists.
2437fe013be4SDimitry Andric (void)ParseDiagnosticArgs(*DiagOpts, Args, /*Diags=*/nullptr, ShowColors);
2438349cc55cSDimitry Andric return DiagOpts;
2439349cc55cSDimitry Andric }
2440349cc55cSDimitry Andric
ParseDiagnosticArgs(DiagnosticOptions & Opts,ArgList & Args,DiagnosticsEngine * Diags,bool DefaultDiagColor)24410b57cec5SDimitry Andric bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
24420b57cec5SDimitry Andric DiagnosticsEngine *Diags,
24435ffd83dbSDimitry Andric bool DefaultDiagColor) {
2444bdd1243dSDimitry Andric std::optional<DiagnosticsEngine> IgnoringDiags;
2445e8d8bef9SDimitry Andric if (!Diags) {
2446e8d8bef9SDimitry Andric IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2447e8d8bef9SDimitry Andric new IgnoringDiagConsumer());
2448e8d8bef9SDimitry Andric Diags = &*IgnoringDiags;
2449e8d8bef9SDimitry Andric }
2450e8d8bef9SDimitry Andric
2451fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags->getNumErrors();
2452fe6060f1SDimitry Andric
2453e8d8bef9SDimitry Andric // The key paths of diagnostic options defined in Options.td start with
2454e8d8bef9SDimitry Andric // "DiagnosticOpts->". Let's provide the expected variable name and type.
2455e8d8bef9SDimitry Andric DiagnosticOptions *DiagnosticOpts = &Opts;
24560b57cec5SDimitry Andric
2457fe013be4SDimitry Andric #define DIAG_OPTION_WITH_MARSHALLING(...) \
2458fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2459e8d8bef9SDimitry Andric #include "clang/Driver/Options.inc"
2460e8d8bef9SDimitry Andric #undef DIAG_OPTION_WITH_MARSHALLING
2461e8d8bef9SDimitry Andric
2462e8d8bef9SDimitry Andric llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2463e8d8bef9SDimitry Andric
24640b57cec5SDimitry Andric if (Arg *A =
24650b57cec5SDimitry Andric Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
24660b57cec5SDimitry Andric Opts.DiagnosticSerializationFile = A->getValue();
24670b57cec5SDimitry Andric Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
24680b57cec5SDimitry Andric
24690b57cec5SDimitry Andric Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2470fe6060f1SDimitry Andric Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
24710b57cec5SDimitry Andric if (Args.hasArg(OPT_verify))
24720b57cec5SDimitry Andric Opts.VerifyPrefixes.push_back("expected");
24730b57cec5SDimitry Andric // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
24740b57cec5SDimitry Andric // then sort it to prepare for fast lookup using std::binary_search.
2475fe6060f1SDimitry Andric if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
24760b57cec5SDimitry Andric Opts.VerifyDiagnostics = false;
24770b57cec5SDimitry Andric else
24780b57cec5SDimitry Andric llvm::sort(Opts.VerifyPrefixes);
24790b57cec5SDimitry Andric DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2480fe6060f1SDimitry Andric parseDiagnosticLevelMask(
2481fe6060f1SDimitry Andric "-verify-ignore-unexpected=",
2482fe6060f1SDimitry Andric Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
24830b57cec5SDimitry Andric if (Args.hasArg(OPT_verify_ignore_unexpected))
24840b57cec5SDimitry Andric DiagMask = DiagnosticLevelMask::All;
24850b57cec5SDimitry Andric Opts.setVerifyIgnoreUnexpected(DiagMask);
24860b57cec5SDimitry Andric if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
24870b57cec5SDimitry Andric Diags->Report(diag::warn_ignoring_ftabstop_value)
24880b57cec5SDimitry Andric << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2489fe013be4SDimitry Andric Opts.TabStop = DiagnosticOptions::DefaultTabStop;
24900b57cec5SDimitry Andric }
24915ffd83dbSDimitry Andric
24920b57cec5SDimitry Andric addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
24930b57cec5SDimitry Andric addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
24940b57cec5SDimitry Andric
2495fe6060f1SDimitry Andric return Diags->getNumErrors() == NumErrorsBefore;
24960b57cec5SDimitry Andric }
24970b57cec5SDimitry Andric
24980b57cec5SDimitry Andric /// Parse the argument to the -ftest-module-file-extension
24990b57cec5SDimitry Andric /// command-line argument.
25000b57cec5SDimitry Andric ///
25010b57cec5SDimitry Andric /// \returns true on error, false on success.
parseTestModuleFileExtensionArg(StringRef Arg,std::string & BlockName,unsigned & MajorVersion,unsigned & MinorVersion,bool & Hashed,std::string & UserInfo)25020b57cec5SDimitry Andric static bool parseTestModuleFileExtensionArg(StringRef Arg,
25030b57cec5SDimitry Andric std::string &BlockName,
25040b57cec5SDimitry Andric unsigned &MajorVersion,
25050b57cec5SDimitry Andric unsigned &MinorVersion,
25060b57cec5SDimitry Andric bool &Hashed,
25070b57cec5SDimitry Andric std::string &UserInfo) {
25080b57cec5SDimitry Andric SmallVector<StringRef, 5> Args;
25090b57cec5SDimitry Andric Arg.split(Args, ':', 5);
25100b57cec5SDimitry Andric if (Args.size() < 5)
25110b57cec5SDimitry Andric return true;
25120b57cec5SDimitry Andric
25135ffd83dbSDimitry Andric BlockName = std::string(Args[0]);
25140b57cec5SDimitry Andric if (Args[1].getAsInteger(10, MajorVersion)) return true;
25150b57cec5SDimitry Andric if (Args[2].getAsInteger(10, MinorVersion)) return true;
25160b57cec5SDimitry Andric if (Args[3].getAsInteger(2, Hashed)) return true;
25170b57cec5SDimitry Andric if (Args.size() > 4)
25185ffd83dbSDimitry Andric UserInfo = std::string(Args[4]);
25190b57cec5SDimitry Andric return false;
25200b57cec5SDimitry Andric }
25210b57cec5SDimitry Andric
2522fe6060f1SDimitry Andric /// Return a table that associates command line option specifiers with the
2523fe6060f1SDimitry Andric /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2524fe6060f1SDimitry Andric /// intentionally missing, as this case is handled separately from other
2525fe6060f1SDimitry Andric /// frontend options.
getFrontendActionTable()2526fe6060f1SDimitry Andric static const auto &getFrontendActionTable() {
2527fe6060f1SDimitry Andric static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2528fe6060f1SDimitry Andric {frontend::ASTDeclList, OPT_ast_list},
2529fe6060f1SDimitry Andric
2530fe6060f1SDimitry Andric {frontend::ASTDump, OPT_ast_dump_all_EQ},
2531fe6060f1SDimitry Andric {frontend::ASTDump, OPT_ast_dump_all},
2532fe6060f1SDimitry Andric {frontend::ASTDump, OPT_ast_dump_EQ},
2533fe6060f1SDimitry Andric {frontend::ASTDump, OPT_ast_dump},
2534fe6060f1SDimitry Andric {frontend::ASTDump, OPT_ast_dump_lookups},
2535fe6060f1SDimitry Andric {frontend::ASTDump, OPT_ast_dump_decl_types},
2536fe6060f1SDimitry Andric
2537fe6060f1SDimitry Andric {frontend::ASTPrint, OPT_ast_print},
2538fe6060f1SDimitry Andric {frontend::ASTView, OPT_ast_view},
2539fe6060f1SDimitry Andric {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2540fe6060f1SDimitry Andric {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2541fe6060f1SDimitry Andric {frontend::DumpTokens, OPT_dump_tokens},
2542fe6060f1SDimitry Andric {frontend::EmitAssembly, OPT_S},
2543fe6060f1SDimitry Andric {frontend::EmitBC, OPT_emit_llvm_bc},
2544fe6060f1SDimitry Andric {frontend::EmitHTML, OPT_emit_html},
2545fe6060f1SDimitry Andric {frontend::EmitLLVM, OPT_emit_llvm},
2546fe6060f1SDimitry Andric {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2547fe6060f1SDimitry Andric {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2548fe6060f1SDimitry Andric {frontend::EmitObj, OPT_emit_obj},
254904eeddc0SDimitry Andric {frontend::ExtractAPI, OPT_extract_api},
2550fe6060f1SDimitry Andric
2551fe6060f1SDimitry Andric {frontend::FixIt, OPT_fixit_EQ},
2552fe6060f1SDimitry Andric {frontend::FixIt, OPT_fixit},
2553fe6060f1SDimitry Andric
2554fe6060f1SDimitry Andric {frontend::GenerateModule, OPT_emit_module},
2555fe6060f1SDimitry Andric {frontend::GenerateModuleInterface, OPT_emit_module_interface},
255681ad6265SDimitry Andric {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2557fe6060f1SDimitry Andric {frontend::GeneratePCH, OPT_emit_pch},
2558fe6060f1SDimitry Andric {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2559fe6060f1SDimitry Andric {frontend::InitOnly, OPT_init_only},
2560fe6060f1SDimitry Andric {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2561fe6060f1SDimitry Andric {frontend::ModuleFileInfo, OPT_module_file_info},
2562fe6060f1SDimitry Andric {frontend::VerifyPCH, OPT_verify_pch},
2563fe6060f1SDimitry Andric {frontend::PrintPreamble, OPT_print_preamble},
2564fe6060f1SDimitry Andric {frontend::PrintPreprocessedInput, OPT_E},
2565fe6060f1SDimitry Andric {frontend::TemplightDump, OPT_templight_dump},
2566fe6060f1SDimitry Andric {frontend::RewriteMacros, OPT_rewrite_macros},
2567fe6060f1SDimitry Andric {frontend::RewriteObjC, OPT_rewrite_objc},
2568fe6060f1SDimitry Andric {frontend::RewriteTest, OPT_rewrite_test},
2569fe6060f1SDimitry Andric {frontend::RunAnalysis, OPT_analyze},
2570fe6060f1SDimitry Andric {frontend::MigrateSource, OPT_migrate},
2571fe6060f1SDimitry Andric {frontend::RunPreprocessorOnly, OPT_Eonly},
2572fe6060f1SDimitry Andric {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2573fe6060f1SDimitry Andric OPT_print_dependency_directives_minimized_source},
2574fe6060f1SDimitry Andric };
2575fe6060f1SDimitry Andric
2576fe6060f1SDimitry Andric return Table;
2577fe6060f1SDimitry Andric }
2578fe6060f1SDimitry Andric
2579fe6060f1SDimitry Andric /// Maps command line option to frontend action.
2580bdd1243dSDimitry Andric static std::optional<frontend::ActionKind>
getFrontendAction(OptSpecifier & Opt)2581bdd1243dSDimitry Andric getFrontendAction(OptSpecifier &Opt) {
2582fe6060f1SDimitry Andric for (const auto &ActionOpt : getFrontendActionTable())
2583fe6060f1SDimitry Andric if (ActionOpt.second == Opt.getID())
2584fe6060f1SDimitry Andric return ActionOpt.first;
2585fe6060f1SDimitry Andric
2586bdd1243dSDimitry Andric return std::nullopt;
2587fe6060f1SDimitry Andric }
2588fe6060f1SDimitry Andric
2589fe6060f1SDimitry Andric /// Maps frontend action to command line option.
2590bdd1243dSDimitry Andric static std::optional<OptSpecifier>
getProgramActionOpt(frontend::ActionKind ProgramAction)2591fe6060f1SDimitry Andric getProgramActionOpt(frontend::ActionKind ProgramAction) {
2592fe6060f1SDimitry Andric for (const auto &ActionOpt : getFrontendActionTable())
2593fe6060f1SDimitry Andric if (ActionOpt.first == ProgramAction)
2594fe6060f1SDimitry Andric return OptSpecifier(ActionOpt.second);
2595fe6060f1SDimitry Andric
2596bdd1243dSDimitry Andric return std::nullopt;
2597fe6060f1SDimitry Andric }
2598fe6060f1SDimitry Andric
GenerateFrontendArgs(const FrontendOptions & Opts,ArgumentConsumer Consumer,bool IsHeader)2599fe6060f1SDimitry Andric static void GenerateFrontendArgs(const FrontendOptions &Opts,
2600c9157d92SDimitry Andric ArgumentConsumer Consumer, bool IsHeader) {
2601fe6060f1SDimitry Andric const FrontendOptions &FrontendOpts = Opts;
2602fe013be4SDimitry Andric #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2603c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2604fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2605fe6060f1SDimitry Andric #undef FRONTEND_OPTION_WITH_MARSHALLING
2606fe6060f1SDimitry Andric
2607bdd1243dSDimitry Andric std::optional<OptSpecifier> ProgramActionOpt =
2608fe6060f1SDimitry Andric getProgramActionOpt(Opts.ProgramAction);
2609fe6060f1SDimitry Andric
2610fe6060f1SDimitry Andric // Generating a simple flag covers most frontend actions.
2611fe6060f1SDimitry Andric std::function<void()> GenerateProgramAction = [&]() {
2612c9157d92SDimitry Andric GenerateArg(Consumer, *ProgramActionOpt);
2613fe6060f1SDimitry Andric };
2614fe6060f1SDimitry Andric
2615fe6060f1SDimitry Andric if (!ProgramActionOpt) {
2616fe6060f1SDimitry Andric // PluginAction is the only program action handled separately.
2617fe6060f1SDimitry Andric assert(Opts.ProgramAction == frontend::PluginAction &&
2618fe6060f1SDimitry Andric "Frontend action without option.");
2619fe6060f1SDimitry Andric GenerateProgramAction = [&]() {
2620c9157d92SDimitry Andric GenerateArg(Consumer, OPT_plugin, Opts.ActionName);
2621fe6060f1SDimitry Andric };
2622fe6060f1SDimitry Andric }
2623fe6060f1SDimitry Andric
2624fe6060f1SDimitry Andric // FIXME: Simplify the complex 'AST dump' command line.
2625fe6060f1SDimitry Andric if (Opts.ProgramAction == frontend::ASTDump) {
2626fe6060f1SDimitry Andric GenerateProgramAction = [&]() {
2627fe6060f1SDimitry Andric // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2628fe6060f1SDimitry Andric // marshalling infrastructure.
2629fe6060f1SDimitry Andric
2630fe6060f1SDimitry Andric if (Opts.ASTDumpFormat != ADOF_Default) {
2631fe6060f1SDimitry Andric StringRef Format;
2632fe6060f1SDimitry Andric switch (Opts.ASTDumpFormat) {
2633fe6060f1SDimitry Andric case ADOF_Default:
2634fe6060f1SDimitry Andric llvm_unreachable("Default AST dump format.");
2635fe6060f1SDimitry Andric case ADOF_JSON:
2636fe6060f1SDimitry Andric Format = "json";
2637fe6060f1SDimitry Andric break;
2638fe6060f1SDimitry Andric }
2639fe6060f1SDimitry Andric
2640fe6060f1SDimitry Andric if (Opts.ASTDumpAll)
2641c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ast_dump_all_EQ, Format);
2642fe6060f1SDimitry Andric if (Opts.ASTDumpDecls)
2643c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ast_dump_EQ, Format);
2644fe6060f1SDimitry Andric } else {
2645fe6060f1SDimitry Andric if (Opts.ASTDumpAll)
2646c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ast_dump_all);
2647fe6060f1SDimitry Andric if (Opts.ASTDumpDecls)
2648c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ast_dump);
2649fe6060f1SDimitry Andric }
2650fe6060f1SDimitry Andric };
2651fe6060f1SDimitry Andric }
2652fe6060f1SDimitry Andric
2653fe6060f1SDimitry Andric if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2654fe6060f1SDimitry Andric GenerateProgramAction = [&]() {
2655c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix);
2656fe6060f1SDimitry Andric };
2657fe6060f1SDimitry Andric }
2658fe6060f1SDimitry Andric
2659fe6060f1SDimitry Andric GenerateProgramAction();
2660fe6060f1SDimitry Andric
2661fe6060f1SDimitry Andric for (const auto &PluginArgs : Opts.PluginArgs) {
2662fe6060f1SDimitry Andric Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2663fe6060f1SDimitry Andric for (const auto &PluginArg : PluginArgs.second)
2664c9157d92SDimitry Andric denormalizeString(Consumer,
2665c9157d92SDimitry Andric Opt.getPrefix() + Opt.getName() + PluginArgs.first,
2666c9157d92SDimitry Andric Opt.getKind(), 0, PluginArg);
2667fe6060f1SDimitry Andric }
2668fe6060f1SDimitry Andric
2669fe6060f1SDimitry Andric for (const auto &Ext : Opts.ModuleFileExtensions)
2670fe6060f1SDimitry Andric if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2671c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ftest_module_file_extension_EQ, TestExt->str());
2672fe6060f1SDimitry Andric
2673fe6060f1SDimitry Andric if (!Opts.CodeCompletionAt.FileName.empty())
2674c9157d92SDimitry Andric GenerateArg(Consumer, OPT_code_completion_at,
2675c9157d92SDimitry Andric Opts.CodeCompletionAt.ToString());
2676fe6060f1SDimitry Andric
2677fe6060f1SDimitry Andric for (const auto &Plugin : Opts.Plugins)
2678c9157d92SDimitry Andric GenerateArg(Consumer, OPT_load, Plugin);
2679fe6060f1SDimitry Andric
2680fe6060f1SDimitry Andric // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2681fe6060f1SDimitry Andric
2682fe6060f1SDimitry Andric for (const auto &ModuleFile : Opts.ModuleFiles)
2683c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fmodule_file, ModuleFile);
2684fe6060f1SDimitry Andric
268581ad6265SDimitry Andric if (Opts.AuxTargetCPU)
2686c9157d92SDimitry Andric GenerateArg(Consumer, OPT_aux_target_cpu, *Opts.AuxTargetCPU);
2687fe6060f1SDimitry Andric
268881ad6265SDimitry Andric if (Opts.AuxTargetFeatures)
2689fe6060f1SDimitry Andric for (const auto &Feature : *Opts.AuxTargetFeatures)
2690c9157d92SDimitry Andric GenerateArg(Consumer, OPT_aux_target_feature, Feature);
2691fe6060f1SDimitry Andric
2692fe6060f1SDimitry Andric {
2693fe6060f1SDimitry Andric StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2694fe6060f1SDimitry Andric StringRef ModuleMap =
2695fe6060f1SDimitry Andric Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
269681ad6265SDimitry Andric StringRef HeaderUnit = "";
269781ad6265SDimitry Andric switch (Opts.DashX.getHeaderUnitKind()) {
269881ad6265SDimitry Andric case InputKind::HeaderUnit_None:
269981ad6265SDimitry Andric break;
270081ad6265SDimitry Andric case InputKind::HeaderUnit_User:
270181ad6265SDimitry Andric HeaderUnit = "-user";
270281ad6265SDimitry Andric break;
270381ad6265SDimitry Andric case InputKind::HeaderUnit_System:
270481ad6265SDimitry Andric HeaderUnit = "-system";
270581ad6265SDimitry Andric break;
270681ad6265SDimitry Andric case InputKind::HeaderUnit_Abs:
270781ad6265SDimitry Andric HeaderUnit = "-header-unit";
270881ad6265SDimitry Andric break;
270981ad6265SDimitry Andric }
2710fe6060f1SDimitry Andric StringRef Header = IsHeader ? "-header" : "";
2711fe6060f1SDimitry Andric
2712fe6060f1SDimitry Andric StringRef Lang;
2713fe6060f1SDimitry Andric switch (Opts.DashX.getLanguage()) {
2714fe6060f1SDimitry Andric case Language::C:
2715fe6060f1SDimitry Andric Lang = "c";
2716fe6060f1SDimitry Andric break;
2717fe6060f1SDimitry Andric case Language::OpenCL:
2718fe6060f1SDimitry Andric Lang = "cl";
2719fe6060f1SDimitry Andric break;
2720fe6060f1SDimitry Andric case Language::OpenCLCXX:
2721fe6060f1SDimitry Andric Lang = "clcpp";
2722fe6060f1SDimitry Andric break;
2723fe6060f1SDimitry Andric case Language::CUDA:
2724fe6060f1SDimitry Andric Lang = "cuda";
2725fe6060f1SDimitry Andric break;
2726fe6060f1SDimitry Andric case Language::HIP:
2727fe6060f1SDimitry Andric Lang = "hip";
2728fe6060f1SDimitry Andric break;
2729fe6060f1SDimitry Andric case Language::CXX:
2730fe6060f1SDimitry Andric Lang = "c++";
2731fe6060f1SDimitry Andric break;
2732fe6060f1SDimitry Andric case Language::ObjC:
2733fe6060f1SDimitry Andric Lang = "objective-c";
2734fe6060f1SDimitry Andric break;
2735fe6060f1SDimitry Andric case Language::ObjCXX:
2736fe6060f1SDimitry Andric Lang = "objective-c++";
2737fe6060f1SDimitry Andric break;
2738fe6060f1SDimitry Andric case Language::RenderScript:
2739fe6060f1SDimitry Andric Lang = "renderscript";
2740fe6060f1SDimitry Andric break;
2741fe6060f1SDimitry Andric case Language::Asm:
2742fe6060f1SDimitry Andric Lang = "assembler-with-cpp";
2743fe6060f1SDimitry Andric break;
2744fe6060f1SDimitry Andric case Language::Unknown:
2745fe6060f1SDimitry Andric assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2746fe6060f1SDimitry Andric "Generating -x argument for unknown language (not precompiled).");
2747fe6060f1SDimitry Andric Lang = "ast";
2748fe6060f1SDimitry Andric break;
2749fe6060f1SDimitry Andric case Language::LLVM_IR:
2750fe6060f1SDimitry Andric Lang = "ir";
2751fe6060f1SDimitry Andric break;
275281ad6265SDimitry Andric case Language::HLSL:
275381ad6265SDimitry Andric Lang = "hlsl";
275481ad6265SDimitry Andric break;
2755fe6060f1SDimitry Andric }
2756fe6060f1SDimitry Andric
2757c9157d92SDimitry Andric GenerateArg(Consumer, OPT_x,
2758c9157d92SDimitry Andric Lang + HeaderUnit + Header + ModuleMap + Preprocessed);
2759fe6060f1SDimitry Andric }
2760fe6060f1SDimitry Andric
2761fe6060f1SDimitry Andric // OPT_INPUT has a unique class, generate it directly.
2762fe6060f1SDimitry Andric for (const auto &Input : Opts.Inputs)
2763c9157d92SDimitry Andric Consumer(Input.getFile());
2764fe6060f1SDimitry Andric }
2765fe6060f1SDimitry Andric
ParseFrontendArgs(FrontendOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,bool & IsHeaderFile)2766fe6060f1SDimitry Andric static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2767fe6060f1SDimitry Andric DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2768fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
2769fe6060f1SDimitry Andric
2770fe6060f1SDimitry Andric FrontendOptions &FrontendOpts = Opts;
2771fe6060f1SDimitry Andric
2772fe013be4SDimitry Andric #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2773fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2774fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
2775fe6060f1SDimitry Andric #undef FRONTEND_OPTION_WITH_MARSHALLING
2776fe6060f1SDimitry Andric
27770b57cec5SDimitry Andric Opts.ProgramAction = frontend::ParseSyntaxOnly;
27780b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2779fe6060f1SDimitry Andric OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2780bdd1243dSDimitry Andric std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
2781fe6060f1SDimitry Andric assert(ProgramAction && "Option specifier not in Action_Group.");
2782fe6060f1SDimitry Andric
2783fe6060f1SDimitry Andric if (ProgramAction == frontend::ASTDump &&
2784fe6060f1SDimitry Andric (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
27850b57cec5SDimitry Andric unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
27860b57cec5SDimitry Andric .CaseLower("default", ADOF_Default)
27870b57cec5SDimitry Andric .CaseLower("json", ADOF_JSON)
27880b57cec5SDimitry Andric .Default(std::numeric_limits<unsigned>::max());
27890b57cec5SDimitry Andric
27900b57cec5SDimitry Andric if (Val != std::numeric_limits<unsigned>::max())
27910b57cec5SDimitry Andric Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
27920b57cec5SDimitry Andric else {
27930b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
27940b57cec5SDimitry Andric << A->getAsString(Args) << A->getValue();
27950b57cec5SDimitry Andric Opts.ASTDumpFormat = ADOF_Default;
27960b57cec5SDimitry Andric }
27970b57cec5SDimitry Andric }
2798fe6060f1SDimitry Andric
2799fe6060f1SDimitry Andric if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
28000b57cec5SDimitry Andric Opts.FixItSuffix = A->getValue();
2801fe6060f1SDimitry Andric
2802fe6060f1SDimitry Andric if (ProgramAction == frontend::GenerateInterfaceStubs) {
2803a7dea167SDimitry Andric StringRef ArgStr =
2804a7dea167SDimitry Andric Args.hasArg(OPT_interface_stub_version_EQ)
2805a7dea167SDimitry Andric ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2806fe6060f1SDimitry Andric : "ifs-v1";
2807a7dea167SDimitry Andric if (ArgStr == "experimental-yaml-elf-v1" ||
2808fe6060f1SDimitry Andric ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2809a7dea167SDimitry Andric ArgStr == "experimental-tapi-elf-v1") {
2810a7dea167SDimitry Andric std::string ErrorMessage =
2811a7dea167SDimitry Andric "Invalid interface stub format: " + ArgStr.str() +
2812a7dea167SDimitry Andric " is deprecated.";
28130b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
2814a7dea167SDimitry Andric << "Must specify a valid interface stub format type, ie: "
2815fe6060f1SDimitry Andric "-interface-stub-version=ifs-v1"
2816a7dea167SDimitry Andric << ErrorMessage;
2817fe6060f1SDimitry Andric ProgramAction = frontend::ParseSyntaxOnly;
2818c9157d92SDimitry Andric } else if (!ArgStr.starts_with("ifs-")) {
2819a7dea167SDimitry Andric std::string ErrorMessage =
2820a7dea167SDimitry Andric "Invalid interface stub format: " + ArgStr.str() + ".";
2821a7dea167SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
2822a7dea167SDimitry Andric << "Must specify a valid interface stub format type, ie: "
2823fe6060f1SDimitry Andric "-interface-stub-version=ifs-v1"
2824a7dea167SDimitry Andric << ErrorMessage;
2825fe6060f1SDimitry Andric ProgramAction = frontend::ParseSyntaxOnly;
2826a7dea167SDimitry Andric }
28270b57cec5SDimitry Andric }
2828fe6060f1SDimitry Andric
2829fe6060f1SDimitry Andric Opts.ProgramAction = *ProgramAction;
28300b57cec5SDimitry Andric }
28310b57cec5SDimitry Andric
28320b57cec5SDimitry Andric if (const Arg* A = Args.getLastArg(OPT_plugin)) {
28330b57cec5SDimitry Andric Opts.Plugins.emplace_back(A->getValue(0));
28340b57cec5SDimitry Andric Opts.ProgramAction = frontend::PluginAction;
28350b57cec5SDimitry Andric Opts.ActionName = A->getValue();
28360b57cec5SDimitry Andric }
28370b57cec5SDimitry Andric for (const auto *AA : Args.filtered(OPT_plugin_arg))
28380b57cec5SDimitry Andric Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
28390b57cec5SDimitry Andric
28400b57cec5SDimitry Andric for (const std::string &Arg :
28410b57cec5SDimitry Andric Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
28420b57cec5SDimitry Andric std::string BlockName;
28430b57cec5SDimitry Andric unsigned MajorVersion;
28440b57cec5SDimitry Andric unsigned MinorVersion;
28450b57cec5SDimitry Andric bool Hashed;
28460b57cec5SDimitry Andric std::string UserInfo;
28470b57cec5SDimitry Andric if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
28480b57cec5SDimitry Andric MinorVersion, Hashed, UserInfo)) {
28490b57cec5SDimitry Andric Diags.Report(diag::err_test_module_file_extension_format) << Arg;
28500b57cec5SDimitry Andric
28510b57cec5SDimitry Andric continue;
28520b57cec5SDimitry Andric }
28530b57cec5SDimitry Andric
28540b57cec5SDimitry Andric // Add the testing module file extension.
28550b57cec5SDimitry Andric Opts.ModuleFileExtensions.push_back(
28560b57cec5SDimitry Andric std::make_shared<TestModuleFileExtension>(
28570b57cec5SDimitry Andric BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
28580b57cec5SDimitry Andric }
28590b57cec5SDimitry Andric
28600b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
28610b57cec5SDimitry Andric Opts.CodeCompletionAt =
28620b57cec5SDimitry Andric ParsedSourceLocation::FromString(A->getValue());
28630b57cec5SDimitry Andric if (Opts.CodeCompletionAt.FileName.empty())
28640b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
28650b57cec5SDimitry Andric << A->getAsString(Args) << A->getValue();
28660b57cec5SDimitry Andric }
28670b57cec5SDimitry Andric
28680b57cec5SDimitry Andric Opts.Plugins = Args.getAllArgValues(OPT_load);
28690b57cec5SDimitry Andric Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
28700b57cec5SDimitry Andric Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
28710b57cec5SDimitry Andric // Only the -fmodule-file=<file> form.
28720b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_fmodule_file)) {
28730b57cec5SDimitry Andric StringRef Val = A->getValue();
2874349cc55cSDimitry Andric if (!Val.contains('='))
28755ffd83dbSDimitry Andric Opts.ModuleFiles.push_back(std::string(Val));
28760b57cec5SDimitry Andric }
28775ffd83dbSDimitry Andric
28785ffd83dbSDimitry Andric if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
28795ffd83dbSDimitry Andric Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
28805ffd83dbSDimitry Andric << "-emit-module";
28810b57cec5SDimitry Andric
28825ffd83dbSDimitry Andric if (Args.hasArg(OPT_aux_target_cpu))
28835ffd83dbSDimitry Andric Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
28845ffd83dbSDimitry Andric if (Args.hasArg(OPT_aux_target_feature))
28855ffd83dbSDimitry Andric Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
28860b57cec5SDimitry Andric
28870b57cec5SDimitry Andric if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
28880b57cec5SDimitry Andric Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
28890b57cec5SDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
28900b57cec5SDimitry Andric << "ARC migration" << "ObjC migration";
28910b57cec5SDimitry Andric }
28920b57cec5SDimitry Andric
2893a7dea167SDimitry Andric InputKind DashX(Language::Unknown);
28940b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_x)) {
28950b57cec5SDimitry Andric StringRef XValue = A->getValue();
28960b57cec5SDimitry Andric
289781ad6265SDimitry Andric // Parse suffixes:
289881ad6265SDimitry Andric // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
28990b57cec5SDimitry Andric // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
29000b57cec5SDimitry Andric bool Preprocessed = XValue.consume_back("-cpp-output");
29010b57cec5SDimitry Andric bool ModuleMap = XValue.consume_back("-module-map");
290281ad6265SDimitry Andric // Detect and consume the header indicator.
290381ad6265SDimitry Andric bool IsHeader =
290481ad6265SDimitry Andric XValue != "precompiled-header" && XValue.consume_back("-header");
290581ad6265SDimitry Andric
290681ad6265SDimitry Andric // If we have c++-{user,system}-header, that indicates a header unit input
290781ad6265SDimitry Andric // likewise, if the user put -fmodule-header together with a header with an
290881ad6265SDimitry Andric // absolute path (header-unit-header).
290981ad6265SDimitry Andric InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None;
291081ad6265SDimitry Andric if (IsHeader || Preprocessed) {
291181ad6265SDimitry Andric if (XValue.consume_back("-header-unit"))
291281ad6265SDimitry Andric HUK = InputKind::HeaderUnit_Abs;
291381ad6265SDimitry Andric else if (XValue.consume_back("-system"))
291481ad6265SDimitry Andric HUK = InputKind::HeaderUnit_System;
291581ad6265SDimitry Andric else if (XValue.consume_back("-user"))
291681ad6265SDimitry Andric HUK = InputKind::HeaderUnit_User;
291781ad6265SDimitry Andric }
291881ad6265SDimitry Andric
291981ad6265SDimitry Andric // The value set by this processing is an un-preprocessed source which is
292081ad6265SDimitry Andric // not intended to be a module map or header unit.
292181ad6265SDimitry Andric IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
292281ad6265SDimitry Andric HUK == InputKind::HeaderUnit_None;
29230b57cec5SDimitry Andric
29240b57cec5SDimitry Andric // Principal languages.
29250b57cec5SDimitry Andric DashX = llvm::StringSwitch<InputKind>(XValue)
2926a7dea167SDimitry Andric .Case("c", Language::C)
2927a7dea167SDimitry Andric .Case("cl", Language::OpenCL)
2928fe6060f1SDimitry Andric .Case("clcpp", Language::OpenCLCXX)
2929a7dea167SDimitry Andric .Case("cuda", Language::CUDA)
2930a7dea167SDimitry Andric .Case("hip", Language::HIP)
2931a7dea167SDimitry Andric .Case("c++", Language::CXX)
2932a7dea167SDimitry Andric .Case("objective-c", Language::ObjC)
2933a7dea167SDimitry Andric .Case("objective-c++", Language::ObjCXX)
2934a7dea167SDimitry Andric .Case("renderscript", Language::RenderScript)
293581ad6265SDimitry Andric .Case("hlsl", Language::HLSL)
2936a7dea167SDimitry Andric .Default(Language::Unknown);
29370b57cec5SDimitry Andric
29380b57cec5SDimitry Andric // "objc[++]-cpp-output" is an acceptable synonym for
29390b57cec5SDimitry Andric // "objective-c[++]-cpp-output".
294081ad6265SDimitry Andric if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
294181ad6265SDimitry Andric HUK == InputKind::HeaderUnit_None)
29420b57cec5SDimitry Andric DashX = llvm::StringSwitch<InputKind>(XValue)
2943a7dea167SDimitry Andric .Case("objc", Language::ObjC)
2944a7dea167SDimitry Andric .Case("objc++", Language::ObjCXX)
2945a7dea167SDimitry Andric .Default(Language::Unknown);
29460b57cec5SDimitry Andric
29470b57cec5SDimitry Andric // Some special cases cannot be combined with suffixes.
294881ad6265SDimitry Andric if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
294981ad6265SDimitry Andric HUK == InputKind::HeaderUnit_None)
29500b57cec5SDimitry Andric DashX = llvm::StringSwitch<InputKind>(XValue)
2951a7dea167SDimitry Andric .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2952a7dea167SDimitry Andric .Case("assembler-with-cpp", Language::Asm)
2953590d96feSDimitry Andric .Cases("ast", "pcm", "precompiled-header",
2954a7dea167SDimitry Andric InputKind(Language::Unknown, InputKind::Precompiled))
2955a7dea167SDimitry Andric .Case("ir", Language::LLVM_IR)
2956a7dea167SDimitry Andric .Default(Language::Unknown);
29570b57cec5SDimitry Andric
29580b57cec5SDimitry Andric if (DashX.isUnknown())
29590b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
29600b57cec5SDimitry Andric << A->getAsString(Args) << A->getValue();
29610b57cec5SDimitry Andric
29620b57cec5SDimitry Andric if (Preprocessed)
29630b57cec5SDimitry Andric DashX = DashX.getPreprocessed();
296481ad6265SDimitry Andric // A regular header is considered mutually exclusive with a header unit.
296581ad6265SDimitry Andric if (HUK != InputKind::HeaderUnit_None) {
296681ad6265SDimitry Andric DashX = DashX.withHeaderUnit(HUK);
296781ad6265SDimitry Andric IsHeaderFile = true;
296881ad6265SDimitry Andric } else if (IsHeaderFile)
296981ad6265SDimitry Andric DashX = DashX.getHeader();
29700b57cec5SDimitry Andric if (ModuleMap)
29710b57cec5SDimitry Andric DashX = DashX.withFormat(InputKind::ModuleMap);
29720b57cec5SDimitry Andric }
29730b57cec5SDimitry Andric
29740b57cec5SDimitry Andric // '-' is the default input if none is given.
29750b57cec5SDimitry Andric std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
29760b57cec5SDimitry Andric Opts.Inputs.clear();
29770b57cec5SDimitry Andric if (Inputs.empty())
29780b57cec5SDimitry Andric Inputs.push_back("-");
297981ad6265SDimitry Andric
298081ad6265SDimitry Andric if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None &&
298181ad6265SDimitry Andric Inputs.size() > 1)
298281ad6265SDimitry Andric Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
298381ad6265SDimitry Andric
29840b57cec5SDimitry Andric for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
29850b57cec5SDimitry Andric InputKind IK = DashX;
29860b57cec5SDimitry Andric if (IK.isUnknown()) {
29870b57cec5SDimitry Andric IK = FrontendOptions::getInputKindForExtension(
29880b57cec5SDimitry Andric StringRef(Inputs[i]).rsplit('.').second);
29890b57cec5SDimitry Andric // FIXME: Warn on this?
29900b57cec5SDimitry Andric if (IK.isUnknown())
2991a7dea167SDimitry Andric IK = Language::C;
29920b57cec5SDimitry Andric // FIXME: Remove this hack.
29930b57cec5SDimitry Andric if (i == 0)
29940b57cec5SDimitry Andric DashX = IK;
29950b57cec5SDimitry Andric }
29960b57cec5SDimitry Andric
29975ffd83dbSDimitry Andric bool IsSystem = false;
29985ffd83dbSDimitry Andric
29990b57cec5SDimitry Andric // The -emit-module action implicitly takes a module map.
30000b57cec5SDimitry Andric if (Opts.ProgramAction == frontend::GenerateModule &&
30015ffd83dbSDimitry Andric IK.getFormat() == InputKind::Source) {
30020b57cec5SDimitry Andric IK = IK.withFormat(InputKind::ModuleMap);
30035ffd83dbSDimitry Andric IsSystem = Opts.IsSystemModule;
30045ffd83dbSDimitry Andric }
30050b57cec5SDimitry Andric
30065ffd83dbSDimitry Andric Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
30070b57cec5SDimitry Andric }
30080b57cec5SDimitry Andric
3009fe6060f1SDimitry Andric Opts.DashX = DashX;
3010fe6060f1SDimitry Andric
3011fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
30120b57cec5SDimitry Andric }
30130b57cec5SDimitry Andric
GetResourcesPath(const char * Argv0,void * MainAddr)30140b57cec5SDimitry Andric std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
30150b57cec5SDimitry Andric void *MainAddr) {
30160b57cec5SDimitry Andric std::string ClangExecutable =
30170b57cec5SDimitry Andric llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
30180b57cec5SDimitry Andric return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
30190b57cec5SDimitry Andric }
30200b57cec5SDimitry Andric
GenerateHeaderSearchArgs(const HeaderSearchOptions & Opts,ArgumentConsumer Consumer)3021c9157d92SDimitry Andric static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts,
3022c9157d92SDimitry Andric ArgumentConsumer Consumer) {
3023fe6060f1SDimitry Andric const HeaderSearchOptions *HeaderSearchOpts = &Opts;
3024fe013be4SDimitry Andric #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3025c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3026fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
3027fe6060f1SDimitry Andric #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3028fe6060f1SDimitry Andric
3029fe6060f1SDimitry Andric if (Opts.UseLibcxx)
3030c9157d92SDimitry Andric GenerateArg(Consumer, OPT_stdlib_EQ, "libc++");
3031fe6060f1SDimitry Andric
3032fe6060f1SDimitry Andric if (!Opts.ModuleCachePath.empty())
3033c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fmodules_cache_path, Opts.ModuleCachePath);
3034fe6060f1SDimitry Andric
3035fe6060f1SDimitry Andric for (const auto &File : Opts.PrebuiltModuleFiles)
3036c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fmodule_file, File.first + "=" + File.second);
3037fe6060f1SDimitry Andric
3038fe6060f1SDimitry Andric for (const auto &Path : Opts.PrebuiltModulePaths)
3039c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fprebuilt_module_path, Path);
3040fe6060f1SDimitry Andric
3041fe6060f1SDimitry Andric for (const auto &Macro : Opts.ModulesIgnoreMacros)
3042c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fmodules_ignore_macro, Macro.val());
3043fe6060f1SDimitry Andric
3044fe6060f1SDimitry Andric auto Matches = [](const HeaderSearchOptions::Entry &Entry,
3045fe6060f1SDimitry Andric llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
3046bdd1243dSDimitry Andric std::optional<bool> IsFramework,
3047bdd1243dSDimitry Andric std::optional<bool> IgnoreSysRoot) {
3048349cc55cSDimitry Andric return llvm::is_contained(Groups, Entry.Group) &&
3049fe6060f1SDimitry Andric (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
3050fe6060f1SDimitry Andric (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
3051fe6060f1SDimitry Andric };
3052fe6060f1SDimitry Andric
3053fe6060f1SDimitry Andric auto It = Opts.UserEntries.begin();
3054fe6060f1SDimitry Andric auto End = Opts.UserEntries.end();
3055fe6060f1SDimitry Andric
3056fe6060f1SDimitry Andric // Add -I..., -F..., and -index-header-map options in order.
3057bdd1243dSDimitry Andric for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled},
3058bdd1243dSDimitry Andric std::nullopt, true);
3059fe6060f1SDimitry Andric ++It) {
3060fe6060f1SDimitry Andric OptSpecifier Opt = [It, Matches]() {
3061fe6060f1SDimitry Andric if (Matches(*It, frontend::IndexHeaderMap, true, true))
3062fe6060f1SDimitry Andric return OPT_F;
3063fe6060f1SDimitry Andric if (Matches(*It, frontend::IndexHeaderMap, false, true))
3064fe6060f1SDimitry Andric return OPT_I;
3065fe6060f1SDimitry Andric if (Matches(*It, frontend::Angled, true, true))
3066fe6060f1SDimitry Andric return OPT_F;
3067fe6060f1SDimitry Andric if (Matches(*It, frontend::Angled, false, true))
3068fe6060f1SDimitry Andric return OPT_I;
3069fe6060f1SDimitry Andric llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
3070fe6060f1SDimitry Andric }();
3071fe6060f1SDimitry Andric
3072fe6060f1SDimitry Andric if (It->Group == frontend::IndexHeaderMap)
3073c9157d92SDimitry Andric GenerateArg(Consumer, OPT_index_header_map);
3074c9157d92SDimitry Andric GenerateArg(Consumer, Opt, It->Path);
3075fe6060f1SDimitry Andric };
3076fe6060f1SDimitry Andric
3077fe6060f1SDimitry Andric // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
3078fe6060f1SDimitry Andric // have already been generated as "-I[xx]yy". If that's the case, their
3079fe6060f1SDimitry Andric // position on command line was such that this has no semantic impact on
3080fe6060f1SDimitry Andric // include paths.
3081fe6060f1SDimitry Andric for (; It < End &&
3082fe6060f1SDimitry Andric Matches(*It, {frontend::After, frontend::Angled}, false, true);
3083fe6060f1SDimitry Andric ++It) {
3084fe6060f1SDimitry Andric OptSpecifier Opt =
3085fe6060f1SDimitry Andric It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3086c9157d92SDimitry Andric GenerateArg(Consumer, Opt, It->Path);
3087fe6060f1SDimitry Andric }
3088fe6060f1SDimitry Andric
3089fe6060f1SDimitry Andric // Note: Some paths that came from "-idirafter=xxyy" may have already been
3090fe6060f1SDimitry Andric // generated as "-iwithprefix=xxyy". If that's the case, their position on
3091fe6060f1SDimitry Andric // command line was such that this has no semantic impact on include paths.
3092fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3093c9157d92SDimitry Andric GenerateArg(Consumer, OPT_idirafter, It->Path);
3094fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3095c9157d92SDimitry Andric GenerateArg(Consumer, OPT_iquote, It->Path);
3096bdd1243dSDimitry Andric for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt);
3097bdd1243dSDimitry Andric ++It)
3098c9157d92SDimitry Andric GenerateArg(Consumer, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3099c9157d92SDimitry Andric It->Path);
3100fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3101c9157d92SDimitry Andric GenerateArg(Consumer, OPT_iframework, It->Path);
3102fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3103c9157d92SDimitry Andric GenerateArg(Consumer, OPT_iframeworkwithsysroot, It->Path);
3104fe6060f1SDimitry Andric
3105fe6060f1SDimitry Andric // Add the paths for the various language specific isystem flags.
3106fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3107c9157d92SDimitry Andric GenerateArg(Consumer, OPT_c_isystem, It->Path);
3108fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3109c9157d92SDimitry Andric GenerateArg(Consumer, OPT_cxx_isystem, It->Path);
3110fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3111c9157d92SDimitry Andric GenerateArg(Consumer, OPT_objc_isystem, It->Path);
3112fe6060f1SDimitry Andric for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3113c9157d92SDimitry Andric GenerateArg(Consumer, OPT_objcxx_isystem, It->Path);
3114fe6060f1SDimitry Andric
3115fe6060f1SDimitry Andric // Add the internal paths from a driver that detects standard include paths.
3116fe6060f1SDimitry Andric // Note: Some paths that came from "-internal-isystem" arguments may have
3117fe6060f1SDimitry Andric // already been generated as "-isystem". If that's the case, their position on
3118fe6060f1SDimitry Andric // command line was such that this has no semantic impact on include paths.
3119fe6060f1SDimitry Andric for (; It < End &&
3120fe6060f1SDimitry Andric Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3121fe6060f1SDimitry Andric ++It) {
3122fe6060f1SDimitry Andric OptSpecifier Opt = It->Group == frontend::System
3123fe6060f1SDimitry Andric ? OPT_internal_isystem
3124fe6060f1SDimitry Andric : OPT_internal_externc_isystem;
3125c9157d92SDimitry Andric GenerateArg(Consumer, Opt, It->Path);
3126fe6060f1SDimitry Andric }
3127fe6060f1SDimitry Andric
3128fe6060f1SDimitry Andric assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3129fe6060f1SDimitry Andric
3130fe6060f1SDimitry Andric // Add the path prefixes which are implicitly treated as being system headers.
3131fe6060f1SDimitry Andric for (const auto &P : Opts.SystemHeaderPrefixes) {
3132fe6060f1SDimitry Andric OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3133fe6060f1SDimitry Andric : OPT_no_system_header_prefix;
3134c9157d92SDimitry Andric GenerateArg(Consumer, Opt, P.Prefix);
3135fe6060f1SDimitry Andric }
3136fe6060f1SDimitry Andric
3137fe6060f1SDimitry Andric for (const std::string &F : Opts.VFSOverlayFiles)
3138c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ivfsoverlay, F);
3139fe6060f1SDimitry Andric }
3140fe6060f1SDimitry Andric
ParseHeaderSearchArgs(HeaderSearchOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,const std::string & WorkingDir)3141fe6060f1SDimitry Andric static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3142fe6060f1SDimitry Andric DiagnosticsEngine &Diags,
31430b57cec5SDimitry Andric const std::string &WorkingDir) {
3144fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
3145fe6060f1SDimitry Andric
3146fe6060f1SDimitry Andric HeaderSearchOptions *HeaderSearchOpts = &Opts;
3147fe6060f1SDimitry Andric
3148fe013be4SDimitry Andric #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3149fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3150fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
3151fe6060f1SDimitry Andric #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3152fe6060f1SDimitry Andric
31530b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
31540b57cec5SDimitry Andric Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
31550b57cec5SDimitry Andric
31560b57cec5SDimitry Andric // Canonicalize -fmodules-cache-path before storing it.
31570b57cec5SDimitry Andric SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
31580b57cec5SDimitry Andric if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
31590b57cec5SDimitry Andric if (WorkingDir.empty())
31600b57cec5SDimitry Andric llvm::sys::fs::make_absolute(P);
31610b57cec5SDimitry Andric else
31620b57cec5SDimitry Andric llvm::sys::fs::make_absolute(WorkingDir, P);
31630b57cec5SDimitry Andric }
31640b57cec5SDimitry Andric llvm::sys::path::remove_dots(P);
3165*a58f00eaSDimitry Andric Opts.ModuleCachePath = std::string(P);
31660b57cec5SDimitry Andric
31670b57cec5SDimitry Andric // Only the -fmodule-file=<name>=<file> form.
31680b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_fmodule_file)) {
31690b57cec5SDimitry Andric StringRef Val = A->getValue();
3170349cc55cSDimitry Andric if (Val.contains('=')) {
31715ffd83dbSDimitry Andric auto Split = Val.split('=');
3172c9157d92SDimitry Andric Opts.PrebuiltModuleFiles.insert_or_assign(
3173c9157d92SDimitry Andric std::string(Split.first), std::string(Split.second));
31745ffd83dbSDimitry Andric }
31750b57cec5SDimitry Andric }
31760b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
31770b57cec5SDimitry Andric Opts.AddPrebuiltModulePath(A->getValue());
31780b57cec5SDimitry Andric
31790b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
31800b57cec5SDimitry Andric StringRef MacroDef = A->getValue();
31810b57cec5SDimitry Andric Opts.ModulesIgnoreMacros.insert(
31820b57cec5SDimitry Andric llvm::CachedHashString(MacroDef.split('=').first));
31830b57cec5SDimitry Andric }
31840b57cec5SDimitry Andric
31850b57cec5SDimitry Andric // Add -I..., -F..., and -index-header-map options in order.
31860b57cec5SDimitry Andric bool IsIndexHeaderMap = false;
31870b57cec5SDimitry Andric bool IsSysrootSpecified =
31880b57cec5SDimitry Andric Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
31890b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
31900b57cec5SDimitry Andric if (A->getOption().matches(OPT_index_header_map)) {
31910b57cec5SDimitry Andric // -index-header-map applies to the next -I or -F.
31920b57cec5SDimitry Andric IsIndexHeaderMap = true;
31930b57cec5SDimitry Andric continue;
31940b57cec5SDimitry Andric }
31950b57cec5SDimitry Andric
31960b57cec5SDimitry Andric frontend::IncludeDirGroup Group =
31970b57cec5SDimitry Andric IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
31980b57cec5SDimitry Andric
31990b57cec5SDimitry Andric bool IsFramework = A->getOption().matches(OPT_F);
32000b57cec5SDimitry Andric std::string Path = A->getValue();
32010b57cec5SDimitry Andric
32020b57cec5SDimitry Andric if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
32030b57cec5SDimitry Andric SmallString<32> Buffer;
32040b57cec5SDimitry Andric llvm::sys::path::append(Buffer, Opts.Sysroot,
32050b57cec5SDimitry Andric llvm::StringRef(A->getValue()).substr(1));
3206*a58f00eaSDimitry Andric Path = std::string(Buffer);
32070b57cec5SDimitry Andric }
32080b57cec5SDimitry Andric
32090b57cec5SDimitry Andric Opts.AddPath(Path, Group, IsFramework,
32100b57cec5SDimitry Andric /*IgnoreSysroot*/ true);
32110b57cec5SDimitry Andric IsIndexHeaderMap = false;
32120b57cec5SDimitry Andric }
32130b57cec5SDimitry Andric
32140b57cec5SDimitry Andric // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
32150b57cec5SDimitry Andric StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
32160b57cec5SDimitry Andric for (const auto *A :
32170b57cec5SDimitry Andric Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
32180b57cec5SDimitry Andric if (A->getOption().matches(OPT_iprefix))
32190b57cec5SDimitry Andric Prefix = A->getValue();
32200b57cec5SDimitry Andric else if (A->getOption().matches(OPT_iwithprefix))
32210b57cec5SDimitry Andric Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
32220b57cec5SDimitry Andric else
32230b57cec5SDimitry Andric Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
32240b57cec5SDimitry Andric }
32250b57cec5SDimitry Andric
32260b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_idirafter))
32270b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::After, false, true);
32280b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_iquote))
32290b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
32300b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
32310b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::System, false,
32320b57cec5SDimitry Andric !A->getOption().matches(OPT_iwithsysroot));
32330b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_iframework))
32340b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::System, true, true);
32350b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
32360b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
32370b57cec5SDimitry Andric /*IgnoreSysRoot=*/false);
32380b57cec5SDimitry Andric
32390b57cec5SDimitry Andric // Add the paths for the various language specific isystem flags.
32400b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_c_isystem))
32410b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
32420b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_cxx_isystem))
32430b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
32440b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_objc_isystem))
32450b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
32460b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_objcxx_isystem))
32470b57cec5SDimitry Andric Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
32480b57cec5SDimitry Andric
32490b57cec5SDimitry Andric // Add the internal paths from a driver that detects standard include paths.
32500b57cec5SDimitry Andric for (const auto *A :
32510b57cec5SDimitry Andric Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
32520b57cec5SDimitry Andric frontend::IncludeDirGroup Group = frontend::System;
32530b57cec5SDimitry Andric if (A->getOption().matches(OPT_internal_externc_isystem))
32540b57cec5SDimitry Andric Group = frontend::ExternCSystem;
32550b57cec5SDimitry Andric Opts.AddPath(A->getValue(), Group, false, true);
32560b57cec5SDimitry Andric }
32570b57cec5SDimitry Andric
32580b57cec5SDimitry Andric // Add the path prefixes which are implicitly treated as being system headers.
32590b57cec5SDimitry Andric for (const auto *A :
32600b57cec5SDimitry Andric Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
32610b57cec5SDimitry Andric Opts.AddSystemHeaderPrefix(
32620b57cec5SDimitry Andric A->getValue(), A->getOption().matches(OPT_system_header_prefix));
32630b57cec5SDimitry Andric
3264fe013be4SDimitry Andric for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay))
32650b57cec5SDimitry Andric Opts.AddVFSOverlayFile(A->getValue());
3266fe6060f1SDimitry Andric
3267fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
32680b57cec5SDimitry Andric }
32690b57cec5SDimitry Andric
GenerateAPINotesArgs(const APINotesOptions & Opts,ArgumentConsumer Consumer)3270c9157d92SDimitry Andric static void GenerateAPINotesArgs(const APINotesOptions &Opts,
3271c9157d92SDimitry Andric ArgumentConsumer Consumer) {
3272c9157d92SDimitry Andric if (!Opts.SwiftVersion.empty())
3273c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fapinotes_swift_version,
3274c9157d92SDimitry Andric Opts.SwiftVersion.getAsString());
3275c9157d92SDimitry Andric
3276c9157d92SDimitry Andric for (const auto &Path : Opts.ModuleSearchPaths)
3277c9157d92SDimitry Andric GenerateArg(Consumer, OPT_iapinotes_modules, Path);
3278c9157d92SDimitry Andric }
3279c9157d92SDimitry Andric
ParseAPINotesArgs(APINotesOptions & Opts,ArgList & Args,DiagnosticsEngine & diags)3280c9157d92SDimitry Andric static void ParseAPINotesArgs(APINotesOptions &Opts, ArgList &Args,
3281c9157d92SDimitry Andric DiagnosticsEngine &diags) {
3282c9157d92SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_fapinotes_swift_version)) {
3283c9157d92SDimitry Andric if (Opts.SwiftVersion.tryParse(A->getValue()))
3284c9157d92SDimitry Andric diags.Report(diag::err_drv_invalid_value)
3285c9157d92SDimitry Andric << A->getAsString(Args) << A->getValue();
3286c9157d92SDimitry Andric }
3287c9157d92SDimitry Andric for (const Arg *A : Args.filtered(OPT_iapinotes_modules))
3288c9157d92SDimitry Andric Opts.ModuleSearchPaths.push_back(A->getValue());
3289c9157d92SDimitry Andric }
3290c9157d92SDimitry Andric
32910b57cec5SDimitry Andric /// Check if input file kind and language standard are compatible.
IsInputCompatibleWithStandard(InputKind IK,const LangStandard & S)32920b57cec5SDimitry Andric static bool IsInputCompatibleWithStandard(InputKind IK,
32930b57cec5SDimitry Andric const LangStandard &S) {
32940b57cec5SDimitry Andric switch (IK.getLanguage()) {
3295a7dea167SDimitry Andric case Language::Unknown:
3296a7dea167SDimitry Andric case Language::LLVM_IR:
32970b57cec5SDimitry Andric llvm_unreachable("should not parse language flags for this input");
32980b57cec5SDimitry Andric
3299a7dea167SDimitry Andric case Language::C:
3300a7dea167SDimitry Andric case Language::ObjC:
3301a7dea167SDimitry Andric case Language::RenderScript:
3302a7dea167SDimitry Andric return S.getLanguage() == Language::C;
33030b57cec5SDimitry Andric
3304a7dea167SDimitry Andric case Language::OpenCL:
3305fe6060f1SDimitry Andric return S.getLanguage() == Language::OpenCL ||
3306fe6060f1SDimitry Andric S.getLanguage() == Language::OpenCLCXX;
3307fe6060f1SDimitry Andric
3308fe6060f1SDimitry Andric case Language::OpenCLCXX:
3309fe6060f1SDimitry Andric return S.getLanguage() == Language::OpenCLCXX;
33100b57cec5SDimitry Andric
3311a7dea167SDimitry Andric case Language::CXX:
3312a7dea167SDimitry Andric case Language::ObjCXX:
3313a7dea167SDimitry Andric return S.getLanguage() == Language::CXX;
33140b57cec5SDimitry Andric
3315a7dea167SDimitry Andric case Language::CUDA:
33160b57cec5SDimitry Andric // FIXME: What -std= values should be permitted for CUDA compilations?
3317a7dea167SDimitry Andric return S.getLanguage() == Language::CUDA ||
3318a7dea167SDimitry Andric S.getLanguage() == Language::CXX;
33190b57cec5SDimitry Andric
3320a7dea167SDimitry Andric case Language::HIP:
3321a7dea167SDimitry Andric return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
33220b57cec5SDimitry Andric
3323a7dea167SDimitry Andric case Language::Asm:
33240b57cec5SDimitry Andric // Accept (and ignore) all -std= values.
33250b57cec5SDimitry Andric // FIXME: The -std= value is not ignored; it affects the tokenization
33260b57cec5SDimitry Andric // and preprocessing rules if we're preprocessing this asm input.
33270b57cec5SDimitry Andric return true;
332881ad6265SDimitry Andric
332981ad6265SDimitry Andric case Language::HLSL:
333081ad6265SDimitry Andric return S.getLanguage() == Language::HLSL;
33310b57cec5SDimitry Andric }
33320b57cec5SDimitry Andric
33330b57cec5SDimitry Andric llvm_unreachable("unexpected input language");
33340b57cec5SDimitry Andric }
33350b57cec5SDimitry Andric
33360b57cec5SDimitry Andric /// Get language name for given input kind.
GetInputKindName(InputKind IK)333704eeddc0SDimitry Andric static StringRef GetInputKindName(InputKind IK) {
33380b57cec5SDimitry Andric switch (IK.getLanguage()) {
3339a7dea167SDimitry Andric case Language::C:
33400b57cec5SDimitry Andric return "C";
3341a7dea167SDimitry Andric case Language::ObjC:
33420b57cec5SDimitry Andric return "Objective-C";
3343a7dea167SDimitry Andric case Language::CXX:
33440b57cec5SDimitry Andric return "C++";
3345a7dea167SDimitry Andric case Language::ObjCXX:
33460b57cec5SDimitry Andric return "Objective-C++";
3347a7dea167SDimitry Andric case Language::OpenCL:
33480b57cec5SDimitry Andric return "OpenCL";
3349fe6060f1SDimitry Andric case Language::OpenCLCXX:
3350fe6060f1SDimitry Andric return "C++ for OpenCL";
3351a7dea167SDimitry Andric case Language::CUDA:
33520b57cec5SDimitry Andric return "CUDA";
3353a7dea167SDimitry Andric case Language::RenderScript:
33540b57cec5SDimitry Andric return "RenderScript";
3355a7dea167SDimitry Andric case Language::HIP:
33560b57cec5SDimitry Andric return "HIP";
33570b57cec5SDimitry Andric
3358a7dea167SDimitry Andric case Language::Asm:
33590b57cec5SDimitry Andric return "Asm";
3360a7dea167SDimitry Andric case Language::LLVM_IR:
33610b57cec5SDimitry Andric return "LLVM IR";
33620b57cec5SDimitry Andric
336381ad6265SDimitry Andric case Language::HLSL:
336481ad6265SDimitry Andric return "HLSL";
336581ad6265SDimitry Andric
3366a7dea167SDimitry Andric case Language::Unknown:
33670b57cec5SDimitry Andric break;
33680b57cec5SDimitry Andric }
33690b57cec5SDimitry Andric llvm_unreachable("unknown input language");
33700b57cec5SDimitry Andric }
33710b57cec5SDimitry Andric
GenerateLangArgs(const LangOptions & Opts,ArgumentConsumer Consumer,const llvm::Triple & T,InputKind IK)3372c9157d92SDimitry Andric void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts,
3373c9157d92SDimitry Andric ArgumentConsumer Consumer,
3374c9157d92SDimitry Andric const llvm::Triple &T,
3375c9157d92SDimitry Andric InputKind IK) {
3376fe6060f1SDimitry Andric if (IK.getFormat() == InputKind::Precompiled ||
3377fe6060f1SDimitry Andric IK.getLanguage() == Language::LLVM_IR) {
3378fe6060f1SDimitry Andric if (Opts.ObjCAutoRefCount)
3379c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_arc);
3380fe6060f1SDimitry Andric if (Opts.PICLevel != 0)
3381c9157d92SDimitry Andric GenerateArg(Consumer, OPT_pic_level, Twine(Opts.PICLevel));
3382fe6060f1SDimitry Andric if (Opts.PIE)
3383c9157d92SDimitry Andric GenerateArg(Consumer, OPT_pic_is_pie);
3384fe6060f1SDimitry Andric for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3385c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3386fe6060f1SDimitry Andric
3387fe6060f1SDimitry Andric return;
3388e8d8bef9SDimitry Andric }
3389e8d8bef9SDimitry Andric
3390fe6060f1SDimitry Andric OptSpecifier StdOpt;
3391fe6060f1SDimitry Andric switch (Opts.LangStd) {
3392fe6060f1SDimitry Andric case LangStandard::lang_opencl10:
3393fe6060f1SDimitry Andric case LangStandard::lang_opencl11:
3394fe6060f1SDimitry Andric case LangStandard::lang_opencl12:
3395fe6060f1SDimitry Andric case LangStandard::lang_opencl20:
3396fe6060f1SDimitry Andric case LangStandard::lang_opencl30:
3397349cc55cSDimitry Andric case LangStandard::lang_openclcpp10:
3398349cc55cSDimitry Andric case LangStandard::lang_openclcpp2021:
3399fe6060f1SDimitry Andric StdOpt = OPT_cl_std_EQ;
3400fe6060f1SDimitry Andric break;
3401fe6060f1SDimitry Andric default:
3402fe6060f1SDimitry Andric StdOpt = OPT_std_EQ;
3403fe6060f1SDimitry Andric break;
3404fe6060f1SDimitry Andric }
3405fe6060f1SDimitry Andric
3406fe6060f1SDimitry Andric auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3407c9157d92SDimitry Andric GenerateArg(Consumer, StdOpt, LangStandard.getName());
3408fe6060f1SDimitry Andric
3409fe6060f1SDimitry Andric if (Opts.IncludeDefaultHeader)
3410c9157d92SDimitry Andric GenerateArg(Consumer, OPT_finclude_default_header);
3411fe6060f1SDimitry Andric if (Opts.DeclareOpenCLBuiltins)
3412c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdeclare_opencl_builtins);
3413fe6060f1SDimitry Andric
3414fe6060f1SDimitry Andric const LangOptions *LangOpts = &Opts;
3415fe6060f1SDimitry Andric
3416fe013be4SDimitry Andric #define LANG_OPTION_WITH_MARSHALLING(...) \
3417c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3418fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
3419fe6060f1SDimitry Andric #undef LANG_OPTION_WITH_MARSHALLING
3420fe6060f1SDimitry Andric
3421fe6060f1SDimitry Andric // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3422fe6060f1SDimitry Andric
3423fe6060f1SDimitry Andric if (Opts.ObjC) {
3424c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString());
3425fe6060f1SDimitry Andric
3426fe6060f1SDimitry Andric if (Opts.GC == LangOptions::GCOnly)
3427c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_gc_only);
3428fe6060f1SDimitry Andric else if (Opts.GC == LangOptions::HybridGC)
3429c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_gc);
3430fe6060f1SDimitry Andric else if (Opts.ObjCAutoRefCount == 1)
3431c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_arc);
3432fe6060f1SDimitry Andric
3433fe6060f1SDimitry Andric if (Opts.ObjCWeakRuntime)
3434c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_runtime_has_weak);
3435fe6060f1SDimitry Andric
3436fe6060f1SDimitry Andric if (Opts.ObjCWeak)
3437c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_weak);
3438fe6060f1SDimitry Andric
3439fe6060f1SDimitry Andric if (Opts.ObjCSubscriptingLegacyRuntime)
3440c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fobjc_subscripting_legacy_runtime);
3441fe6060f1SDimitry Andric }
3442fe6060f1SDimitry Andric
3443fe6060f1SDimitry Andric if (Opts.GNUCVersion != 0) {
3444fe6060f1SDimitry Andric unsigned Major = Opts.GNUCVersion / 100 / 100;
3445fe6060f1SDimitry Andric unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3446fe6060f1SDimitry Andric unsigned Patch = Opts.GNUCVersion % 100;
3447c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fgnuc_version_EQ,
3448c9157d92SDimitry Andric Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch));
3449fe6060f1SDimitry Andric }
3450fe6060f1SDimitry Andric
3451fe6060f1SDimitry Andric if (Opts.IgnoreXCOFFVisibility)
3452c9157d92SDimitry Andric GenerateArg(Consumer, OPT_mignore_xcoff_visibility);
3453fe6060f1SDimitry Andric
3454fe6060f1SDimitry Andric if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3455c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ftrapv);
3456c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ftrapv_handler, Opts.OverflowHandler);
3457fe6060f1SDimitry Andric } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3458c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fwrapv);
3459fe6060f1SDimitry Andric }
3460fe6060f1SDimitry Andric
3461fe6060f1SDimitry Andric if (Opts.MSCompatibilityVersion != 0) {
3462fe6060f1SDimitry Andric unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3463fe6060f1SDimitry Andric unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3464fe6060f1SDimitry Andric unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3465c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fms_compatibility_version,
3466c9157d92SDimitry Andric Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor));
3467fe6060f1SDimitry Andric }
3468fe6060f1SDimitry Andric
3469*a58f00eaSDimitry Andric if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
3470*a58f00eaSDimitry Andric T.isOSzOS()) {
3471fe6060f1SDimitry Andric if (!Opts.Trigraphs)
3472c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_trigraphs);
3473fe6060f1SDimitry Andric } else {
3474fe6060f1SDimitry Andric if (Opts.Trigraphs)
3475c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ftrigraphs);
3476fe6060f1SDimitry Andric }
3477fe6060f1SDimitry Andric
3478fe6060f1SDimitry Andric if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3479c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fblocks);
3480fe6060f1SDimitry Andric
3481fe6060f1SDimitry Andric if (Opts.ConvergentFunctions &&
3482fe6060f1SDimitry Andric !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3483c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fconvergent_functions);
3484fe6060f1SDimitry Andric
3485fe6060f1SDimitry Andric if (Opts.NoBuiltin && !Opts.Freestanding)
3486c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_builtin);
3487fe6060f1SDimitry Andric
3488fe6060f1SDimitry Andric if (!Opts.NoBuiltin)
3489fe6060f1SDimitry Andric for (const auto &Func : Opts.NoBuiltinFuncs)
3490c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_builtin_, Func);
3491fe6060f1SDimitry Andric
3492fe6060f1SDimitry Andric if (Opts.LongDoubleSize == 128)
3493c9157d92SDimitry Andric GenerateArg(Consumer, OPT_mlong_double_128);
3494fe6060f1SDimitry Andric else if (Opts.LongDoubleSize == 64)
3495c9157d92SDimitry Andric GenerateArg(Consumer, OPT_mlong_double_64);
349681ad6265SDimitry Andric else if (Opts.LongDoubleSize == 80)
3497c9157d92SDimitry Andric GenerateArg(Consumer, OPT_mlong_double_80);
3498fe6060f1SDimitry Andric
3499fe6060f1SDimitry Andric // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3500fe6060f1SDimitry Andric
3501fe6060f1SDimitry Andric // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3502fe6060f1SDimitry Andric // '-fopenmp-targets='.
3503fe6060f1SDimitry Andric if (Opts.OpenMP && !Opts.OpenMPSimd) {
3504c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp);
3505fe6060f1SDimitry Andric
3506fe013be4SDimitry Andric if (Opts.OpenMP != 51)
3507c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3508fe6060f1SDimitry Andric
3509fe6060f1SDimitry Andric if (!Opts.OpenMPUseTLS)
3510c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fnoopenmp_use_tls);
3511fe6060f1SDimitry Andric
3512fe013be4SDimitry Andric if (Opts.OpenMPIsTargetDevice)
3513c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_is_target_device);
3514fe6060f1SDimitry Andric
3515fe6060f1SDimitry Andric if (Opts.OpenMPIRBuilder)
3516c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_enable_irbuilder);
3517fe6060f1SDimitry Andric }
3518fe6060f1SDimitry Andric
3519fe6060f1SDimitry Andric if (Opts.OpenMPSimd) {
3520c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_simd);
3521fe6060f1SDimitry Andric
3522fe013be4SDimitry Andric if (Opts.OpenMP != 51)
3523c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3524fe6060f1SDimitry Andric }
3525fe6060f1SDimitry Andric
3526349cc55cSDimitry Andric if (Opts.OpenMPThreadSubscription)
3527c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_assume_threads_oversubscription);
3528349cc55cSDimitry Andric
3529349cc55cSDimitry Andric if (Opts.OpenMPTeamSubscription)
3530c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_assume_teams_oversubscription);
3531349cc55cSDimitry Andric
3532349cc55cSDimitry Andric if (Opts.OpenMPTargetDebug != 0)
3533c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_target_debug_EQ,
3534c9157d92SDimitry Andric Twine(Opts.OpenMPTargetDebug));
3535349cc55cSDimitry Andric
3536fe6060f1SDimitry Andric if (Opts.OpenMPCUDANumSMs != 0)
3537c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_cuda_number_of_sm_EQ,
3538c9157d92SDimitry Andric Twine(Opts.OpenMPCUDANumSMs));
3539fe6060f1SDimitry Andric
3540fe6060f1SDimitry Andric if (Opts.OpenMPCUDABlocksPerSM != 0)
3541c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3542c9157d92SDimitry Andric Twine(Opts.OpenMPCUDABlocksPerSM));
3543fe6060f1SDimitry Andric
3544fe6060f1SDimitry Andric if (Opts.OpenMPCUDAReductionBufNum != 1024)
3545c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3546c9157d92SDimitry Andric Twine(Opts.OpenMPCUDAReductionBufNum));
3547fe6060f1SDimitry Andric
3548fe6060f1SDimitry Andric if (!Opts.OMPTargetTriples.empty()) {
3549fe6060f1SDimitry Andric std::string Targets;
3550fe6060f1SDimitry Andric llvm::raw_string_ostream OS(Targets);
3551fe6060f1SDimitry Andric llvm::interleave(
3552fe6060f1SDimitry Andric Opts.OMPTargetTriples, OS,
3553fe6060f1SDimitry Andric [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3554c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_targets_EQ, OS.str());
3555fe6060f1SDimitry Andric }
3556fe6060f1SDimitry Andric
3557fe6060f1SDimitry Andric if (!Opts.OMPHostIRFile.empty())
3558c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile);
3559fe6060f1SDimitry Andric
3560fe6060f1SDimitry Andric if (Opts.OpenMPCUDAMode)
3561c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenmp_cuda_mode);
3562c9157d92SDimitry Andric
3563c9157d92SDimitry Andric if (Opts.OpenACC) {
3564c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fopenacc);
3565c9157d92SDimitry Andric if (!Opts.OpenACCMacroOverride.empty())
3566c9157d92SDimitry Andric GenerateArg(Consumer, OPT_openacc_macro_override,
3567c9157d92SDimitry Andric Opts.OpenACCMacroOverride);
3568c9157d92SDimitry Andric }
3569fe6060f1SDimitry Andric
3570fe6060f1SDimitry Andric // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3571fe6060f1SDimitry Andric // generated from CodeGenOptions.
3572fe6060f1SDimitry Andric
3573fe6060f1SDimitry Andric if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3574c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ffp_contract, "fast");
3575fe6060f1SDimitry Andric else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3576c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ffp_contract, "on");
3577fe6060f1SDimitry Andric else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3578c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ffp_contract, "off");
3579fe6060f1SDimitry Andric else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3580c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ffp_contract, "fast-honor-pragmas");
3581fe6060f1SDimitry Andric
3582fe6060f1SDimitry Andric for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3583c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3584fe6060f1SDimitry Andric
3585fe6060f1SDimitry Andric // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3586fe6060f1SDimitry Andric for (const std::string &F : Opts.NoSanitizeFiles)
3587c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fsanitize_ignorelist_EQ, F);
3588fe6060f1SDimitry Andric
3589c9157d92SDimitry Andric switch (Opts.getClangABICompat()) {
3590c9157d92SDimitry Andric case LangOptions::ClangABI::Ver3_8:
3591c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "3.8");
3592c9157d92SDimitry Andric break;
3593c9157d92SDimitry Andric case LangOptions::ClangABI::Ver4:
3594c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "4.0");
3595c9157d92SDimitry Andric break;
3596c9157d92SDimitry Andric case LangOptions::ClangABI::Ver6:
3597c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "6.0");
3598c9157d92SDimitry Andric break;
3599c9157d92SDimitry Andric case LangOptions::ClangABI::Ver7:
3600c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "7.0");
3601c9157d92SDimitry Andric break;
3602c9157d92SDimitry Andric case LangOptions::ClangABI::Ver9:
3603c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "9.0");
3604c9157d92SDimitry Andric break;
3605c9157d92SDimitry Andric case LangOptions::ClangABI::Ver11:
3606c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "11.0");
3607c9157d92SDimitry Andric break;
3608c9157d92SDimitry Andric case LangOptions::ClangABI::Ver12:
3609c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "12.0");
3610c9157d92SDimitry Andric break;
3611c9157d92SDimitry Andric case LangOptions::ClangABI::Ver14:
3612c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "14.0");
3613c9157d92SDimitry Andric break;
3614c9157d92SDimitry Andric case LangOptions::ClangABI::Ver15:
3615c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "15.0");
3616c9157d92SDimitry Andric break;
3617c9157d92SDimitry Andric case LangOptions::ClangABI::Ver17:
3618c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "17.0");
3619c9157d92SDimitry Andric break;
3620c9157d92SDimitry Andric case LangOptions::ClangABI::Latest:
3621c9157d92SDimitry Andric break;
3622c9157d92SDimitry Andric }
3623fe6060f1SDimitry Andric
3624fe6060f1SDimitry Andric if (Opts.getSignReturnAddressScope() ==
3625fe6060f1SDimitry Andric LangOptions::SignReturnAddressScopeKind::All)
3626c9157d92SDimitry Andric GenerateArg(Consumer, OPT_msign_return_address_EQ, "all");
3627fe6060f1SDimitry Andric else if (Opts.getSignReturnAddressScope() ==
3628fe6060f1SDimitry Andric LangOptions::SignReturnAddressScopeKind::NonLeaf)
3629c9157d92SDimitry Andric GenerateArg(Consumer, OPT_msign_return_address_EQ, "non-leaf");
3630fe6060f1SDimitry Andric
3631fe6060f1SDimitry Andric if (Opts.getSignReturnAddressKey() ==
3632fe6060f1SDimitry Andric LangOptions::SignReturnAddressKeyKind::BKey)
3633c9157d92SDimitry Andric GenerateArg(Consumer, OPT_msign_return_address_key_EQ, "b_key");
3634fe6060f1SDimitry Andric
3635fe6060f1SDimitry Andric if (Opts.CXXABI)
3636c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fcxx_abi_EQ,
3637c9157d92SDimitry Andric TargetCXXABI::getSpelling(*Opts.CXXABI));
3638fe6060f1SDimitry Andric
3639fe6060f1SDimitry Andric if (Opts.RelativeCXXABIVTables)
3640c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fexperimental_relative_cxx_abi_vtables);
3641fe6060f1SDimitry Andric else
3642c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_experimental_relative_cxx_abi_vtables);
36436e75b2fbSDimitry Andric
364481ad6265SDimitry Andric if (Opts.UseTargetPathSeparator)
3645c9157d92SDimitry Andric GenerateArg(Consumer, OPT_ffile_reproducible);
364681ad6265SDimitry Andric else
3647c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fno_file_reproducible);
364881ad6265SDimitry Andric
36496e75b2fbSDimitry Andric for (const auto &MP : Opts.MacroPrefixMap)
3650c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second);
365181ad6265SDimitry Andric
365281ad6265SDimitry Andric if (!Opts.RandstructSeed.empty())
3653c9157d92SDimitry Andric GenerateArg(Consumer, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed);
3654fe6060f1SDimitry Andric }
3655fe6060f1SDimitry Andric
ParseLangArgs(LangOptions & Opts,ArgList & Args,InputKind IK,const llvm::Triple & T,std::vector<std::string> & Includes,DiagnosticsEngine & Diags)3656fe6060f1SDimitry Andric bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3657e8d8bef9SDimitry Andric InputKind IK, const llvm::Triple &T,
3658e8d8bef9SDimitry Andric std::vector<std::string> &Includes,
36590b57cec5SDimitry Andric DiagnosticsEngine &Diags) {
3660fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
3661fe6060f1SDimitry Andric
3662fe6060f1SDimitry Andric if (IK.getFormat() == InputKind::Precompiled ||
3663fe6060f1SDimitry Andric IK.getLanguage() == Language::LLVM_IR) {
3664fe6060f1SDimitry Andric // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3665fe6060f1SDimitry Andric // PassManager in BackendUtil.cpp. They need to be initialized no matter
3666fe6060f1SDimitry Andric // what the input type is.
3667fe6060f1SDimitry Andric if (Args.hasArg(OPT_fobjc_arc))
3668fe6060f1SDimitry Andric Opts.ObjCAutoRefCount = 1;
3669fe6060f1SDimitry Andric // PICLevel and PIELevel are needed during code generation and this should
3670fe6060f1SDimitry Andric // be set regardless of the input type.
3671fe6060f1SDimitry Andric Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3672fe6060f1SDimitry Andric Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3673fe6060f1SDimitry Andric parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3674fe6060f1SDimitry Andric Diags, Opts.Sanitize);
3675fe6060f1SDimitry Andric
3676fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
3677fe6060f1SDimitry Andric }
3678fe6060f1SDimitry Andric
3679fe6060f1SDimitry Andric // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3680fe6060f1SDimitry Andric // FIXME: Should we really be parsing this for an Language::Asm input?
3681fe6060f1SDimitry Andric
36820b57cec5SDimitry Andric // FIXME: Cleanup per-file based stuff.
36830b57cec5SDimitry Andric LangStandard::Kind LangStd = LangStandard::lang_unspecified;
36840b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3685a7dea167SDimitry Andric LangStd = LangStandard::getLangKind(A->getValue());
36860b57cec5SDimitry Andric if (LangStd == LangStandard::lang_unspecified) {
36870b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
36880b57cec5SDimitry Andric << A->getAsString(Args) << A->getValue();
36890b57cec5SDimitry Andric // Report supported standards with short description.
36900b57cec5SDimitry Andric for (unsigned KindValue = 0;
36910b57cec5SDimitry Andric KindValue != LangStandard::lang_unspecified;
36920b57cec5SDimitry Andric ++KindValue) {
36930b57cec5SDimitry Andric const LangStandard &Std = LangStandard::getLangStandardForKind(
36940b57cec5SDimitry Andric static_cast<LangStandard::Kind>(KindValue));
36950b57cec5SDimitry Andric if (IsInputCompatibleWithStandard(IK, Std)) {
36960b57cec5SDimitry Andric auto Diag = Diags.Report(diag::note_drv_use_standard);
36970b57cec5SDimitry Andric Diag << Std.getName() << Std.getDescription();
36980b57cec5SDimitry Andric unsigned NumAliases = 0;
36990b57cec5SDimitry Andric #define LANGSTANDARD(id, name, lang, desc, features)
37000b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS(id, alias) \
37010b57cec5SDimitry Andric if (KindValue == LangStandard::lang_##id) ++NumAliases;
37020b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3703a7dea167SDimitry Andric #include "clang/Basic/LangStandards.def"
37040b57cec5SDimitry Andric Diag << NumAliases;
37050b57cec5SDimitry Andric #define LANGSTANDARD(id, name, lang, desc, features)
37060b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS(id, alias) \
37070b57cec5SDimitry Andric if (KindValue == LangStandard::lang_##id) Diag << alias;
37080b57cec5SDimitry Andric #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3709a7dea167SDimitry Andric #include "clang/Basic/LangStandards.def"
37100b57cec5SDimitry Andric }
37110b57cec5SDimitry Andric }
37120b57cec5SDimitry Andric } else {
37130b57cec5SDimitry Andric // Valid standard, check to make sure language and standard are
37140b57cec5SDimitry Andric // compatible.
37150b57cec5SDimitry Andric const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
37160b57cec5SDimitry Andric if (!IsInputCompatibleWithStandard(IK, Std)) {
37170b57cec5SDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
37180b57cec5SDimitry Andric << A->getAsString(Args) << GetInputKindName(IK);
37190b57cec5SDimitry Andric }
37200b57cec5SDimitry Andric }
37210b57cec5SDimitry Andric }
37220b57cec5SDimitry Andric
37230b57cec5SDimitry Andric // -cl-std only applies for OpenCL language standards.
37240b57cec5SDimitry Andric // Override the -std option in this case.
37250b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
37260b57cec5SDimitry Andric LangStandard::Kind OpenCLLangStd
37270b57cec5SDimitry Andric = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
37280b57cec5SDimitry Andric .Cases("cl", "CL", LangStandard::lang_opencl10)
3729e8d8bef9SDimitry Andric .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
37300b57cec5SDimitry Andric .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
37310b57cec5SDimitry Andric .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
37320b57cec5SDimitry Andric .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3733e8d8bef9SDimitry Andric .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3734349cc55cSDimitry Andric .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
3735349cc55cSDimitry Andric .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
3736349cc55cSDimitry Andric .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
37370b57cec5SDimitry Andric .Default(LangStandard::lang_unspecified);
37380b57cec5SDimitry Andric
37390b57cec5SDimitry Andric if (OpenCLLangStd == LangStandard::lang_unspecified) {
37400b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
37410b57cec5SDimitry Andric << A->getAsString(Args) << A->getValue();
37420b57cec5SDimitry Andric }
37430b57cec5SDimitry Andric else
37440b57cec5SDimitry Andric LangStd = OpenCLLangStd;
37450b57cec5SDimitry Andric }
37460b57cec5SDimitry Andric
3747e8d8bef9SDimitry Andric // These need to be parsed now. They are used to set OpenCL defaults.
37480b57cec5SDimitry Andric Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
37490b57cec5SDimitry Andric Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
37500b57cec5SDimitry Andric
375181ad6265SDimitry Andric LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
37520b57cec5SDimitry Andric
3753e8d8bef9SDimitry Andric // The key paths of codegen options defined in Options.td start with
3754e8d8bef9SDimitry Andric // "LangOpts->". Let's provide the expected variable name and type.
3755e8d8bef9SDimitry Andric LangOptions *LangOpts = &Opts;
3756e8d8bef9SDimitry Andric
3757fe013be4SDimitry Andric #define LANG_OPTION_WITH_MARSHALLING(...) \
3758fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3759e8d8bef9SDimitry Andric #include "clang/Driver/Options.inc"
3760e8d8bef9SDimitry Andric #undef LANG_OPTION_WITH_MARSHALLING
3761e8d8bef9SDimitry Andric
3762e8d8bef9SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3763e8d8bef9SDimitry Andric StringRef Name = A->getValue();
3764e8d8bef9SDimitry Andric if (Name == "full" || Name == "branch") {
3765e8d8bef9SDimitry Andric Opts.CFProtectionBranch = 1;
37660b57cec5SDimitry Andric }
3767e8d8bef9SDimitry Andric }
37680b57cec5SDimitry Andric
3769fe6060f1SDimitry Andric if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3770fe6060f1SDimitry Andric !Args.hasArg(OPT_sycl_std_EQ)) {
3771fe6060f1SDimitry Andric // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3772fe6060f1SDimitry Andric // provide -sycl-std=, we want to default it to whatever the default SYCL
3773fe6060f1SDimitry Andric // version is. I could not find a way to express this with the options
3774fe6060f1SDimitry Andric // tablegen because we still want this value to be SYCL_None when the user
3775fe6060f1SDimitry Andric // is not in device or host mode.
3776fe6060f1SDimitry Andric Opts.setSYCLVersion(LangOptions::SYCL_Default);
3777fe6060f1SDimitry Andric }
37780b57cec5SDimitry Andric
37790b57cec5SDimitry Andric if (Opts.ObjC) {
37800b57cec5SDimitry Andric if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
37810b57cec5SDimitry Andric StringRef value = arg->getValue();
37820b57cec5SDimitry Andric if (Opts.ObjCRuntime.tryParse(value))
37830b57cec5SDimitry Andric Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
37840b57cec5SDimitry Andric }
37850b57cec5SDimitry Andric
37860b57cec5SDimitry Andric if (Args.hasArg(OPT_fobjc_gc_only))
37870b57cec5SDimitry Andric Opts.setGC(LangOptions::GCOnly);
37880b57cec5SDimitry Andric else if (Args.hasArg(OPT_fobjc_gc))
37890b57cec5SDimitry Andric Opts.setGC(LangOptions::HybridGC);
37900b57cec5SDimitry Andric else if (Args.hasArg(OPT_fobjc_arc)) {
37910b57cec5SDimitry Andric Opts.ObjCAutoRefCount = 1;
37920b57cec5SDimitry Andric if (!Opts.ObjCRuntime.allowsARC())
37930b57cec5SDimitry Andric Diags.Report(diag::err_arc_unsupported_on_runtime);
37940b57cec5SDimitry Andric }
37950b57cec5SDimitry Andric
37960b57cec5SDimitry Andric // ObjCWeakRuntime tracks whether the runtime supports __weak, not
37970b57cec5SDimitry Andric // whether the feature is actually enabled. This is predominantly
37980b57cec5SDimitry Andric // determined by -fobjc-runtime, but we allow it to be overridden
37990b57cec5SDimitry Andric // from the command line for testing purposes.
38000b57cec5SDimitry Andric if (Args.hasArg(OPT_fobjc_runtime_has_weak))
38010b57cec5SDimitry Andric Opts.ObjCWeakRuntime = 1;
38020b57cec5SDimitry Andric else
38030b57cec5SDimitry Andric Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
38040b57cec5SDimitry Andric
38050b57cec5SDimitry Andric // ObjCWeak determines whether __weak is actually enabled.
38060b57cec5SDimitry Andric // Note that we allow -fno-objc-weak to disable this even in ARC mode.
38070b57cec5SDimitry Andric if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
38080b57cec5SDimitry Andric if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
38090b57cec5SDimitry Andric assert(!Opts.ObjCWeak);
38100b57cec5SDimitry Andric } else if (Opts.getGC() != LangOptions::NonGC) {
38110b57cec5SDimitry Andric Diags.Report(diag::err_objc_weak_with_gc);
38120b57cec5SDimitry Andric } else if (!Opts.ObjCWeakRuntime) {
38130b57cec5SDimitry Andric Diags.Report(diag::err_objc_weak_unsupported);
38140b57cec5SDimitry Andric } else {
38150b57cec5SDimitry Andric Opts.ObjCWeak = 1;
38160b57cec5SDimitry Andric }
38170b57cec5SDimitry Andric } else if (Opts.ObjCAutoRefCount) {
38180b57cec5SDimitry Andric Opts.ObjCWeak = Opts.ObjCWeakRuntime;
38190b57cec5SDimitry Andric }
38200b57cec5SDimitry Andric
38210b57cec5SDimitry Andric if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
38220b57cec5SDimitry Andric Opts.ObjCSubscriptingLegacyRuntime =
38230b57cec5SDimitry Andric (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
38240b57cec5SDimitry Andric }
38250b57cec5SDimitry Andric
3826a7dea167SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3827a7dea167SDimitry Andric // Check that the version has 1 to 3 components and the minor and patch
3828a7dea167SDimitry Andric // versions fit in two decimal digits.
3829a7dea167SDimitry Andric VersionTuple GNUCVer;
3830a7dea167SDimitry Andric bool Invalid = GNUCVer.tryParse(A->getValue());
3831a7dea167SDimitry Andric unsigned Major = GNUCVer.getMajor();
383281ad6265SDimitry Andric unsigned Minor = GNUCVer.getMinor().value_or(0);
383381ad6265SDimitry Andric unsigned Patch = GNUCVer.getSubminor().value_or(0);
3834a7dea167SDimitry Andric if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3835a7dea167SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
3836a7dea167SDimitry Andric << A->getAsString(Args) << A->getValue();
3837a7dea167SDimitry Andric }
3838a7dea167SDimitry Andric Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3839a7dea167SDimitry Andric }
3840a7dea167SDimitry Andric
384181ad6265SDimitry Andric if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
3842fe6060f1SDimitry Andric Opts.IgnoreXCOFFVisibility = 1;
3843fe6060f1SDimitry Andric
38440b57cec5SDimitry Andric if (Args.hasArg(OPT_ftrapv)) {
38450b57cec5SDimitry Andric Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
38460b57cec5SDimitry Andric // Set the handler, if one is specified.
38470b57cec5SDimitry Andric Opts.OverflowHandler =
38485ffd83dbSDimitry Andric std::string(Args.getLastArgValue(OPT_ftrapv_handler));
38490b57cec5SDimitry Andric }
38500b57cec5SDimitry Andric else if (Args.hasArg(OPT_fwrapv))
38510b57cec5SDimitry Andric Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
38520b57cec5SDimitry Andric
38530b57cec5SDimitry Andric Opts.MSCompatibilityVersion = 0;
38540b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
38550b57cec5SDimitry Andric VersionTuple VT;
38560b57cec5SDimitry Andric if (VT.tryParse(A->getValue()))
38570b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
38580b57cec5SDimitry Andric << A->getValue();
38590b57cec5SDimitry Andric Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
386081ad6265SDimitry Andric VT.getMinor().value_or(0) * 100000 +
386181ad6265SDimitry Andric VT.getSubminor().value_or(0);
38620b57cec5SDimitry Andric }
38630b57cec5SDimitry Andric
38640b57cec5SDimitry Andric // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
38650b57cec5SDimitry Andric // is specified, or -std is set to a conforming mode.
3866*a58f00eaSDimitry Andric // Trigraphs are disabled by default in C++17 and C23 onwards.
3867e8d8bef9SDimitry Andric // For z/OS, trigraphs are enabled by default (without regard to the above).
3868e8d8bef9SDimitry Andric Opts.Trigraphs =
3869*a58f00eaSDimitry Andric (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
3870*a58f00eaSDimitry Andric T.isOSzOS();
38710b57cec5SDimitry Andric Opts.Trigraphs =
38720b57cec5SDimitry Andric Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
38730b57cec5SDimitry Andric
38740b57cec5SDimitry Andric Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
38750b57cec5SDimitry Andric && Opts.OpenCLVersion == 200);
38760b57cec5SDimitry Andric
3877fe013be4SDimitry Andric Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) ||
3878fe013be4SDimitry Andric Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3879fe013be4SDimitry Andric Opts.SYCLIsDevice;
3880480093f4SDimitry Andric
38810b57cec5SDimitry Andric Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
38820b57cec5SDimitry Andric if (!Opts.NoBuiltin)
38830b57cec5SDimitry Andric getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
388481ad6265SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
388581ad6265SDimitry Andric if (A->getOption().matches(options::OPT_mlong_double_64))
388681ad6265SDimitry Andric Opts.LongDoubleSize = 64;
388781ad6265SDimitry Andric else if (A->getOption().matches(options::OPT_mlong_double_80))
388881ad6265SDimitry Andric Opts.LongDoubleSize = 80;
388981ad6265SDimitry Andric else if (A->getOption().matches(options::OPT_mlong_double_128))
389081ad6265SDimitry Andric Opts.LongDoubleSize = 128;
389181ad6265SDimitry Andric else
389281ad6265SDimitry Andric Opts.LongDoubleSize = 0;
389381ad6265SDimitry Andric }
3894bdd1243dSDimitry Andric if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
38955ffd83dbSDimitry Andric Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
389681ad6265SDimitry Andric
38970b57cec5SDimitry Andric llvm::sort(Opts.ModuleFeatures);
3898e8d8bef9SDimitry Andric
38990b57cec5SDimitry Andric // -mrtd option
39000b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_mrtd)) {
39010b57cec5SDimitry Andric if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
39020b57cec5SDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
39030b57cec5SDimitry Andric << A->getSpelling() << "-fdefault-calling-conv";
39040b57cec5SDimitry Andric else {
3905c9157d92SDimitry Andric switch (T.getArch()) {
3906c9157d92SDimitry Andric case llvm::Triple::x86:
3907c9157d92SDimitry Andric Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3908c9157d92SDimitry Andric break;
3909c9157d92SDimitry Andric case llvm::Triple::m68k:
3910c9157d92SDimitry Andric Opts.setDefaultCallingConv(LangOptions::DCC_RtdCall);
3911c9157d92SDimitry Andric break;
3912c9157d92SDimitry Andric default:
39130b57cec5SDimitry Andric Diags.Report(diag::err_drv_argument_not_allowed_with)
39140b57cec5SDimitry Andric << A->getSpelling() << T.getTriple();
3915c9157d92SDimitry Andric }
39160b57cec5SDimitry Andric }
39170b57cec5SDimitry Andric }
39180b57cec5SDimitry Andric
3919fe6060f1SDimitry Andric // Check if -fopenmp is specified and set default version to 5.0.
3920fe013be4SDimitry Andric Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0;
39210b57cec5SDimitry Andric // Check if -fopenmp-simd is specified.
39220b57cec5SDimitry Andric bool IsSimdSpecified =
39230b57cec5SDimitry Andric Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
39240b57cec5SDimitry Andric /*Default=*/false);
39250b57cec5SDimitry Andric Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
39260b57cec5SDimitry Andric Opts.OpenMPUseTLS =
39270b57cec5SDimitry Andric Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3928fe013be4SDimitry Andric Opts.OpenMPIsTargetDevice =
3929fe013be4SDimitry Andric Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device);
3930480093f4SDimitry Andric Opts.OpenMPIRBuilder =
3931480093f4SDimitry Andric Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
39320b57cec5SDimitry Andric bool IsTargetSpecified =
3933fe013be4SDimitry Andric Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
39340b57cec5SDimitry Andric
3935fe013be4SDimitry Andric Opts.ConvergentFunctions =
3936fe013be4SDimitry Andric Opts.ConvergentFunctions || Opts.OpenMPIsTargetDevice;
3937d409305fSDimitry Andric
39380b57cec5SDimitry Andric if (Opts.OpenMP || Opts.OpenMPSimd) {
39390b57cec5SDimitry Andric if (int Version = getLastArgIntValue(
39400b57cec5SDimitry Andric Args, OPT_fopenmp_version_EQ,
3941fe013be4SDimitry Andric (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
39420b57cec5SDimitry Andric Opts.OpenMP = Version;
39430b57cec5SDimitry Andric // Provide diagnostic when a given target is not expected to be an OpenMP
39440b57cec5SDimitry Andric // device or host.
3945fe013be4SDimitry Andric if (!Opts.OpenMPIsTargetDevice) {
39460b57cec5SDimitry Andric switch (T.getArch()) {
39470b57cec5SDimitry Andric default:
39480b57cec5SDimitry Andric break;
39490b57cec5SDimitry Andric // Add unsupported host targets here:
39500b57cec5SDimitry Andric case llvm::Triple::nvptx:
39510b57cec5SDimitry Andric case llvm::Triple::nvptx64:
3952e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
39530b57cec5SDimitry Andric break;
39540b57cec5SDimitry Andric }
39550b57cec5SDimitry Andric }
39560b57cec5SDimitry Andric }
39570b57cec5SDimitry Andric
39580b57cec5SDimitry Andric // Set the flag to prevent the implementation from emitting device exception
39590b57cec5SDimitry Andric // handling code for those requiring so.
3960fe013be4SDimitry Andric if ((Opts.OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) ||
39615ffd83dbSDimitry Andric Opts.OpenCLCPlusPlus) {
3962349cc55cSDimitry Andric
39630b57cec5SDimitry Andric Opts.Exceptions = 0;
39640b57cec5SDimitry Andric Opts.CXXExceptions = 0;
39650b57cec5SDimitry Andric }
3966fe013be4SDimitry Andric if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) {
39670b57cec5SDimitry Andric Opts.OpenMPCUDANumSMs =
39680b57cec5SDimitry Andric getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
39690b57cec5SDimitry Andric Opts.OpenMPCUDANumSMs, Diags);
39700b57cec5SDimitry Andric Opts.OpenMPCUDABlocksPerSM =
39710b57cec5SDimitry Andric getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
39720b57cec5SDimitry Andric Opts.OpenMPCUDABlocksPerSM, Diags);
39730b57cec5SDimitry Andric Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
39740b57cec5SDimitry Andric Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
39750b57cec5SDimitry Andric Opts.OpenMPCUDAReductionBufNum, Diags);
39760b57cec5SDimitry Andric }
39770b57cec5SDimitry Andric
3978349cc55cSDimitry Andric // Set the value of the debugging flag used in the new offloading device RTL.
3979349cc55cSDimitry Andric // Set either by a specific value or to a default if not specified.
3980fe013be4SDimitry Andric if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
3981349cc55cSDimitry Andric Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
3982349cc55cSDimitry Andric Opts.OpenMPTargetDebug = getLastArgIntValue(
3983349cc55cSDimitry Andric Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
3984349cc55cSDimitry Andric if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
3985349cc55cSDimitry Andric Opts.OpenMPTargetDebug = 1;
3986349cc55cSDimitry Andric }
3987349cc55cSDimitry Andric
3988fe013be4SDimitry Andric if (Opts.OpenMPIsTargetDevice) {
3989349cc55cSDimitry Andric if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
3990349cc55cSDimitry Andric Opts.OpenMPTeamSubscription = true;
3991349cc55cSDimitry Andric if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
3992349cc55cSDimitry Andric Opts.OpenMPThreadSubscription = true;
3993349cc55cSDimitry Andric }
3994349cc55cSDimitry Andric
39950b57cec5SDimitry Andric // Get the OpenMP target triples if any.
39960b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3997e8d8bef9SDimitry Andric enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3998e8d8bef9SDimitry Andric auto getArchPtrSize = [](const llvm::Triple &T) {
3999e8d8bef9SDimitry Andric if (T.isArch16Bit())
4000e8d8bef9SDimitry Andric return Arch16Bit;
4001e8d8bef9SDimitry Andric if (T.isArch32Bit())
4002e8d8bef9SDimitry Andric return Arch32Bit;
4003e8d8bef9SDimitry Andric assert(T.isArch64Bit() && "Expected 64-bit architecture");
4004e8d8bef9SDimitry Andric return Arch64Bit;
4005e8d8bef9SDimitry Andric };
40060b57cec5SDimitry Andric
40070b57cec5SDimitry Andric for (unsigned i = 0; i < A->getNumValues(); ++i) {
40080b57cec5SDimitry Andric llvm::Triple TT(A->getValue(i));
40090b57cec5SDimitry Andric
40100b57cec5SDimitry Andric if (TT.getArch() == llvm::Triple::UnknownArch ||
4011e8d8bef9SDimitry Andric !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
40120b57cec5SDimitry Andric TT.getArch() == llvm::Triple::nvptx ||
40130b57cec5SDimitry Andric TT.getArch() == llvm::Triple::nvptx64 ||
40145ffd83dbSDimitry Andric TT.getArch() == llvm::Triple::amdgcn ||
40150b57cec5SDimitry Andric TT.getArch() == llvm::Triple::x86 ||
40160b57cec5SDimitry Andric TT.getArch() == llvm::Triple::x86_64))
40170b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
4018e8d8bef9SDimitry Andric else if (getArchPtrSize(T) != getArchPtrSize(TT))
4019e8d8bef9SDimitry Andric Diags.Report(diag::err_drv_incompatible_omp_arch)
4020e8d8bef9SDimitry Andric << A->getValue(i) << T.str();
40210b57cec5SDimitry Andric else
40220b57cec5SDimitry Andric Opts.OMPTargetTriples.push_back(TT);
40230b57cec5SDimitry Andric }
40240b57cec5SDimitry Andric }
40250b57cec5SDimitry Andric
40260b57cec5SDimitry Andric // Get OpenMP host file path if any and report if a non existent file is
40270b57cec5SDimitry Andric // found
40280b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
40290b57cec5SDimitry Andric Opts.OMPHostIRFile = A->getValue();
40300b57cec5SDimitry Andric if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
40310b57cec5SDimitry Andric Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
40320b57cec5SDimitry Andric << Opts.OMPHostIRFile;
40330b57cec5SDimitry Andric }
40340b57cec5SDimitry Andric
40355ffd83dbSDimitry Andric // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
4036fe013be4SDimitry Andric Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice &&
4037fe013be4SDimitry Andric (T.isNVPTX() || T.isAMDGCN()) &&
40380b57cec5SDimitry Andric Args.hasArg(options::OPT_fopenmp_cuda_mode);
40390b57cec5SDimitry Andric
4040c9157d92SDimitry Andric // OpenACC Configuration.
4041c9157d92SDimitry Andric if (Args.hasArg(options::OPT_fopenacc)) {
4042c9157d92SDimitry Andric Opts.OpenACC = true;
4043c9157d92SDimitry Andric
4044c9157d92SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override))
4045c9157d92SDimitry Andric Opts.OpenACCMacroOverride = A->getValue();
4046c9157d92SDimitry Andric }
4047c9157d92SDimitry Andric
40480b57cec5SDimitry Andric // FIXME: Eliminate this dependency.
40490b57cec5SDimitry Andric unsigned Opt = getOptimizationLevel(Args, IK, Diags),
40500b57cec5SDimitry Andric OptSize = getOptimizationLevelSize(Args);
40510b57cec5SDimitry Andric Opts.Optimize = Opt != 0;
40520b57cec5SDimitry Andric Opts.OptimizeSize = OptSize != 0;
40530b57cec5SDimitry Andric
40540b57cec5SDimitry Andric // This is the __NO_INLINE__ define, which just depends on things like the
40550b57cec5SDimitry Andric // optimization level and -fno-inline, not actually whether the backend has
40560b57cec5SDimitry Andric // inlining enabled.
40570b57cec5SDimitry Andric Opts.NoInlineDefine = !Opts.Optimize;
40580b57cec5SDimitry Andric if (Arg *InlineArg = Args.getLastArg(
40590b57cec5SDimitry Andric options::OPT_finline_functions, options::OPT_finline_hint_functions,
40600b57cec5SDimitry Andric options::OPT_fno_inline_functions, options::OPT_fno_inline))
40610b57cec5SDimitry Andric if (InlineArg->getOption().matches(options::OPT_fno_inline))
40620b57cec5SDimitry Andric Opts.NoInlineDefine = true;
40630b57cec5SDimitry Andric
40640b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
40650b57cec5SDimitry Andric StringRef Val = A->getValue();
40660b57cec5SDimitry Andric if (Val == "fast")
40675ffd83dbSDimitry Andric Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
40680b57cec5SDimitry Andric else if (Val == "on")
40695ffd83dbSDimitry Andric Opts.setDefaultFPContractMode(LangOptions::FPM_On);
40700b57cec5SDimitry Andric else if (Val == "off")
40715ffd83dbSDimitry Andric Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
4072e8d8bef9SDimitry Andric else if (Val == "fast-honor-pragmas")
4073e8d8bef9SDimitry Andric Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
40740b57cec5SDimitry Andric else
40750b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
40760b57cec5SDimitry Andric }
40770b57cec5SDimitry Andric
40780b57cec5SDimitry Andric // Parse -fsanitize= arguments.
40790b57cec5SDimitry Andric parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
40800b57cec5SDimitry Andric Diags, Opts.Sanitize);
4081fe6060f1SDimitry Andric Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
4082fe6060f1SDimitry Andric std::vector<std::string> systemIgnorelists =
4083fe6060f1SDimitry Andric Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
4084fe6060f1SDimitry Andric Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
4085fe6060f1SDimitry Andric systemIgnorelists.begin(),
4086fe6060f1SDimitry Andric systemIgnorelists.end());
40870b57cec5SDimitry Andric
40880b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
40890b57cec5SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Latest);
40900b57cec5SDimitry Andric
40910b57cec5SDimitry Andric StringRef Ver = A->getValue();
40920b57cec5SDimitry Andric std::pair<StringRef, StringRef> VerParts = Ver.split('.');
40930b57cec5SDimitry Andric unsigned Major, Minor = 0;
40940b57cec5SDimitry Andric
40950b57cec5SDimitry Andric // Check the version number is valid: either 3.x (0 <= x <= 9) or
40960b57cec5SDimitry Andric // y or y.0 (4 <= y <= current version).
4097c9157d92SDimitry Andric if (!VerParts.first.starts_with("0") &&
4098c9157d92SDimitry Andric !VerParts.first.getAsInteger(10, Major) && 3 <= Major &&
4099c9157d92SDimitry Andric Major <= CLANG_VERSION_MAJOR &&
4100c9157d92SDimitry Andric (Major == 3
4101c9157d92SDimitry Andric ? VerParts.second.size() == 1 &&
41020b57cec5SDimitry Andric !VerParts.second.getAsInteger(10, Minor)
4103c9157d92SDimitry Andric : VerParts.first.size() == Ver.size() || VerParts.second == "0")) {
41040b57cec5SDimitry Andric // Got a valid version number.
41050b57cec5SDimitry Andric if (Major == 3 && Minor <= 8)
41060b57cec5SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
41070b57cec5SDimitry Andric else if (Major <= 4)
41080b57cec5SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
41090b57cec5SDimitry Andric else if (Major <= 6)
41100b57cec5SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
41110b57cec5SDimitry Andric else if (Major <= 7)
41120b57cec5SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
4113a7dea167SDimitry Andric else if (Major <= 9)
4114a7dea167SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
4115e8d8bef9SDimitry Andric else if (Major <= 11)
4116e8d8bef9SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
4117fe6060f1SDimitry Andric else if (Major <= 12)
4118fe6060f1SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
411981ad6265SDimitry Andric else if (Major <= 14)
412081ad6265SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
4121bdd1243dSDimitry Andric else if (Major <= 15)
4122bdd1243dSDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver15);
4123c9157d92SDimitry Andric else if (Major <= 17)
4124c9157d92SDimitry Andric Opts.setClangABICompat(LangOptions::ClangABI::Ver17);
41250b57cec5SDimitry Andric } else if (Ver != "latest") {
41260b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
41270b57cec5SDimitry Andric << A->getAsString(Args) << A->getValue();
41280b57cec5SDimitry Andric }
41290b57cec5SDimitry Andric }
41300b57cec5SDimitry Andric
41315ffd83dbSDimitry Andric if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
41325ffd83dbSDimitry Andric StringRef SignScope = A->getValue();
41335ffd83dbSDimitry Andric
4134fe6060f1SDimitry Andric if (SignScope.equals_insensitive("none"))
41355ffd83dbSDimitry Andric Opts.setSignReturnAddressScope(
41365ffd83dbSDimitry Andric LangOptions::SignReturnAddressScopeKind::None);
4137fe6060f1SDimitry Andric else if (SignScope.equals_insensitive("all"))
41385ffd83dbSDimitry Andric Opts.setSignReturnAddressScope(
41395ffd83dbSDimitry Andric LangOptions::SignReturnAddressScopeKind::All);
4140fe6060f1SDimitry Andric else if (SignScope.equals_insensitive("non-leaf"))
41415ffd83dbSDimitry Andric Opts.setSignReturnAddressScope(
41425ffd83dbSDimitry Andric LangOptions::SignReturnAddressScopeKind::NonLeaf);
41435ffd83dbSDimitry Andric else
41445ffd83dbSDimitry Andric Diags.Report(diag::err_drv_invalid_value)
41455ffd83dbSDimitry Andric << A->getAsString(Args) << SignScope;
41465ffd83dbSDimitry Andric
41475ffd83dbSDimitry Andric if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
41485ffd83dbSDimitry Andric StringRef SignKey = A->getValue();
41495ffd83dbSDimitry Andric if (!SignScope.empty() && !SignKey.empty()) {
4150c9157d92SDimitry Andric if (SignKey == "a_key")
41515ffd83dbSDimitry Andric Opts.setSignReturnAddressKey(
41525ffd83dbSDimitry Andric LangOptions::SignReturnAddressKeyKind::AKey);
4153c9157d92SDimitry Andric else if (SignKey == "b_key")
41545ffd83dbSDimitry Andric Opts.setSignReturnAddressKey(
41555ffd83dbSDimitry Andric LangOptions::SignReturnAddressKeyKind::BKey);
41565ffd83dbSDimitry Andric else
41575ffd83dbSDimitry Andric Diags.Report(diag::err_drv_invalid_value)
41585ffd83dbSDimitry Andric << A->getAsString(Args) << SignKey;
41595ffd83dbSDimitry Andric }
41605ffd83dbSDimitry Andric }
41615ffd83dbSDimitry Andric }
41625ffd83dbSDimitry Andric
4163fe6060f1SDimitry Andric // The value can be empty, which indicates the system default should be used.
4164fe6060f1SDimitry Andric StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4165fe6060f1SDimitry Andric if (!CXXABI.empty()) {
4166fe6060f1SDimitry Andric if (!TargetCXXABI::isABI(CXXABI)) {
4167fe6060f1SDimitry Andric Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4168fe6060f1SDimitry Andric } else {
4169fe6060f1SDimitry Andric auto Kind = TargetCXXABI::getKind(CXXABI);
4170fe6060f1SDimitry Andric if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4171fe6060f1SDimitry Andric Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4172fe6060f1SDimitry Andric else
4173fe6060f1SDimitry Andric Opts.CXXABI = Kind;
4174fe6060f1SDimitry Andric }
4175fe6060f1SDimitry Andric }
4176fe6060f1SDimitry Andric
4177fe6060f1SDimitry Andric Opts.RelativeCXXABIVTables =
4178fe6060f1SDimitry Andric Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4179fe6060f1SDimitry Andric options::OPT_fno_experimental_relative_cxx_abi_vtables,
4180fe6060f1SDimitry Andric TargetCXXABI::usesRelativeVTables(T));
4181fe6060f1SDimitry Andric
4182c9157d92SDimitry Andric // RTTI is on by default.
4183c9157d92SDimitry Andric bool HasRTTI = !Args.hasArg(options::OPT_fno_rtti);
4184c9157d92SDimitry Andric Opts.OmitVTableRTTI =
4185c9157d92SDimitry Andric Args.hasFlag(options::OPT_fexperimental_omit_vtable_rtti,
4186c9157d92SDimitry Andric options::OPT_fno_experimental_omit_vtable_rtti, false);
4187c9157d92SDimitry Andric if (Opts.OmitVTableRTTI && HasRTTI)
4188c9157d92SDimitry Andric Diags.Report(diag::err_drv_using_omit_rtti_component_without_no_rtti);
4189c9157d92SDimitry Andric
41906e75b2fbSDimitry Andric for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
41916e75b2fbSDimitry Andric auto Split = StringRef(A).split('=');
41926e75b2fbSDimitry Andric Opts.MacroPrefixMap.insert(
41936e75b2fbSDimitry Andric {std::string(Split.first), std::string(Split.second)});
41946e75b2fbSDimitry Andric }
41956e75b2fbSDimitry Andric
419681ad6265SDimitry Andric Opts.UseTargetPathSeparator =
419781ad6265SDimitry Andric !Args.getLastArg(OPT_fno_file_reproducible) &&
419881ad6265SDimitry Andric (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
419981ad6265SDimitry Andric Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
420081ad6265SDimitry Andric Args.getLastArg(OPT_ffile_reproducible));
420181ad6265SDimitry Andric
42020eae32dcSDimitry Andric // Error if -mvscale-min is unbounded.
42030eae32dcSDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
42040eae32dcSDimitry Andric unsigned VScaleMin;
42050eae32dcSDimitry Andric if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
42060eae32dcSDimitry Andric Diags.Report(diag::err_cc1_unbounded_vscale_min);
42070eae32dcSDimitry Andric }
42080eae32dcSDimitry Andric
420981ad6265SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
421081ad6265SDimitry Andric std::ifstream SeedFile(A->getValue(0));
421181ad6265SDimitry Andric
421281ad6265SDimitry Andric if (!SeedFile.is_open())
421381ad6265SDimitry Andric Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
421481ad6265SDimitry Andric << A->getValue(0);
421581ad6265SDimitry Andric
421681ad6265SDimitry Andric std::getline(SeedFile, Opts.RandstructSeed);
421781ad6265SDimitry Andric }
421881ad6265SDimitry Andric
421981ad6265SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
422081ad6265SDimitry Andric Opts.RandstructSeed = A->getValue(0);
422181ad6265SDimitry Andric
4222bdd1243dSDimitry Andric // Validate options for HLSL
4223bdd1243dSDimitry Andric if (Opts.HLSL) {
4224c9157d92SDimitry Andric // TODO: Revisit restricting SPIR-V to logical once we've figured out how to
4225c9157d92SDimitry Andric // handle PhysicalStorageBuffer64 memory model
4226c9157d92SDimitry Andric if (T.isDXIL() || T.isSPIRVLogical()) {
4227*a58f00eaSDimitry Andric enum { ShaderModel, VulkanEnv, ShaderStage };
4228*a58f00eaSDimitry Andric enum { OS, Environment };
4229*a58f00eaSDimitry Andric
4230*a58f00eaSDimitry Andric int ExpectedOS = T.isSPIRVLogical() ? VulkanEnv : ShaderModel;
4231*a58f00eaSDimitry Andric
4232c9157d92SDimitry Andric if (T.getOSName().empty()) {
4233c9157d92SDimitry Andric Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4234*a58f00eaSDimitry Andric << ExpectedOS << OS << T.str();
4235c9157d92SDimitry Andric } else if (T.getEnvironmentName().empty()) {
4236c9157d92SDimitry Andric Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4237*a58f00eaSDimitry Andric << ShaderStage << Environment << T.str();
4238c9157d92SDimitry Andric } else if (!T.isShaderStageEnvironment()) {
4239c9157d92SDimitry Andric Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4240c9157d92SDimitry Andric << ShaderStage << T.getEnvironmentName() << T.str();
4241c9157d92SDimitry Andric }
4242*a58f00eaSDimitry Andric
4243*a58f00eaSDimitry Andric if (T.isDXIL()) {
4244*a58f00eaSDimitry Andric if (!T.isShaderModelOS() || T.getOSVersion() == VersionTuple(0)) {
4245*a58f00eaSDimitry Andric Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4246*a58f00eaSDimitry Andric << ShaderModel << T.getOSName() << T.str();
4247*a58f00eaSDimitry Andric }
4248*a58f00eaSDimitry Andric } else if (T.isSPIRVLogical()) {
4249*a58f00eaSDimitry Andric if (!T.isVulkanOS() || T.getVulkanVersion() == VersionTuple(0)) {
4250*a58f00eaSDimitry Andric Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4251*a58f00eaSDimitry Andric << VulkanEnv << T.getOSName() << T.str();
4252*a58f00eaSDimitry Andric }
4253*a58f00eaSDimitry Andric } else {
4254*a58f00eaSDimitry Andric llvm_unreachable("expected DXIL or SPIR-V target");
4255*a58f00eaSDimitry Andric }
4256c9157d92SDimitry Andric } else
4257bdd1243dSDimitry Andric Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
4258bdd1243dSDimitry Andric }
4259bdd1243dSDimitry Andric
4260fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
42610b57cec5SDimitry Andric }
42620b57cec5SDimitry Andric
isStrictlyPreprocessorAction(frontend::ActionKind Action)42630b57cec5SDimitry Andric static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
42640b57cec5SDimitry Andric switch (Action) {
42650b57cec5SDimitry Andric case frontend::ASTDeclList:
42660b57cec5SDimitry Andric case frontend::ASTDump:
42670b57cec5SDimitry Andric case frontend::ASTPrint:
42680b57cec5SDimitry Andric case frontend::ASTView:
42690b57cec5SDimitry Andric case frontend::EmitAssembly:
42700b57cec5SDimitry Andric case frontend::EmitBC:
42710b57cec5SDimitry Andric case frontend::EmitHTML:
42720b57cec5SDimitry Andric case frontend::EmitLLVM:
42730b57cec5SDimitry Andric case frontend::EmitLLVMOnly:
42740b57cec5SDimitry Andric case frontend::EmitCodeGenOnly:
42750b57cec5SDimitry Andric case frontend::EmitObj:
427604eeddc0SDimitry Andric case frontend::ExtractAPI:
42770b57cec5SDimitry Andric case frontend::FixIt:
42780b57cec5SDimitry Andric case frontend::GenerateModule:
42790b57cec5SDimitry Andric case frontend::GenerateModuleInterface:
428081ad6265SDimitry Andric case frontend::GenerateHeaderUnit:
42810b57cec5SDimitry Andric case frontend::GeneratePCH:
42825ffd83dbSDimitry Andric case frontend::GenerateInterfaceStubs:
42830b57cec5SDimitry Andric case frontend::ParseSyntaxOnly:
42840b57cec5SDimitry Andric case frontend::ModuleFileInfo:
42850b57cec5SDimitry Andric case frontend::VerifyPCH:
42860b57cec5SDimitry Andric case frontend::PluginAction:
42870b57cec5SDimitry Andric case frontend::RewriteObjC:
42880b57cec5SDimitry Andric case frontend::RewriteTest:
42890b57cec5SDimitry Andric case frontend::RunAnalysis:
42900b57cec5SDimitry Andric case frontend::TemplightDump:
42910b57cec5SDimitry Andric case frontend::MigrateSource:
42920b57cec5SDimitry Andric return false;
42930b57cec5SDimitry Andric
42940b57cec5SDimitry Andric case frontend::DumpCompilerOptions:
42950b57cec5SDimitry Andric case frontend::DumpRawTokens:
42960b57cec5SDimitry Andric case frontend::DumpTokens:
42970b57cec5SDimitry Andric case frontend::InitOnly:
42980b57cec5SDimitry Andric case frontend::PrintPreamble:
42990b57cec5SDimitry Andric case frontend::PrintPreprocessedInput:
43000b57cec5SDimitry Andric case frontend::RewriteMacros:
43010b57cec5SDimitry Andric case frontend::RunPreprocessorOnly:
43020b57cec5SDimitry Andric case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
43030b57cec5SDimitry Andric return true;
43040b57cec5SDimitry Andric }
43050b57cec5SDimitry Andric llvm_unreachable("invalid frontend action");
43060b57cec5SDimitry Andric }
43070b57cec5SDimitry Andric
GeneratePreprocessorArgs(const PreprocessorOptions & Opts,ArgumentConsumer Consumer,const LangOptions & LangOpts,const FrontendOptions & FrontendOpts,const CodeGenOptions & CodeGenOpts)4308c9157d92SDimitry Andric static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts,
4309c9157d92SDimitry Andric ArgumentConsumer Consumer,
4310fe6060f1SDimitry Andric const LangOptions &LangOpts,
4311fe6060f1SDimitry Andric const FrontendOptions &FrontendOpts,
4312fe6060f1SDimitry Andric const CodeGenOptions &CodeGenOpts) {
4313c9157d92SDimitry Andric const PreprocessorOptions *PreprocessorOpts = &Opts;
4314fe6060f1SDimitry Andric
4315fe013be4SDimitry Andric #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4316c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4317fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
4318fe6060f1SDimitry Andric #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4319fe6060f1SDimitry Andric
4320fe6060f1SDimitry Andric if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4321c9157d92SDimitry Andric GenerateArg(Consumer, OPT_pch_through_hdrstop_use);
4322fe6060f1SDimitry Andric
4323fe6060f1SDimitry Andric for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4324c9157d92SDimitry Andric GenerateArg(Consumer, OPT_error_on_deserialized_pch_decl, D);
4325fe6060f1SDimitry Andric
4326fe6060f1SDimitry Andric if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4327c9157d92SDimitry Andric GenerateArg(Consumer, OPT_preamble_bytes_EQ,
4328fe6060f1SDimitry Andric Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4329c9157d92SDimitry Andric (Opts.PrecompiledPreambleBytes.second ? "1" : "0"));
4330fe6060f1SDimitry Andric
4331fe6060f1SDimitry Andric for (const auto &M : Opts.Macros) {
4332fe6060f1SDimitry Andric // Don't generate __CET__ macro definitions. They are implied by the
4333fe6060f1SDimitry Andric // -fcf-protection option that is generated elsewhere.
4334fe6060f1SDimitry Andric if (M.first == "__CET__=1" && !M.second &&
4335fe6060f1SDimitry Andric !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4336fe6060f1SDimitry Andric continue;
4337fe6060f1SDimitry Andric if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4338fe6060f1SDimitry Andric !CodeGenOpts.CFProtectionBranch)
4339fe6060f1SDimitry Andric continue;
4340fe6060f1SDimitry Andric if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4341fe6060f1SDimitry Andric CodeGenOpts.CFProtectionBranch)
4342fe6060f1SDimitry Andric continue;
4343fe6060f1SDimitry Andric
4344c9157d92SDimitry Andric GenerateArg(Consumer, M.second ? OPT_U : OPT_D, M.first);
4345fe6060f1SDimitry Andric }
4346fe6060f1SDimitry Andric
4347fe6060f1SDimitry Andric for (const auto &I : Opts.Includes) {
4348fe6060f1SDimitry Andric // Don't generate OpenCL includes. They are implied by other flags that are
4349fe6060f1SDimitry Andric // generated elsewhere.
4350fe6060f1SDimitry Andric if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4351fe6060f1SDimitry Andric ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4352fe6060f1SDimitry Andric I == "opencl-c.h"))
4353fe6060f1SDimitry Andric continue;
435481ad6265SDimitry Andric // Don't generate HLSL includes. They are implied by other flags that are
435581ad6265SDimitry Andric // generated elsewhere.
435681ad6265SDimitry Andric if (LangOpts.HLSL && I == "hlsl.h")
435781ad6265SDimitry Andric continue;
4358fe6060f1SDimitry Andric
4359c9157d92SDimitry Andric GenerateArg(Consumer, OPT_include, I);
4360fe6060f1SDimitry Andric }
4361fe6060f1SDimitry Andric
4362fe6060f1SDimitry Andric for (const auto &CI : Opts.ChainedIncludes)
4363c9157d92SDimitry Andric GenerateArg(Consumer, OPT_chain_include, CI);
4364fe6060f1SDimitry Andric
4365fe6060f1SDimitry Andric for (const auto &RF : Opts.RemappedFiles)
4366c9157d92SDimitry Andric GenerateArg(Consumer, OPT_remap_file, RF.first + ";" + RF.second);
4367fe6060f1SDimitry Andric
4368bdd1243dSDimitry Andric if (Opts.SourceDateEpoch)
4369c9157d92SDimitry Andric GenerateArg(Consumer, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch));
4370c9157d92SDimitry Andric
4371c9157d92SDimitry Andric if (Opts.DefineTargetOSMacros)
4372c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdefine_target_os_macros);
4373bdd1243dSDimitry Andric
4374fe6060f1SDimitry Andric // Don't handle LexEditorPlaceholders. It is implied by the action that is
4375fe6060f1SDimitry Andric // generated elsewhere.
4376fe6060f1SDimitry Andric }
4377fe6060f1SDimitry Andric
ParsePreprocessorArgs(PreprocessorOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action,const FrontendOptions & FrontendOpts)4378fe6060f1SDimitry Andric static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
43790b57cec5SDimitry Andric DiagnosticsEngine &Diags,
4380fe6060f1SDimitry Andric frontend::ActionKind Action,
4381fe6060f1SDimitry Andric const FrontendOptions &FrontendOpts) {
4382fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
4383fe6060f1SDimitry Andric
4384fe6060f1SDimitry Andric PreprocessorOptions *PreprocessorOpts = &Opts;
4385fe6060f1SDimitry Andric
4386fe013be4SDimitry Andric #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4387fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4388fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
4389fe6060f1SDimitry Andric #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4390fe6060f1SDimitry Andric
43910b57cec5SDimitry Andric Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
43920b57cec5SDimitry Andric Args.hasArg(OPT_pch_through_hdrstop_use);
43930b57cec5SDimitry Andric
43940b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
43950b57cec5SDimitry Andric Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
43960b57cec5SDimitry Andric
43970b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
43980b57cec5SDimitry Andric StringRef Value(A->getValue());
43990b57cec5SDimitry Andric size_t Comma = Value.find(',');
44000b57cec5SDimitry Andric unsigned Bytes = 0;
44010b57cec5SDimitry Andric unsigned EndOfLine = 0;
44020b57cec5SDimitry Andric
44030b57cec5SDimitry Andric if (Comma == StringRef::npos ||
44040b57cec5SDimitry Andric Value.substr(0, Comma).getAsInteger(10, Bytes) ||
44050b57cec5SDimitry Andric Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
44060b57cec5SDimitry Andric Diags.Report(diag::err_drv_preamble_format);
44070b57cec5SDimitry Andric else {
44080b57cec5SDimitry Andric Opts.PrecompiledPreambleBytes.first = Bytes;
44090b57cec5SDimitry Andric Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
44100b57cec5SDimitry Andric }
44110b57cec5SDimitry Andric }
44120b57cec5SDimitry Andric
44130b57cec5SDimitry Andric // Add the __CET__ macro if a CFProtection option is set.
44140b57cec5SDimitry Andric if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
44150b57cec5SDimitry Andric StringRef Name = A->getValue();
44160b57cec5SDimitry Andric if (Name == "branch")
44170b57cec5SDimitry Andric Opts.addMacroDef("__CET__=1");
44180b57cec5SDimitry Andric else if (Name == "return")
44190b57cec5SDimitry Andric Opts.addMacroDef("__CET__=2");
44200b57cec5SDimitry Andric else if (Name == "full")
44210b57cec5SDimitry Andric Opts.addMacroDef("__CET__=3");
44220b57cec5SDimitry Andric }
44230b57cec5SDimitry Andric
44240b57cec5SDimitry Andric // Add macros from the command line.
44250b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
44260b57cec5SDimitry Andric if (A->getOption().matches(OPT_D))
44270b57cec5SDimitry Andric Opts.addMacroDef(A->getValue());
44280b57cec5SDimitry Andric else
44290b57cec5SDimitry Andric Opts.addMacroUndef(A->getValue());
44300b57cec5SDimitry Andric }
44310b57cec5SDimitry Andric
44320b57cec5SDimitry Andric // Add the ordered list of -includes.
44330b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_include))
44340b57cec5SDimitry Andric Opts.Includes.emplace_back(A->getValue());
44350b57cec5SDimitry Andric
44360b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_chain_include))
44370b57cec5SDimitry Andric Opts.ChainedIncludes.emplace_back(A->getValue());
44380b57cec5SDimitry Andric
44390b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_remap_file)) {
44400b57cec5SDimitry Andric std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
44410b57cec5SDimitry Andric
44420b57cec5SDimitry Andric if (Split.second.empty()) {
44430b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
44440b57cec5SDimitry Andric continue;
44450b57cec5SDimitry Andric }
44460b57cec5SDimitry Andric
44470b57cec5SDimitry Andric Opts.addRemappedFile(Split.first, Split.second);
44480b57cec5SDimitry Andric }
44490b57cec5SDimitry Andric
4450bdd1243dSDimitry Andric if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
4451bdd1243dSDimitry Andric StringRef Epoch = A->getValue();
4452bdd1243dSDimitry Andric // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
4453bdd1243dSDimitry Andric // On time64 systems, pick 253402300799 (the UNIX timestamp of
4454bdd1243dSDimitry Andric // 9999-12-31T23:59:59Z) as the upper bound.
4455bdd1243dSDimitry Andric const uint64_t MaxTimestamp =
4456bdd1243dSDimitry Andric std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799);
4457bdd1243dSDimitry Andric uint64_t V;
4458bdd1243dSDimitry Andric if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) {
4459bdd1243dSDimitry Andric Diags.Report(diag::err_fe_invalid_source_date_epoch)
4460bdd1243dSDimitry Andric << Epoch << MaxTimestamp;
4461bdd1243dSDimitry Andric } else {
4462bdd1243dSDimitry Andric Opts.SourceDateEpoch = V;
4463bdd1243dSDimitry Andric }
4464bdd1243dSDimitry Andric }
4465bdd1243dSDimitry Andric
44660b57cec5SDimitry Andric // Always avoid lexing editor placeholders when we're just running the
44670b57cec5SDimitry Andric // preprocessor as we never want to emit the
44680b57cec5SDimitry Andric // "editor placeholder in source file" error in PP only mode.
44690b57cec5SDimitry Andric if (isStrictlyPreprocessorAction(Action))
44700b57cec5SDimitry Andric Opts.LexEditorPlaceholders = false;
4471fe6060f1SDimitry Andric
4472c9157d92SDimitry Andric Opts.DefineTargetOSMacros =
4473c9157d92SDimitry Andric Args.hasFlag(OPT_fdefine_target_os_macros,
4474c9157d92SDimitry Andric OPT_fno_define_target_os_macros, Opts.DefineTargetOSMacros);
4475c9157d92SDimitry Andric
4476fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
44770b57cec5SDimitry Andric }
44780b57cec5SDimitry Andric
4479c9157d92SDimitry Andric static void
GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions & Opts,ArgumentConsumer Consumer,frontend::ActionKind Action)4480c9157d92SDimitry Andric GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts,
4481c9157d92SDimitry Andric ArgumentConsumer Consumer,
4482c9157d92SDimitry Andric frontend::ActionKind Action) {
4483fe6060f1SDimitry Andric const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4484fe6060f1SDimitry Andric
4485fe013be4SDimitry Andric #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4486c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4487fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
4488fe6060f1SDimitry Andric #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4489fe6060f1SDimitry Andric
4490fe6060f1SDimitry Andric bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4491fe6060f1SDimitry Andric if (Generate_dM)
4492c9157d92SDimitry Andric GenerateArg(Consumer, OPT_dM);
4493fe6060f1SDimitry Andric if (!Generate_dM && Opts.ShowMacros)
4494c9157d92SDimitry Andric GenerateArg(Consumer, OPT_dD);
449581ad6265SDimitry Andric if (Opts.DirectivesOnly)
4496c9157d92SDimitry Andric GenerateArg(Consumer, OPT_fdirectives_only);
4497fe6060f1SDimitry Andric }
4498fe6060f1SDimitry Andric
ParsePreprocessorOutputArgs(PreprocessorOutputOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags,frontend::ActionKind Action)4499fe6060f1SDimitry Andric static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4500fe6060f1SDimitry Andric ArgList &Args, DiagnosticsEngine &Diags,
45010b57cec5SDimitry Andric frontend::ActionKind Action) {
4502fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
45030b57cec5SDimitry Andric
4504fe6060f1SDimitry Andric PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4505fe6060f1SDimitry Andric
4506fe013be4SDimitry Andric #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4507fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4508fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
4509fe6060f1SDimitry Andric #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4510fe6060f1SDimitry Andric
4511fe6060f1SDimitry Andric Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
45120b57cec5SDimitry Andric Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
451381ad6265SDimitry Andric Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
4514fe6060f1SDimitry Andric
4515fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
45160b57cec5SDimitry Andric }
45170b57cec5SDimitry Andric
GenerateTargetArgs(const TargetOptions & Opts,ArgumentConsumer Consumer)4518fe6060f1SDimitry Andric static void GenerateTargetArgs(const TargetOptions &Opts,
4519c9157d92SDimitry Andric ArgumentConsumer Consumer) {
4520fe6060f1SDimitry Andric const TargetOptions *TargetOpts = &Opts;
4521fe013be4SDimitry Andric #define TARGET_OPTION_WITH_MARSHALLING(...) \
4522c9157d92SDimitry Andric GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4523fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
4524fe6060f1SDimitry Andric #undef TARGET_OPTION_WITH_MARSHALLING
4525fe6060f1SDimitry Andric
4526fe6060f1SDimitry Andric if (!Opts.SDKVersion.empty())
4527c9157d92SDimitry Andric GenerateArg(Consumer, OPT_target_sdk_version_EQ,
4528c9157d92SDimitry Andric Opts.SDKVersion.getAsString());
452981ad6265SDimitry Andric if (!Opts.DarwinTargetVariantSDKVersion.empty())
4530c9157d92SDimitry Andric GenerateArg(Consumer, OPT_darwin_target_variant_sdk_version_EQ,
4531c9157d92SDimitry Andric Opts.DarwinTargetVariantSDKVersion.getAsString());
4532fe6060f1SDimitry Andric }
4533fe6060f1SDimitry Andric
ParseTargetArgs(TargetOptions & Opts,ArgList & Args,DiagnosticsEngine & Diags)4534fe6060f1SDimitry Andric static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
45350b57cec5SDimitry Andric DiagnosticsEngine &Diags) {
4536fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
4537fe6060f1SDimitry Andric
4538fe6060f1SDimitry Andric TargetOptions *TargetOpts = &Opts;
4539fe6060f1SDimitry Andric
4540fe013be4SDimitry Andric #define TARGET_OPTION_WITH_MARSHALLING(...) \
4541fe013be4SDimitry Andric PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4542fe6060f1SDimitry Andric #include "clang/Driver/Options.inc"
4543fe6060f1SDimitry Andric #undef TARGET_OPTION_WITH_MARSHALLING
4544fe6060f1SDimitry Andric
45450b57cec5SDimitry Andric if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
45460b57cec5SDimitry Andric llvm::VersionTuple Version;
45470b57cec5SDimitry Andric if (Version.tryParse(A->getValue()))
45480b57cec5SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
45490b57cec5SDimitry Andric << A->getAsString(Args) << A->getValue();
45500b57cec5SDimitry Andric else
45510b57cec5SDimitry Andric Opts.SDKVersion = Version;
45520b57cec5SDimitry Andric }
455381ad6265SDimitry Andric if (Arg *A =
455481ad6265SDimitry Andric Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
455581ad6265SDimitry Andric llvm::VersionTuple Version;
455681ad6265SDimitry Andric if (Version.tryParse(A->getValue()))
455781ad6265SDimitry Andric Diags.Report(diag::err_drv_invalid_value)
455881ad6265SDimitry Andric << A->getAsString(Args) << A->getValue();
455981ad6265SDimitry Andric else
456081ad6265SDimitry Andric Opts.DarwinTargetVariantSDKVersion = Version;
456181ad6265SDimitry Andric }
4562fe6060f1SDimitry Andric
4563fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
45640b57cec5SDimitry Andric }
45650b57cec5SDimitry Andric
CreateFromArgsImpl(CompilerInvocation & Res,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0)4566fe6060f1SDimitry Andric bool CompilerInvocation::CreateFromArgsImpl(
4567fe6060f1SDimitry Andric CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4568fe6060f1SDimitry Andric DiagnosticsEngine &Diags, const char *Argv0) {
4569fe6060f1SDimitry Andric unsigned NumErrorsBefore = Diags.getNumErrors();
45700b57cec5SDimitry Andric
45710b57cec5SDimitry Andric // Parse the arguments.
4572a7dea167SDimitry Andric const OptTable &Opts = getDriverOptTable();
4573c9157d92SDimitry Andric llvm::opt::Visibility VisibilityMask(options::CC1Option);
45740b57cec5SDimitry Andric unsigned MissingArgIndex, MissingArgCount;
4575a7dea167SDimitry Andric InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4576c9157d92SDimitry Andric MissingArgCount, VisibilityMask);
4577c9157d92SDimitry Andric LangOptions &LangOpts = Res.getLangOpts();
45780b57cec5SDimitry Andric
45790b57cec5SDimitry Andric // Check for missing argument error.
4580fe6060f1SDimitry Andric if (MissingArgCount)
45810b57cec5SDimitry Andric Diags.Report(diag::err_drv_missing_argument)
45820b57cec5SDimitry Andric << Args.getArgString(MissingArgIndex) << MissingArgCount;
45830b57cec5SDimitry Andric
45840b57cec5SDimitry Andric // Issue errors on unknown arguments.
45850b57cec5SDimitry Andric for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
45860b57cec5SDimitry Andric auto ArgString = A->getAsString(Args);
45870b57cec5SDimitry Andric std::string Nearest;
4588c9157d92SDimitry Andric if (Opts.findNearest(ArgString, Nearest, VisibilityMask) > 1)
45890b57cec5SDimitry Andric Diags.Report(diag::err_drv_unknown_argument) << ArgString;
45900b57cec5SDimitry Andric else
45910b57cec5SDimitry Andric Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
45920b57cec5SDimitry Andric << ArgString << Nearest;
45930b57cec5SDimitry Andric }
45940b57cec5SDimitry Andric
4595fe6060f1SDimitry Andric ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4596fe6060f1SDimitry Andric ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4597c9157d92SDimitry Andric ParseAnalyzerArgs(Res.getAnalyzerOpts(), Args, Diags);
4598fe6060f1SDimitry Andric ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
45995ffd83dbSDimitry Andric /*DefaultDiagColor=*/false);
4600fe6060f1SDimitry Andric ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
46010b57cec5SDimitry Andric // FIXME: We shouldn't have to pass the DashX option around here
4602fe6060f1SDimitry Andric InputKind DashX = Res.getFrontendOpts().DashX;
46030b57cec5SDimitry Andric ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4604e8d8bef9SDimitry Andric llvm::Triple T(Res.getTargetOpts().Triple);
4605fe6060f1SDimitry Andric ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
46060b57cec5SDimitry Andric Res.getFileSystemOpts().WorkingDir);
4607c9157d92SDimitry Andric ParseAPINotesArgs(Res.getAPINotesOpts(), Args, Diags);
4608fe6060f1SDimitry Andric
4609e8d8bef9SDimitry Andric ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4610e8d8bef9SDimitry Andric Diags);
46110b57cec5SDimitry Andric if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
46120b57cec5SDimitry Andric LangOpts.ObjCExceptions = 1;
46130b57cec5SDimitry Andric
461481ad6265SDimitry Andric for (auto Warning : Res.getDiagnosticOpts().Warnings) {
461581ad6265SDimitry Andric if (Warning == "misexpect" &&
461681ad6265SDimitry Andric !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
461781ad6265SDimitry Andric Res.getCodeGenOpts().MisExpect = true;
461881ad6265SDimitry Andric }
461981ad6265SDimitry Andric }
462081ad6265SDimitry Andric
46210b57cec5SDimitry Andric if (LangOpts.CUDA) {
46220b57cec5SDimitry Andric // During CUDA device-side compilation, the aux triple is the
46230b57cec5SDimitry Andric // triple used for host compilation.
46240b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice)
46250b57cec5SDimitry Andric Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
46260b57cec5SDimitry Andric }
46270b57cec5SDimitry Andric
46280b57cec5SDimitry Andric // Set the triple of the host for OpenMP device compile.
4629fe013be4SDimitry Andric if (LangOpts.OpenMPIsTargetDevice)
46300b57cec5SDimitry Andric Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
46310b57cec5SDimitry Andric
4632fe6060f1SDimitry Andric ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4633e8d8bef9SDimitry Andric Res.getFrontendOpts().OutputFile, LangOpts);
4634e8d8bef9SDimitry Andric
46350b57cec5SDimitry Andric // FIXME: Override value name discarding when asan or msan is used because the
46360b57cec5SDimitry Andric // backend passes depend on the name of the alloca in order to print out
46370b57cec5SDimitry Andric // names.
46380b57cec5SDimitry Andric Res.getCodeGenOpts().DiscardValueNames &=
46390b57cec5SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) &&
46400b57cec5SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
46410b57cec5SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
46420b57cec5SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
46430b57cec5SDimitry Andric
46440b57cec5SDimitry Andric ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4645fe6060f1SDimitry Andric Res.getFrontendOpts().ProgramAction,
4646fe6060f1SDimitry Andric Res.getFrontendOpts());
4647fe6060f1SDimitry Andric ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
46480b57cec5SDimitry Andric Res.getFrontendOpts().ProgramAction);
46490b57cec5SDimitry Andric
4650fe6060f1SDimitry Andric ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
4651fe6060f1SDimitry Andric Res.getFrontendOpts().ProgramAction,
4652fe6060f1SDimitry Andric Res.getPreprocessorOutputOpts().ShowLineMarkers);
4653fe6060f1SDimitry Andric if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4654fe6060f1SDimitry Andric Res.getDependencyOutputOpts().Targets.empty())
4655fe6060f1SDimitry Andric Diags.Report(diag::err_fe_dependency_file_requires_MT);
46560b57cec5SDimitry Andric
46570b57cec5SDimitry Andric // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
46580b57cec5SDimitry Andric if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4659c9157d92SDimitry Andric !Res.getLangOpts().Sanitize.empty()) {
46600b57cec5SDimitry Andric Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
46610b57cec5SDimitry Andric Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
46620b57cec5SDimitry Andric }
46635ffd83dbSDimitry Andric
46645ffd83dbSDimitry Andric // Store the command-line for using in the CodeView backend.
4665bdd1243dSDimitry Andric if (Res.getCodeGenOpts().CodeViewCommandLine) {
46665ffd83dbSDimitry Andric Res.getCodeGenOpts().Argv0 = Argv0;
46670eae32dcSDimitry Andric append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
4668bdd1243dSDimitry Andric }
46695ffd83dbSDimitry Andric
4670fe013be4SDimitry Andric // Set PGOOptions. Need to create a temporary VFS to read the profile
4671fe013be4SDimitry Andric // to determine the PGO type.
4672fe013be4SDimitry Andric if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty()) {
4673fe013be4SDimitry Andric auto FS =
4674fe013be4SDimitry Andric createVFSFromOverlayFiles(Res.getHeaderSearchOpts().VFSOverlayFiles,
4675fe013be4SDimitry Andric Diags, llvm::vfs::getRealFileSystem());
4676fe013be4SDimitry Andric setPGOUseInstrumentor(Res.getCodeGenOpts(),
4677fe013be4SDimitry Andric Res.getCodeGenOpts().ProfileInstrumentUsePath, *FS,
4678fe013be4SDimitry Andric Diags);
4679fe013be4SDimitry Andric }
4680fe013be4SDimitry Andric
4681e8d8bef9SDimitry Andric FixupInvocation(Res, Diags, Args, DashX);
4682e8d8bef9SDimitry Andric
4683fe6060f1SDimitry Andric return Diags.getNumErrors() == NumErrorsBefore;
4684fe6060f1SDimitry Andric }
4685fe6060f1SDimitry Andric
CreateFromArgs(CompilerInvocation & Invocation,ArrayRef<const char * > CommandLineArgs,DiagnosticsEngine & Diags,const char * Argv0)4686fe6060f1SDimitry Andric bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
4687fe6060f1SDimitry Andric ArrayRef<const char *> CommandLineArgs,
4688fe6060f1SDimitry Andric DiagnosticsEngine &Diags,
4689fe6060f1SDimitry Andric const char *Argv0) {
4690fe6060f1SDimitry Andric CompilerInvocation DummyInvocation;
4691fe6060f1SDimitry Andric
4692fe6060f1SDimitry Andric return RoundTrip(
4693fe6060f1SDimitry Andric [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4694fe6060f1SDimitry Andric DiagnosticsEngine &Diags, const char *Argv0) {
4695fe6060f1SDimitry Andric return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4696fe6060f1SDimitry Andric },
4697fe6060f1SDimitry Andric [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4698bdd1243dSDimitry Andric StringAllocator SA) {
4699bdd1243dSDimitry Andric Args.push_back("-cc1");
4700bdd1243dSDimitry Andric Invocation.generateCC1CommandLine(Args, SA);
4701bdd1243dSDimitry Andric },
4702fe6060f1SDimitry Andric Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
47030b57cec5SDimitry Andric }
47040b57cec5SDimitry Andric
getModuleHash() const47050b57cec5SDimitry Andric std::string CompilerInvocation::getModuleHash() const {
4706349cc55cSDimitry Andric // FIXME: Consider using SHA1 instead of MD5.
4707c9157d92SDimitry Andric llvm::HashBuilder<llvm::MD5, llvm::endianness::native> HBuilder;
4708349cc55cSDimitry Andric
47090b57cec5SDimitry Andric // Note: For QoI reasons, the things we use as a hash here should all be
47100b57cec5SDimitry Andric // dumped via the -module-info flag.
47110b57cec5SDimitry Andric
47120b57cec5SDimitry Andric // Start the signature with the compiler version.
4713349cc55cSDimitry Andric HBuilder.add(getClangFullRepositoryVersion());
47140b57cec5SDimitry Andric
47155ffd83dbSDimitry Andric // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
47165ffd83dbSDimitry Andric // and getClangFullRepositoryVersion() doesn't include git revision.
4717349cc55cSDimitry Andric HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR);
47185ffd83dbSDimitry Andric
47190b57cec5SDimitry Andric // Extend the signature with the language options
4720349cc55cSDimitry Andric #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
47210b57cec5SDimitry Andric #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4722349cc55cSDimitry Andric HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
47230b57cec5SDimitry Andric #define BENIGN_LANGOPT(Name, Bits, Default, Description)
47240b57cec5SDimitry Andric #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
47250b57cec5SDimitry Andric #include "clang/Basic/LangOptions.def"
47260b57cec5SDimitry Andric
4727c9157d92SDimitry Andric HBuilder.addRange(getLangOpts().ModuleFeatures);
47280b57cec5SDimitry Andric
4729c9157d92SDimitry Andric HBuilder.add(getLangOpts().ObjCRuntime);
4730c9157d92SDimitry Andric HBuilder.addRange(getLangOpts().CommentOpts.BlockCommandNames);
47315ffd83dbSDimitry Andric
47320b57cec5SDimitry Andric // Extend the signature with the target options.
4733c9157d92SDimitry Andric HBuilder.add(getTargetOpts().Triple, getTargetOpts().CPU,
4734c9157d92SDimitry Andric getTargetOpts().TuneCPU, getTargetOpts().ABI);
4735c9157d92SDimitry Andric HBuilder.addRange(getTargetOpts().FeaturesAsWritten);
47360b57cec5SDimitry Andric
47370b57cec5SDimitry Andric // Extend the signature with preprocessor options.
47380b57cec5SDimitry Andric const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4739349cc55cSDimitry Andric HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
47400b57cec5SDimitry Andric
4741349cc55cSDimitry Andric const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4742349cc55cSDimitry Andric for (const auto &Macro : getPreprocessorOpts().Macros) {
47430b57cec5SDimitry Andric // If we're supposed to ignore this macro for the purposes of modules,
47440b57cec5SDimitry Andric // don't put it into the hash.
47450b57cec5SDimitry Andric if (!hsOpts.ModulesIgnoreMacros.empty()) {
47460b57cec5SDimitry Andric // Check whether we're ignoring this macro.
4747349cc55cSDimitry Andric StringRef MacroDef = Macro.first;
47480b57cec5SDimitry Andric if (hsOpts.ModulesIgnoreMacros.count(
47490b57cec5SDimitry Andric llvm::CachedHashString(MacroDef.split('=').first)))
47500b57cec5SDimitry Andric continue;
47510b57cec5SDimitry Andric }
47520b57cec5SDimitry Andric
4753349cc55cSDimitry Andric HBuilder.add(Macro);
47540b57cec5SDimitry Andric }
47550b57cec5SDimitry Andric
47560b57cec5SDimitry Andric // Extend the signature with the sysroot and other header search options.
4757349cc55cSDimitry Andric HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
4758349cc55cSDimitry Andric hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes,
4759349cc55cSDimitry Andric hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
47600b57cec5SDimitry Andric hsOpts.ModulesValidateDiagnosticOptions);
4761349cc55cSDimitry Andric HBuilder.add(hsOpts.ResourceDir);
47620b57cec5SDimitry Andric
4763a7dea167SDimitry Andric if (hsOpts.ModulesStrictContextHash) {
4764349cc55cSDimitry Andric HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
4765349cc55cSDimitry Andric HBuilder.addRange(hsOpts.UserEntries);
4766a7dea167SDimitry Andric
4767a7dea167SDimitry Andric const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4768349cc55cSDimitry Andric #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
4769a7dea167SDimitry Andric #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4770349cc55cSDimitry Andric HBuilder.add(diagOpts.get##Name());
4771a7dea167SDimitry Andric #include "clang/Basic/DiagnosticOptions.def"
4772a7dea167SDimitry Andric #undef DIAGOPT
4773a7dea167SDimitry Andric #undef ENUM_DIAGOPT
4774a7dea167SDimitry Andric }
4775a7dea167SDimitry Andric
47760b57cec5SDimitry Andric // Extend the signature with the user build path.
4777349cc55cSDimitry Andric HBuilder.add(hsOpts.ModuleUserBuildPath);
47780b57cec5SDimitry Andric
47790b57cec5SDimitry Andric // Extend the signature with the module file extensions.
4780349cc55cSDimitry Andric for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
4781349cc55cSDimitry Andric ext->hashExtension(HBuilder);
47820b57cec5SDimitry Andric
4783c9157d92SDimitry Andric // Extend the signature with the Swift version for API notes.
4784c9157d92SDimitry Andric const APINotesOptions &APINotesOpts = getAPINotesOpts();
4785c9157d92SDimitry Andric if (!APINotesOpts.SwiftVersion.empty()) {
4786c9157d92SDimitry Andric HBuilder.add(APINotesOpts.SwiftVersion.getMajor());
4787c9157d92SDimitry Andric if (auto Minor = APINotesOpts.SwiftVersion.getMinor())
4788c9157d92SDimitry Andric HBuilder.add(*Minor);
4789c9157d92SDimitry Andric if (auto Subminor = APINotesOpts.SwiftVersion.getSubminor())
4790c9157d92SDimitry Andric HBuilder.add(*Subminor);
4791c9157d92SDimitry Andric if (auto Build = APINotesOpts.SwiftVersion.getBuild())
4792c9157d92SDimitry Andric HBuilder.add(*Build);
4793c9157d92SDimitry Andric }
4794c9157d92SDimitry Andric
47950b57cec5SDimitry Andric // When compiling with -gmodules, also hash -fdebug-prefix-map as it
47960b57cec5SDimitry Andric // affects the debug info in the PCM.
47970b57cec5SDimitry Andric if (getCodeGenOpts().DebugTypeExtRefs)
4798349cc55cSDimitry Andric HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
47990b57cec5SDimitry Andric
4800c9157d92SDimitry Andric // Extend the signature with the affecting debug options.
4801c9157d92SDimitry Andric if (getHeaderSearchOpts().ModuleFormat == "obj") {
4802c9157d92SDimitry Andric #define DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
4803c9157d92SDimitry Andric #define VALUE_DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
4804c9157d92SDimitry Andric #define ENUM_DEBUGOPT(Name, Type, Bits, Default) \
4805c9157d92SDimitry Andric HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
4806c9157d92SDimitry Andric #define BENIGN_DEBUGOPT(Name, Bits, Default)
4807c9157d92SDimitry Andric #define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default)
4808c9157d92SDimitry Andric #define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default)
4809c9157d92SDimitry Andric #include "clang/Basic/DebugOptions.def"
4810c9157d92SDimitry Andric }
4811c9157d92SDimitry Andric
48120b57cec5SDimitry Andric // Extend the signature with the enabled sanitizers, if at least one is
48130b57cec5SDimitry Andric // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4814c9157d92SDimitry Andric SanitizerSet SanHash = getLangOpts().Sanitize;
48150b57cec5SDimitry Andric SanHash.clear(getPPTransparentSanitizers());
48160b57cec5SDimitry Andric if (!SanHash.empty())
4817349cc55cSDimitry Andric HBuilder.add(SanHash.Mask);
48180b57cec5SDimitry Andric
4819349cc55cSDimitry Andric llvm::MD5::MD5Result Result;
4820349cc55cSDimitry Andric HBuilder.getHasher().final(Result);
4821349cc55cSDimitry Andric uint64_t Hash = Result.high() ^ Result.low();
4822349cc55cSDimitry Andric return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
48230b57cec5SDimitry Andric }
48240b57cec5SDimitry Andric
generateCC1CommandLine(ArgumentConsumer Consumer) const4825c9157d92SDimitry Andric void CompilerInvocationBase::generateCC1CommandLine(
4826c9157d92SDimitry Andric ArgumentConsumer Consumer) const {
4827c9157d92SDimitry Andric llvm::Triple T(getTargetOpts().Triple);
48285ffd83dbSDimitry Andric
4829c9157d92SDimitry Andric GenerateFileSystemArgs(getFileSystemOpts(), Consumer);
4830c9157d92SDimitry Andric GenerateMigratorArgs(getMigratorOpts(), Consumer);
4831c9157d92SDimitry Andric GenerateAnalyzerArgs(getAnalyzerOpts(), Consumer);
4832c9157d92SDimitry Andric GenerateDiagnosticArgs(getDiagnosticOpts(), Consumer,
4833c9157d92SDimitry Andric /*DefaultDiagColor=*/false);
4834c9157d92SDimitry Andric GenerateFrontendArgs(getFrontendOpts(), Consumer, getLangOpts().IsHeaderFile);
4835c9157d92SDimitry Andric GenerateTargetArgs(getTargetOpts(), Consumer);
4836c9157d92SDimitry Andric GenerateHeaderSearchArgs(getHeaderSearchOpts(), Consumer);
4837c9157d92SDimitry Andric GenerateAPINotesArgs(getAPINotesOpts(), Consumer);
4838c9157d92SDimitry Andric GenerateLangArgs(getLangOpts(), Consumer, T, getFrontendOpts().DashX);
4839c9157d92SDimitry Andric GenerateCodeGenArgs(getCodeGenOpts(), Consumer, T,
4840c9157d92SDimitry Andric getFrontendOpts().OutputFile, &getLangOpts());
4841c9157d92SDimitry Andric GeneratePreprocessorArgs(getPreprocessorOpts(), Consumer, getLangOpts(),
4842c9157d92SDimitry Andric getFrontendOpts(), getCodeGenOpts());
4843c9157d92SDimitry Andric GeneratePreprocessorOutputArgs(getPreprocessorOutputOpts(), Consumer,
4844c9157d92SDimitry Andric getFrontendOpts().ProgramAction);
4845c9157d92SDimitry Andric GenerateDependencyOutputArgs(getDependencyOutputOpts(), Consumer);
48465ffd83dbSDimitry Andric }
48475ffd83dbSDimitry Andric
getCC1CommandLine() const4848c9157d92SDimitry Andric std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const {
4849c9157d92SDimitry Andric std::vector<std::string> Args{"-cc1"};
4850c9157d92SDimitry Andric generateCC1CommandLine(
4851c9157d92SDimitry Andric [&Args](const Twine &Arg) { Args.push_back(Arg.str()); });
4852c9157d92SDimitry Andric return Args;
4853bdd1243dSDimitry Andric }
4854bdd1243dSDimitry Andric
resetNonModularOptions()4855bdd1243dSDimitry Andric void CompilerInvocation::resetNonModularOptions() {
4856c9157d92SDimitry Andric getLangOpts().resetNonModularOptions();
4857bdd1243dSDimitry Andric getPreprocessorOpts().resetNonModularOptions();
4858c9157d92SDimitry Andric getCodeGenOpts().resetNonModularOptions(getHeaderSearchOpts().ModuleFormat);
4859bdd1243dSDimitry Andric }
4860bdd1243dSDimitry Andric
clearImplicitModuleBuildOptions()4861bdd1243dSDimitry Andric void CompilerInvocation::clearImplicitModuleBuildOptions() {
4862c9157d92SDimitry Andric getLangOpts().ImplicitModules = false;
4863bdd1243dSDimitry Andric getHeaderSearchOpts().ImplicitModuleMaps = false;
4864bdd1243dSDimitry Andric getHeaderSearchOpts().ModuleCachePath.clear();
4865bdd1243dSDimitry Andric getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
4866bdd1243dSDimitry Andric getHeaderSearchOpts().BuildSessionTimestamp = 0;
4867bdd1243dSDimitry Andric // The specific values we canonicalize to for pruning don't affect behaviour,
4868bdd1243dSDimitry Andric /// so use the default values so they may be dropped from the command-line.
4869bdd1243dSDimitry Andric getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
4870bdd1243dSDimitry Andric getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
4871bdd1243dSDimitry Andric }
4872bdd1243dSDimitry Andric
48730b57cec5SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags)4874e8d8bef9SDimitry Andric clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
48750b57cec5SDimitry Andric DiagnosticsEngine &Diags) {
48760b57cec5SDimitry Andric return createVFSFromCompilerInvocation(CI, Diags,
48770b57cec5SDimitry Andric llvm::vfs::getRealFileSystem());
48780b57cec5SDimitry Andric }
48790b57cec5SDimitry Andric
4880e8d8bef9SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation & CI,DiagnosticsEngine & Diags,IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)4881e8d8bef9SDimitry Andric clang::createVFSFromCompilerInvocation(
48820b57cec5SDimitry Andric const CompilerInvocation &CI, DiagnosticsEngine &Diags,
48830b57cec5SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4884bdd1243dSDimitry Andric return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles,
4885bdd1243dSDimitry Andric Diags, std::move(BaseFS));
4886bdd1243dSDimitry Andric }
4887bdd1243dSDimitry Andric
createVFSFromOverlayFiles(ArrayRef<std::string> VFSOverlayFiles,DiagnosticsEngine & Diags,IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)4888bdd1243dSDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles(
4889bdd1243dSDimitry Andric ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags,
4890bdd1243dSDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4891bdd1243dSDimitry Andric if (VFSOverlayFiles.empty())
48920b57cec5SDimitry Andric return BaseFS;
48930b57cec5SDimitry Andric
48940b57cec5SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
48950b57cec5SDimitry Andric // earlier vfs files are on the bottom
4896bdd1243dSDimitry Andric for (const auto &File : VFSOverlayFiles) {
48970b57cec5SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
48980b57cec5SDimitry Andric Result->getBufferForFile(File);
48990b57cec5SDimitry Andric if (!Buffer) {
49000b57cec5SDimitry Andric Diags.Report(diag::err_missing_vfs_overlay_file) << File;
49010b57cec5SDimitry Andric continue;
49020b57cec5SDimitry Andric }
49030b57cec5SDimitry Andric
49040b57cec5SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
49050b57cec5SDimitry Andric std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
49060b57cec5SDimitry Andric /*DiagContext*/ nullptr, Result);
49070b57cec5SDimitry Andric if (!FS) {
49080b57cec5SDimitry Andric Diags.Report(diag::err_invalid_vfs_overlay) << File;
49090b57cec5SDimitry Andric continue;
49100b57cec5SDimitry Andric }
49110b57cec5SDimitry Andric
49120b57cec5SDimitry Andric Result = FS;
49130b57cec5SDimitry Andric }
49140b57cec5SDimitry Andric return Result;
49150b57cec5SDimitry Andric }
4916