clang 23.0.0git
Compilation.h
Go to the documentation of this file.
1//===- Compilation.h - Compilation Task Data Structure ----------*- C++ -*-===//
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#ifndef LLVM_CLANG_DRIVER_COMPILATION_H
10#define LLVM_CLANG_DRIVER_COMPILATION_H
11
12#include "clang/Basic/LLVM.h"
13#include "clang/Driver/Action.h"
14#include "clang/Driver/Job.h"
15#include "clang/Driver/Util.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Option/Option.h"
20#include <cassert>
21#include <iterator>
22#include <map>
23#include <memory>
24#include <optional>
25#include <utility>
26#include <vector>
27
28namespace llvm {
29namespace opt {
30
31class DerivedArgList;
32class InputArgList;
33
34} // namespace opt
35} // namespace llvm
36
37namespace clang {
38namespace driver {
39
40class Driver;
41class ToolChain;
42
43/// Compilation - A set of tasks to perform for a single driver
44/// invocation.
46 /// The driver we were created by.
47 const Driver &TheDriver;
48
49 /// The default tool chain.
50 const ToolChain &DefaultToolChain;
51
52 /// A mask of all the programming models the host has to support in the
53 /// current compilation.
54 unsigned ActiveOffloadMask = 0;
55
56 /// Array with the toolchains of offloading host and devices in the order they
57 /// were requested by the user. We are preserving that order in case the code
58 /// generation needs to derive a programming-model-specific semantic out of
59 /// it.
60 std::multimap<Action::OffloadKind, const ToolChain *>
61 OrderedOffloadingToolchains;
62
63 /// The original (untranslated) input argument list.
64 llvm::opt::InputArgList *Args;
65
66 /// The driver translated arguments. Note that toolchains may perform their
67 /// own argument translation.
68 llvm::opt::DerivedArgList *TranslatedArgs;
69
70 /// The list of actions we've created via MakeAction. This is not accessible
71 /// to consumers; it's here just to manage ownership.
72 std::vector<std::unique_ptr<Action>> AllActions;
73
74 /// The list of actions. This is maintained and modified by consumers, via
75 /// getActions().
76 ActionList Actions;
77
78 /// The root list of jobs.
79 JobList Jobs;
80
81 /// Cache of translated arguments for a particular tool chain, bound
82 /// architecture, and device offload kind.
83 struct TCArgsKey final {
84 const ToolChain *TC = nullptr;
85 StringRef BoundArch;
86 Action::OffloadKind DeviceOffloadKind = Action::OFK_None;
87
88 TCArgsKey(const ToolChain *TC, StringRef BoundArch,
89 Action::OffloadKind DeviceOffloadKind)
90 : TC(TC), BoundArch(BoundArch), DeviceOffloadKind(DeviceOffloadKind) {}
91
92 bool operator<(const TCArgsKey &K) const {
93 return std::tie(TC, BoundArch, DeviceOffloadKind) <
94 std::tie(K.TC, K.BoundArch, K.DeviceOffloadKind);
95 }
96 };
97 std::map<TCArgsKey, llvm::opt::DerivedArgList *> TCArgs;
98
99 /// Temporary files which should be removed on exit.
100 llvm::opt::ArgStringList TempFiles;
101
102 /// Result files which should be removed on failure.
103 ArgStringMap ResultFiles;
104
105 /// Result files which are generated correctly on failure, and which should
106 /// only be removed if we crash.
107 ArgStringMap FailureResultFiles;
108
109 /// -ftime-trace result files.
110 ArgStringMap TimeTraceFiles;
111
112 /// Optional redirection for stdin, stdout, stderr.
113 std::vector<std::optional<StringRef>> Redirects;
114
115 /// Callback called after compilation job has been finished.
116 /// Arguments of the callback are the compilation job as an instance of
117 /// class Command and the exit status of the corresponding child process.
118 std::function<void(const Command &, int)> PostCallback;
119
120 /// Whether we're compiling for diagnostic purposes.
121 bool ForDiagnostics = false;
122
123 /// Whether an error during the parsing of the input args.
124 bool ContainsError;
125
126 /// Whether to keep temporary files regardless of -save-temps.
127 bool ForceKeepTempFiles = false;
128
129 /// The bound architecture currently being built, if any. Set around
130 /// ConstructJob calls so addCommand can stamp it onto each new Command.
131 StringRef CurrentBoundArch;
132
133public:
134 Compilation(const Driver &D, const ToolChain &DefaultToolChain,
135 llvm::opt::InputArgList *Args,
136 llvm::opt::DerivedArgList *TranslatedArgs, bool ContainsError);
137 ~Compilation();
138
139 const Driver &getDriver() const { return TheDriver; }
140
141 const ToolChain &getDefaultToolChain() const { return DefaultToolChain; }
142
144 return ActiveOffloadMask & Kind;
145 }
146
147 unsigned getActiveOffloadKinds() const { return ActiveOffloadMask; }
148
149 /// Iterator that visits device toolchains of a given kind.
151 const std::multimap<Action::OffloadKind,
156
157 template <Action::OffloadKind Kind>
159 return OrderedOffloadingToolchains.equal_range(Kind);
160 }
161
164 return OrderedOffloadingToolchains.equal_range(Kind);
165 }
166
167 /// Return true if an offloading tool chain of a given kind exists.
168 template <Action::OffloadKind Kind> bool hasOffloadToolChain() const {
169 return OrderedOffloadingToolchains.find(Kind) !=
170 OrderedOffloadingToolchains.end();
171 }
172
173 /// Return an offload toolchain of the provided kind. Only one is expected to
174 /// exist.
175 template <Action::OffloadKind Kind>
177 auto TCs = getOffloadToolChains<Kind>();
178
179 assert(TCs.first != TCs.second &&
180 "No tool chains of the selected kind exist!");
181 assert(std::next(TCs.first) == TCs.second &&
182 "More than one tool chain of the this kind exist.");
183 return TCs.first->second;
184 }
185
186 void addOffloadDeviceToolChain(const ToolChain *DeviceToolChain,
187 Action::OffloadKind OffloadKind) {
188 assert(OffloadKind != Action::OFK_Host && OffloadKind != Action::OFK_None &&
189 "This is not a device tool chain!");
190
191 // Update the host offload kind to also contain this kind.
192 ActiveOffloadMask |= OffloadKind;
193 OrderedOffloadingToolchains.insert(
194 std::make_pair(OffloadKind, DeviceToolChain));
195 }
196
197 const llvm::opt::InputArgList &getInputArgs() const { return *Args; }
198
199 const llvm::opt::DerivedArgList &getArgs() const { return *TranslatedArgs; }
200
201 llvm::opt::DerivedArgList &getArgs() { return *TranslatedArgs; }
202
203 ActionList &getActions() { return Actions; }
204 const ActionList &getActions() const { return Actions; }
205
206 /// Creates a new Action owned by this Compilation.
207 ///
208 /// The new Action is *not* added to the list returned by getActions().
209 template <typename T, typename... Args> T *MakeAction(Args &&... Arg) {
210 T *RawPtr = new T(std::forward<Args>(Arg)...);
211 AllActions.push_back(std::unique_ptr<Action>(RawPtr));
212 return RawPtr;
213 }
214
215 JobList &getJobs() { return Jobs; }
216 const JobList &getJobs() const { return Jobs; }
217
218 void addCommand(std::unique_ptr<Command> Cmd) {
219 Cmd->setBoundArch(CurrentBoundArch);
220 Jobs.addJob(std::move(Cmd));
221 }
222
223 StringRef getCurrentBoundArch() const { return CurrentBoundArch; }
224 void setCurrentBoundArch(StringRef Arch) { CurrentBoundArch = Arch; }
225
226 llvm::opt::ArgStringList &getTempFiles() { return TempFiles; }
227 const llvm::opt::ArgStringList &getTempFiles() const { return TempFiles; }
228
229 const ArgStringMap &getResultFiles() const { return ResultFiles; }
230
232 return FailureResultFiles;
233 }
234
235 /// Installs a handler that is executed when a compilation job is finished.
236 /// The arguments of the callback specify the compilation job as an instance
237 /// of class Command and the exit status of the child process executed that
238 /// job.
239 void setPostCallback(const std::function<void(const Command &, int)> &CB) {
240 PostCallback = CB;
241 }
242
243 /// Returns the sysroot path.
244 StringRef getSysRoot() const;
245
246 /// getArgsForToolChain - Return the derived argument list for the
247 /// tool chain \p TC (or the default tool chain, if TC is not specified).
248 /// If a device offloading kind is specified, a translation specific for that
249 /// kind is performed, if any.
250 ///
251 /// \param BoundArch - The bound architecture name, or 0.
252 /// \param DeviceOffloadKind - The offload device kind that should be used in
253 /// the translation, if any.
254 const llvm::opt::DerivedArgList &
255 getArgsForToolChain(const ToolChain *TC, StringRef BoundArch,
256 Action::OffloadKind DeviceOffloadKind);
257
258 /// addTempFile - Add a file to remove on exit, and returns its
259 /// argument.
260 const char *addTempFile(const char *Name) {
261 TempFiles.push_back(Name);
262 return Name;
263 }
264
265 /// addResultFile - Add a file to remove on failure, and returns its
266 /// argument.
267 const char *addResultFile(const char *Name, const JobAction *JA) {
268 ResultFiles[JA] = Name;
269 return Name;
270 }
271
272 /// addFailureResultFile - Add a file to remove if we crash, and returns its
273 /// argument.
274 const char *addFailureResultFile(const char *Name, const JobAction *JA) {
275 FailureResultFiles[JA] = Name;
276 return Name;
277 }
278
279 const char *getTimeTraceFile(const JobAction *JA) const {
280 return TimeTraceFiles.lookup(JA);
281 }
282 void addTimeTraceFile(const char *Name, const JobAction *JA) {
283 assert(!TimeTraceFiles.contains(JA));
284 TimeTraceFiles[JA] = Name;
285 }
286
287 /// CleanupFile - Delete a given file.
288 ///
289 /// \param IssueErrors - Report failures as errors.
290 /// \return Whether the file was removed successfully.
291 bool CleanupFile(const char *File, bool IssueErrors = false) const;
292
293 /// CleanupFileList - Remove the files in the given list.
294 ///
295 /// \param IssueErrors - Report failures as errors.
296 /// \return Whether all files were removed successfully.
297 bool CleanupFileList(const llvm::opt::ArgStringList &Files,
298 bool IssueErrors = false) const;
299
300 /// CleanupFileMap - Remove the files in the given map.
301 ///
302 /// \param JA - If specified, only delete the files associated with this
303 /// JobAction. Otherwise, delete all files in the map.
304 /// \param IssueErrors - Report failures as errors.
305 /// \return Whether all files were removed successfully.
306 bool CleanupFileMap(const ArgStringMap &Files,
307 const JobAction *JA,
308 bool IssueErrors = false) const;
309
310 /// ExecuteCommand - Execute an actual command.
311 ///
312 /// \param FailingCommand - For non-zero results, this will be set to the
313 /// Command which failed, if any.
314 /// \param LogOnly - When true, only tries to log the command, not actually
315 /// execute it.
316 /// \return The result code of the subprocess.
317 int ExecuteCommand(const Command &C, const Command *&FailingCommand,
318 bool LogOnly = false) const;
319
320 /// ExecuteJob - Execute a single job.
321 ///
322 /// \param FailingCommands - For non-zero results, this will be a vector of
323 /// failing commands and their associated result code.
324 /// \param LogOnly - When true, only tries to log the command, not actually
325 /// execute it.
326 void
327 ExecuteJobs(const JobList &Jobs,
328 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands,
329 bool LogOnly = false) const;
330
331 /// initCompilationForDiagnostics - Remove stale state and suppress output
332 /// so compilation can be reexecuted to generate additional diagnostic
333 /// information (e.g., preprocessed source(s)).
335
336 /// Return true if we're compiling for diagnostics.
337 bool isForDiagnostics() const { return ForDiagnostics; }
338
339 /// Return whether an error during the parsing of the input args.
340 bool containsError() const { return ContainsError; }
341
342 /// Force driver to fail before toolchain is created. This is necessary when
343 /// error happens in action builder.
344 void setContainsError() { ContainsError = true; }
345
346 /// Redirect - Redirect output of this compilation. Can only be done once.
347 ///
348 /// \param Redirects - array of optional paths. The array should have a size
349 /// of three. The inferior process's stdin(0), stdout(1), and stderr(2) will
350 /// be redirected to the corresponding paths, if provided (not std::nullopt).
351 void Redirect(ArrayRef<std::optional<StringRef>> Redirects);
352};
353
354} // namespace driver
355} // namespace clang
356
357#endif // LLVM_CLANG_DRIVER_COMPILATION_H
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Command - An executable path/name and argument vector to execute.
Definition Job.h:106
void addCommand(std::unique_ptr< Command > Cmd)
bool hasOffloadToolChain() const
Return true if an offloading tool chain of a given kind exists.
const llvm::opt::DerivedArgList & getArgsForToolChain(const ToolChain *TC, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind)
getArgsForToolChain - Return the derived argument list for the tool chain TC (or the default tool cha...
const JobList & getJobs() const
int ExecuteCommand(const Command &C, const Command *&FailingCommand, bool LogOnly=false) const
ExecuteCommand - Execute an actual command.
llvm::opt::ArgStringList & getTempFiles()
bool CleanupFileMap(const ArgStringMap &Files, const JobAction *JA, bool IssueErrors=false) const
CleanupFileMap - Remove the files in the given map.
std::pair< const_offload_toolchains_iterator, const_offload_toolchains_iterator > const_offload_toolchains_range
const ActionList & getActions() const
void setPostCallback(const std::function< void(const Command &, int)> &CB)
Installs a handler that is executed when a compilation job is finished.
void setCurrentBoundArch(StringRef Arch)
StringRef getCurrentBoundArch() const
const_offload_toolchains_range getOffloadToolChains(Action::OffloadKind Kind) const
bool CleanupFile(const char *File, bool IssueErrors=false) const
CleanupFile - Delete a given file.
const ArgStringMap & getFailureResultFiles() const
llvm::opt::DerivedArgList & getArgs()
const char * getTimeTraceFile(const JobAction *JA) const
unsigned isOffloadingHostKind(Action::OffloadKind Kind) const
Compilation(const Driver &D, const ToolChain &DefaultToolChain, llvm::opt::InputArgList *Args, llvm::opt::DerivedArgList *TranslatedArgs, bool ContainsError)
T * MakeAction(Args &&... Arg)
Creates a new Action owned by this Compilation.
bool CleanupFileList(const llvm::opt::ArgStringList &Files, bool IssueErrors=false) const
CleanupFileList - Remove the files in the given list.
const ArgStringMap & getResultFiles() const
StringRef getSysRoot() const
Returns the sysroot path.
void setContainsError()
Force driver to fail before toolchain is created.
const_offload_toolchains_range getOffloadToolChains() const
const std::multimap< Action::OffloadKind, const ToolChain * >::const_iterator const_offload_toolchains_iterator
Iterator that visits device toolchains of a given kind.
unsigned getActiveOffloadKinds() const
const char * addFailureResultFile(const char *Name, const JobAction *JA)
addFailureResultFile - Add a file to remove if we crash, and returns its argument.
void Redirect(ArrayRef< std::optional< StringRef > > Redirects)
Redirect - Redirect output of this compilation.
const ToolChain & getDefaultToolChain() const
const char * addResultFile(const char *Name, const JobAction *JA)
addResultFile - Add a file to remove on failure, and returns its argument.
void addOffloadDeviceToolChain(const ToolChain *DeviceToolChain, Action::OffloadKind OffloadKind)
void initCompilationForDiagnostics()
initCompilationForDiagnostics - Remove stale state and suppress output so compilation can be reexecut...
const char * addTempFile(const char *Name)
addTempFile - Add a file to remove on exit, and returns its argument.
const llvm::opt::InputArgList & getInputArgs() const
const llvm::opt::ArgStringList & getTempFiles() const
void addTimeTraceFile(const char *Name, const JobAction *JA)
const llvm::opt::DerivedArgList & getArgs() const
void ExecuteJobs(const JobList &Jobs, SmallVectorImpl< std::pair< int, const Command * > > &FailingCommands, bool LogOnly=false) const
ExecuteJob - Execute a single job.
bool containsError() const
Return whether an error during the parsing of the input args.
bool isForDiagnostics() const
Return true if we're compiling for diagnostics.
const ToolChain * getSingleOffloadToolChain() const
Return an offload toolchain of the provided kind.
const Driver & getDriver() const
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:99
JobList - A sequence of jobs to perform.
Definition Job.h:268
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:93
SmallVector< Action *, 3 > ActionList
ActionList - Type used for lists of actions.
Definition Util.h:25
llvm::DenseMap< const JobAction *, const char * > ArgStringMap
ArgStringMap - Type used to map a JobAction to its result file.
Definition Util.h:22
The JSON file list parser is used to communicate input to InstallAPI.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31