1//===-- clang-offload-bundler/ClangOffloadBundler.cpp ---------------------===//
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/// \file
10/// This file implements a stand-alone clang-offload-bundler tool using the
11/// OffloadBundler API.
12///
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/Cuda.h"
16#include "clang/Basic/TargetID.h"
17#include "clang/Basic/Version.h"
18#include "clang/Driver/OffloadBundler.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Object/Archive.h"
24#include "llvm/Object/ArchiveWriter.h"
25#include "llvm/Object/Binary.h"
26#include "llvm/Object/ObjectFile.h"
27#include "llvm/Support/Casting.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/Errc.h"
31#include "llvm/Support/Error.h"
32#include "llvm/Support/ErrorOr.h"
33#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/LibraryOptionsContext.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Program.h"
38#include "llvm/Support/Signals.h"
39#include "llvm/Support/StringSaver.h"
40#include "llvm/Support/WithColor.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/TargetParser/Host.h"
43#include "llvm/TargetParser/Triple.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <forward_list>
49#include <map>
50#include <memory>
51#include <set>
52#include <string>
53#include <system_error>
54#include <utility>
55
56using namespace llvm;
57using namespace llvm::object;
58using namespace clang;
59
60static void PrintVersion(raw_ostream &OS) {
61 OS << clang::getClangToolFullVersion(ToolName: "clang-offload-bundler") << '\n';
62}
63
64int main(int argc, const char **argv) {
65
66 // Mark all our options with this category, everything else (except for
67 // -version and -help) will be hidden.
68 cl::OptionCategory
69 ClangOffloadBundlerCategory("clang-offload-bundler options");
70 cl::list<std::string>
71 InputFileNames("input",
72 cl::desc("Input file."
73 " Can be specified multiple times "
74 "for multiple input files."),
75 cl::cat(ClangOffloadBundlerCategory));
76 cl::list<std::string>
77 InputFileNamesDeprecatedOpt("inputs", cl::CommaSeparated,
78 cl::desc("[<input file>,...] (deprecated)"),
79 cl::cat(ClangOffloadBundlerCategory));
80 cl::list<std::string>
81 OutputFileNames("output",
82 cl::desc("Output file."
83 " Can be specified multiple times "
84 "for multiple output files."),
85 cl::cat(ClangOffloadBundlerCategory));
86 cl::list<std::string>
87 OutputFileNamesDeprecatedOpt("outputs", cl::CommaSeparated,
88 cl::desc("[<output file>,...] (deprecated)"),
89 cl::cat(ClangOffloadBundlerCategory));
90 cl::list<std::string>
91 TargetNames("targets", cl::CommaSeparated,
92 cl::desc("[<offload kind>-<target triple>,...]"),
93 cl::cat(ClangOffloadBundlerCategory));
94 cl::opt<std::string> FilesType(
95 "type", cl::Required,
96 cl::desc("Type of the files to be bundled/unbundled.\n"
97 "Current supported types are:\n"
98 " i - cpp-output\n"
99 " ii - c++-cpp-output\n"
100 " cui - cuda-cpp-output\n"
101 " hipi - hip-cpp-output\n"
102 " d - dependency\n"
103 " ll - llvm\n"
104 " bc - llvm-bc\n"
105 " s - assembler\n"
106 " o - object\n"
107 " a - archive of objects\n"
108 " gch - precompiled-header\n"
109 " ast - clang AST file"),
110 cl::cat(ClangOffloadBundlerCategory));
111 cl::opt<bool>
112 Unbundle("unbundle",
113 cl::desc("Unbundle bundled file into several output files.\n"),
114 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
115 cl::opt<bool>
116 ListBundleIDs("list", cl::desc("List bundle IDs in the bundled file.\n"),
117 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
118 cl::opt<bool> PrintExternalCommands(
119 "###",
120 cl::desc("Print any external commands that are to be executed "
121 "instead of actually executing them - for testing purposes.\n"),
122 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
123 cl::opt<bool>
124 AllowMissingBundles("allow-missing-bundles",
125 cl::desc("Create empty files if bundles are missing "
126 "when unbundling.\n"),
127 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
128 cl::opt<unsigned>
129 BundleAlignment("bundle-align",
130 cl::desc("Alignment of bundle for binary files"),
131 cl::init(Val: 1), cl::cat(ClangOffloadBundlerCategory));
132 cl::opt<bool> CheckInputArchive(
133 "check-input-archive",
134 cl::desc("Check if input heterogeneous archive is "
135 "valid in terms of TargetID rules.\n"),
136 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
137 cl::opt<bool> HipOpenmpCompatible(
138 "hip-openmp-compatible",
139 cl::desc("Treat hip and hipv4 offload kinds as "
140 "compatible with openmp kind, and vice versa.\n"),
141 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
142 cl::opt<bool> Compress("compress",
143 cl::desc("Compress output file when bundling.\n"),
144 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
145 cl::opt<bool> Verbose("verbose", cl::desc("Print debug information.\n"),
146 cl::init(Val: false), cl::cat(ClangOffloadBundlerCategory));
147 cl::opt<int> CompressionLevel(
148 "compression-level", cl::desc("Specify the compression level (integer)"),
149 cl::value_desc("n"), cl::cat(ClangOffloadBundlerCategory));
150
151 // Process commandline options and report errors
152 sys::PrintStackTraceOnErrorSignal(Argv0: argv[0]);
153
154 cl::HideUnrelatedOptions(Category&: ClangOffloadBundlerCategory);
155 cl::SetVersionPrinter(PrintVersion);
156 cl::LibraryOptionsContext LibraryOptions;
157 cl::parseCommandLineOptions(
158 Context&: LibraryOptions, Args: ArrayRef(argv, argc),
159 Overview: "A tool to bundle several input files of the specified type <type> \n"
160 "referring to the same source file but different targets into a single \n"
161 "one. The resulting file can also be unbundled into different files by \n"
162 "this tool if -unbundle is provided.\n");
163
164 /// Class to store bundler options in standard (non-cl::opt) data structures
165 // Avoid using cl::opt variables after these assignments when possible
166 OffloadBundlerConfig BundlerConfig;
167 BundlerConfig.AllowMissingBundles = AllowMissingBundles;
168 BundlerConfig.CheckInputArchive = CheckInputArchive;
169 BundlerConfig.PrintExternalCommands = PrintExternalCommands;
170 BundlerConfig.HipOpenmpCompatible = HipOpenmpCompatible;
171 BundlerConfig.BundleAlignment = BundleAlignment;
172 BundlerConfig.FilesType = FilesType;
173 BundlerConfig.ObjcopyPath = "";
174 // Do not override the default value Compress and Verbose in BundlerConfig.
175 if (Compress.getNumOccurrences() > 0)
176 BundlerConfig.Compress = Compress;
177 if (Verbose.getNumOccurrences() > 0)
178 BundlerConfig.Verbose = Verbose;
179 if (CompressionLevel.getNumOccurrences() > 0)
180 BundlerConfig.CompressionLevel = CompressionLevel;
181
182 BundlerConfig.TargetNames.assign(in_start: TargetNames.begin(), in_end: TargetNames.end());
183 BundlerConfig.InputFileNames.assign(in_start: InputFileNames.begin(),
184 in_end: InputFileNames.end());
185 BundlerConfig.OutputFileNames.assign(in_start: OutputFileNames.begin(),
186 in_end: OutputFileNames.end());
187
188 /// The index of the host input in the list of inputs.
189 BundlerConfig.HostInputIndex = ~0u;
190
191 /// Whether not having host target is allowed.
192 BundlerConfig.AllowNoHost = false;
193
194 auto reportError = [argv](Error E) {
195 logAllUnhandledErrors(E: std::move(E), OS&: WithColor::error(OS&: errs(), Prefix: argv[0]));
196 return 1;
197 };
198
199 auto doWork = [&](std::function<llvm::Error()> Work) {
200 if (llvm::Error Err = Work()) {
201 return reportError(std::move(Err));
202 }
203 return 0;
204 };
205
206 auto warningOS = [argv]() -> raw_ostream & {
207 return WithColor::warning(OS&: errs(), Prefix: StringRef(argv[0]));
208 };
209
210 /// Path to the current binary.
211 std::string BundlerExecutable = argv[0];
212
213 if (!llvm::sys::fs::exists(Path: BundlerExecutable))
214 BundlerExecutable =
215 sys::fs::getMainExecutable(argv0: argv[0], MainExecAddr: &BundlerExecutable);
216
217 // Find llvm-objcopy in order to create the bundle binary.
218 ErrorOr<std::string> Objcopy = sys::findProgramByName(
219 Name: "llvm-objcopy",
220 Paths: sys::path::parent_path(path: BundlerExecutable));
221 if (!Objcopy)
222 Objcopy = sys::findProgramByName(Name: "llvm-objcopy");
223 if (!Objcopy)
224 return reportError(createStringError(
225 EC: Objcopy.getError(), S: "unable to find 'llvm-objcopy' in path"));
226 else
227 BundlerConfig.ObjcopyPath = *Objcopy;
228
229 if (InputFileNames.getNumOccurrences() != 0 &&
230 InputFileNamesDeprecatedOpt.getNumOccurrences() != 0) {
231 return reportError(createStringError(
232 EC: errc::invalid_argument,
233 S: "-inputs and -input cannot be used together, use only -input instead"));
234 }
235
236 if (InputFileNamesDeprecatedOpt.size()) {
237 warningOS() << "-inputs is deprecated, use -input instead\n";
238 // temporary hack to support -inputs
239 std::vector<std::string> &s = InputFileNames;
240 s.insert(position: s.end(), first: InputFileNamesDeprecatedOpt.begin(),
241 last: InputFileNamesDeprecatedOpt.end());
242 }
243 BundlerConfig.InputFileNames.assign(in_start: InputFileNames.begin(),
244 in_end: InputFileNames.end());
245
246 if (OutputFileNames.getNumOccurrences() != 0 &&
247 OutputFileNamesDeprecatedOpt.getNumOccurrences() != 0) {
248 return reportError(createStringError(EC: errc::invalid_argument,
249 S: "-outputs and -output cannot be used "
250 "together, use only -output instead"));
251 }
252
253 if (OutputFileNamesDeprecatedOpt.size()) {
254 warningOS() << "-outputs is deprecated, use -output instead\n";
255 // temporary hack to support -outputs
256 std::vector<std::string> &s = OutputFileNames;
257 s.insert(position: s.end(), first: OutputFileNamesDeprecatedOpt.begin(),
258 last: OutputFileNamesDeprecatedOpt.end());
259 }
260 BundlerConfig.OutputFileNames.assign(in_start: OutputFileNames.begin(),
261 in_end: OutputFileNames.end());
262
263 if (ListBundleIDs) {
264 if (Unbundle) {
265 return reportError(
266 createStringError(EC: errc::invalid_argument,
267 S: "-unbundle and -list cannot be used together"));
268 }
269 if (InputFileNames.size() != 1) {
270 return reportError(createStringError(
271 EC: errc::invalid_argument, S: "only one input file supported for -list"));
272 }
273 if (OutputFileNames.size()) {
274 return reportError(createStringError(
275 EC: errc::invalid_argument, S: "-outputs option is invalid for -list"));
276 }
277 if (TargetNames.size()) {
278 return reportError(createStringError(
279 EC: errc::invalid_argument, S: "-targets option is invalid for -list"));
280 }
281
282 return doWork([&]() {
283 return OffloadBundler::ListBundleIDsInFile(InputFileName: InputFileNames.front(),
284 BundlerConfig);
285 });
286 }
287
288 if (BundlerConfig.CheckInputArchive) {
289 if (!Unbundle) {
290 return reportError(createStringError(
291 EC: errc::invalid_argument, S: "-check-input-archive cannot be used while "
292 "bundling"));
293 }
294 if (Unbundle && BundlerConfig.FilesType != "a") {
295 return reportError(createStringError(
296 EC: errc::invalid_argument, S: "-check-input-archive can only be used for "
297 "unbundling archives (-type=a)"));
298 }
299 }
300
301 if (OutputFileNames.size() == 0) {
302 return reportError(
303 createStringError(EC: errc::invalid_argument, S: "no output file specified!"));
304 }
305
306 if (TargetNames.getNumOccurrences() == 0) {
307 return reportError(createStringError(
308 EC: errc::invalid_argument,
309 S: "for the --targets option: must be specified at least once!"));
310 }
311
312 if (Unbundle) {
313 if (InputFileNames.size() != 1) {
314 return reportError(createStringError(
315 EC: errc::invalid_argument,
316 S: "only one input file supported in unbundling mode"));
317 }
318 if (OutputFileNames.size() != TargetNames.size()) {
319 return reportError(createStringError(
320 EC: errc::invalid_argument, S: "number of output files and targets should "
321 "match in unbundling mode"));
322 }
323 } else {
324 if (BundlerConfig.FilesType == "a") {
325 return reportError(createStringError(EC: errc::invalid_argument,
326 S: "Archive files are only supported "
327 "for unbundling"));
328 }
329 if (OutputFileNames.size() != 1) {
330 return reportError(
331 createStringError(EC: errc::invalid_argument,
332 S: "only one output file supported in bundling mode"));
333 }
334 if (InputFileNames.size() != TargetNames.size()) {
335 return reportError(createStringError(
336 EC: errc::invalid_argument,
337 S: "number of input files and targets should match in bundling mode"));
338 }
339 }
340
341 // Verify that the offload kinds and triples are known. We also check that we
342 // have exactly one host target.
343 unsigned Index = 0u;
344 unsigned HostTargetNum = 0u;
345 bool HIPOnly = true;
346 llvm::DenseSet<StringRef> ParsedTargets;
347 // Map {offload-kind}-{triple} to target IDs.
348 std::map<std::string, std::set<StringRef>> TargetIDs;
349 // Standardize target names to include env field
350 std::vector<std::string> StandardizedTargetNames;
351 for (StringRef Target : TargetNames) {
352 if (!ParsedTargets.insert(V: Target).second) {
353 return reportError(createStringError(
354 EC: errc::invalid_argument, S: "Duplicate targets are not allowed"));
355 }
356
357 if (!checkOffloadBundleID(Str: Target)) {
358 return reportError(createStringError(
359 EC: errc::invalid_argument,
360 S: "Targets need to follow the format '<offload kind>-<target triple>', "
361 "where '<target triple>' follows the format "
362 "'<kind>-<arch>-<vendor>-<os>-<env>[-<target id>[:target "
363 "features]]'."));
364 }
365
366 auto OffloadInfo = OffloadTargetInfo(Target, BundlerConfig);
367 bool KindIsValid = OffloadInfo.isOffloadKindValid();
368 bool TripleIsValid = OffloadInfo.isTripleValid();
369
370 StandardizedTargetNames.push_back(x: OffloadInfo.str());
371
372 if (!KindIsValid || !TripleIsValid) {
373 SmallVector<char, 128u> Buf;
374 raw_svector_ostream Msg(Buf);
375 Msg << "invalid target '" << Target << "'";
376 if (!KindIsValid)
377 Msg << ", unknown offloading kind '" << OffloadInfo.OffloadKind << "'";
378 if (!TripleIsValid)
379 Msg << ", unknown target triple '" << OffloadInfo.Triple.str() << "'";
380 return reportError(createStringError(EC: errc::invalid_argument, S: Msg.str()));
381 }
382
383 TargetIDs[OffloadInfo.OffloadKind.str() + "-" + OffloadInfo.Triple.str()]
384 .insert(x: OffloadInfo.TargetID);
385 if (KindIsValid && OffloadInfo.hasHostKind()) {
386 ++HostTargetNum;
387 // Save the index of the input that refers to the host.
388 BundlerConfig.HostInputIndex = Index;
389 }
390
391 if (OffloadInfo.OffloadKind != "hip" && OffloadInfo.OffloadKind != "hipv4")
392 HIPOnly = false;
393
394 ++Index;
395 }
396
397 BundlerConfig.TargetNames.assign(in_start: StandardizedTargetNames.begin(),
398 in_end: StandardizedTargetNames.end());
399
400 for (const auto &TargetID : TargetIDs) {
401 if (auto ConflictingTID =
402 clang::getConflictTargetIDCombination(TargetIDs: TargetID.second)) {
403 SmallVector<char, 128u> Buf;
404 raw_svector_ostream Msg(Buf);
405 Msg << "Cannot bundle inputs with conflicting targets: '"
406 << TargetID.first + "-" + ConflictingTID->first << "' and '"
407 << TargetID.first + "-" + ConflictingTID->second << "'";
408 return reportError(createStringError(EC: errc::invalid_argument, S: Msg.str()));
409 }
410 }
411
412 // HIP uses clang-offload-bundler to bundle device-only compilation results
413 // for multiple GPU archs, therefore allow no host target if all entries
414 // are for HIP.
415 BundlerConfig.AllowNoHost = HIPOnly;
416
417 // Host triple is not really needed for unbundling operation, so do not
418 // treat missing host triple as error if we do unbundling.
419 if ((Unbundle && HostTargetNum > 1) ||
420 (!Unbundle && HostTargetNum != 1 && !BundlerConfig.AllowNoHost)) {
421 return reportError(createStringError(
422 EC: errc::invalid_argument,
423 S: "expecting exactly one host target but got " + Twine(HostTargetNum)));
424 }
425
426 OffloadBundler Bundler(BundlerConfig);
427
428 return doWork([&]() {
429 if (Unbundle)
430 return (BundlerConfig.FilesType == "a") ? Bundler.UnbundleArchive()
431 : Bundler.UnbundleFiles();
432 return Bundler.BundleFiles();
433 });
434}
435