1//===--- CreateInvocationFromArgs.h - CompilerInvocation from Args --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Construct a compiler invocation object for command line driver arguments
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Driver/CreateInvocationFromArgs.h"
14#include "clang/Basic/DiagnosticFrontend.h"
15#include "clang/Basic/DiagnosticOptions.h"
16#include "clang/Driver/Compilation.h"
17#include "clang/Driver/Driver.h"
18#include "clang/Driver/Tool.h"
19#include "clang/Frontend/CompilerInstance.h"
20#include "clang/Frontend/Utils.h"
21#include "clang/Options/Options.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Option/ArgList.h"
25#include "llvm/Support/VirtualFileSystem.h"
26#include "llvm/TargetParser/Host.h"
27
28using namespace llvm::opt;
29
30namespace clang {
31
32std::unique_ptr<CompilerInvocation>
33createInvocation(ArrayRef<const char *> ArgList, CreateInvocationOptions Opts) {
34 assert(!ArgList.empty());
35 std::optional<DiagnosticOptions> LocalDiagOpts;
36 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
37 if (Opts.Diags) {
38 Diags = std::move(Opts.Diags);
39 } else {
40 LocalDiagOpts.emplace();
41 Diags = CompilerInstance::createDiagnostics(
42 VFS&: Opts.VFS ? *Opts.VFS : *llvm::vfs::getRealFileSystem(), Opts&: *LocalDiagOpts);
43 }
44
45 SmallVector<const char *, 16> Args(ArgList);
46
47 // FIXME: Find a cleaner way to force the driver into restricted modes.
48 Args.insert(
49 I: llvm::find_if(
50 Range&: Args, P: [](const char *Elem) { return llvm::StringRef(Elem) == "--"; }),
51 Elt: "-fsyntax-only");
52
53 // FIXME: We shouldn't have to pass in the path info.
54 driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), *Diags,
55 "clang LLVM compiler", Opts.VFS);
56
57 // Don't check that inputs exist, they may have been remapped.
58 TheDriver.setCheckInputsExist(false);
59 TheDriver.setProbePrecompiled(Opts.ProbePrecompiled);
60
61 std::unique_ptr<driver::Compilation> C(TheDriver.BuildCompilation(Args));
62 if (!C)
63 return nullptr;
64
65 if (C->getArgs().hasArg(Ids: options::OPT_fdriver_only))
66 return nullptr;
67
68 // Just print the cc1 options if -### was present.
69 if (C->getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH)) {
70 C->getJobs().Print(OS&: llvm::errs(), Terminator: "\n", Quote: true);
71 return nullptr;
72 }
73
74 // We expect to get back exactly one command job, if we didn't something
75 // failed. Offload compilation is an exception as it creates multiple jobs. If
76 // that's the case, we proceed with the first job. If caller needs a
77 // particular job, it should be controlled via options (e.g.
78 // --cuda-{host|device}-only for CUDA) passed to the driver.
79 const driver::JobList &Jobs = C->getJobs();
80 bool OffloadCompilation = false;
81 if (Jobs.size() > 1) {
82 for (auto &A : C->getActions()) {
83 // On MacOSX real actions may end up being wrapped in BindArchAction
84 if (isa<driver::BindArchAction>(Val: A))
85 A = *A->input_begin();
86 if (isa<driver::OffloadAction>(Val: A)) {
87 OffloadCompilation = true;
88 break;
89 }
90 }
91 }
92
93 bool PickFirstOfMany = OffloadCompilation || Opts.RecoverOnError;
94 if (Jobs.size() == 0 || (Jobs.size() > 1 && !PickFirstOfMany)) {
95 SmallString<256> Msg;
96 llvm::raw_svector_ostream OS(Msg);
97 Jobs.Print(OS, Terminator: "; ", Quote: true);
98 Diags->Report(DiagID: diag::err_fe_expected_compiler_job) << OS.str();
99 return nullptr;
100 }
101 auto Cmd = llvm::find_if(Range: Jobs, P: [](const driver::Command &Cmd) {
102 return StringRef(Cmd.getCreator().getName()) == "clang";
103 });
104 if (Cmd == Jobs.end()) {
105 Diags->Report(DiagID: diag::err_fe_expected_clang_command);
106 return nullptr;
107 }
108
109 const ArgStringList &CCArgs = Cmd->getArguments();
110 if (Opts.CC1Args)
111 *Opts.CC1Args = {CCArgs.begin(), CCArgs.end()};
112 auto CI = std::make_unique<CompilerInvocation>();
113 if (!CompilerInvocation::CreateFromArgs(Res&: *CI, CommandLineArgs: CCArgs, Diags&: *Diags, Argv0: Args[0]) &&
114 !Opts.RecoverOnError)
115 return nullptr;
116 return CI;
117}
118
119} // namespace clang
120