1//===-- BareMetal.cpp - Bare Metal ToolChain --------------------*- 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#include "BareMetal.h"
10
11#include "CommonArgs.h"
12#include "Gnu.h"
13#include "clang/Driver/InputInfo.h"
14
15#include "Arch/ARM.h"
16#include "Arch/RISCV.h"
17#include "clang/Driver/Compilation.h"
18#include "clang/Driver/Driver.h"
19#include "clang/Driver/DriverDiagnostic.h"
20#include "clang/Driver/MultilibBuilder.h"
21#include "clang/Driver/Options.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Support/Path.h"
25#include "llvm/Support/VirtualFileSystem.h"
26#include "llvm/Support/raw_ostream.h"
27
28#include <sstream>
29
30using namespace llvm::opt;
31using namespace clang;
32using namespace clang::driver;
33using namespace clang::driver::tools;
34using namespace clang::driver::toolchains;
35
36static bool findRISCVMultilibs(const Driver &D,
37 const llvm::Triple &TargetTriple,
38 const ArgList &Args, DetectedMultilibs &Result) {
39 Multilib::flags_list Flags;
40 StringRef Arch = riscv::getRISCVArch(Args, Triple: TargetTriple);
41 StringRef Abi = tools::riscv::getRISCVABI(Args, Triple: TargetTriple);
42
43 if (TargetTriple.isRISCV64()) {
44 MultilibBuilder Imac =
45 MultilibBuilder().flag(Flag: "-march=rv64imac").flag(Flag: "-mabi=lp64");
46 MultilibBuilder Imafdc = MultilibBuilder("/rv64imafdc/lp64d")
47 .flag(Flag: "-march=rv64imafdc")
48 .flag(Flag: "-mabi=lp64d");
49
50 // Multilib reuse
51 bool UseImafdc =
52 (Arch == "rv64imafdc") || (Arch == "rv64gc"); // gc => imafdc
53
54 addMultilibFlag(Enabled: (Arch == "rv64imac"), Flag: "-march=rv64imac", Flags);
55 addMultilibFlag(Enabled: UseImafdc, Flag: "-march=rv64imafdc", Flags);
56 addMultilibFlag(Enabled: Abi == "lp64", Flag: "-mabi=lp64", Flags);
57 addMultilibFlag(Enabled: Abi == "lp64d", Flag: "-mabi=lp64d", Flags);
58
59 Result.Multilibs =
60 MultilibSetBuilder().Either(M1: Imac, M2: Imafdc).makeMultilibSet();
61 return Result.Multilibs.select(Flags, Result.SelectedMultilibs);
62 }
63 if (TargetTriple.isRISCV32()) {
64 MultilibBuilder Imac =
65 MultilibBuilder().flag(Flag: "-march=rv32imac").flag(Flag: "-mabi=ilp32");
66 MultilibBuilder I = MultilibBuilder("/rv32i/ilp32")
67 .flag(Flag: "-march=rv32i")
68 .flag(Flag: "-mabi=ilp32");
69 MultilibBuilder Im = MultilibBuilder("/rv32im/ilp32")
70 .flag(Flag: "-march=rv32im")
71 .flag(Flag: "-mabi=ilp32");
72 MultilibBuilder Iac = MultilibBuilder("/rv32iac/ilp32")
73 .flag(Flag: "-march=rv32iac")
74 .flag(Flag: "-mabi=ilp32");
75 MultilibBuilder Imafc = MultilibBuilder("/rv32imafc/ilp32f")
76 .flag(Flag: "-march=rv32imafc")
77 .flag(Flag: "-mabi=ilp32f");
78
79 // Multilib reuse
80 bool UseI = (Arch == "rv32i") || (Arch == "rv32ic"); // ic => i
81 bool UseIm = (Arch == "rv32im") || (Arch == "rv32imc"); // imc => im
82 bool UseImafc = (Arch == "rv32imafc") || (Arch == "rv32imafdc") ||
83 (Arch == "rv32gc"); // imafdc,gc => imafc
84
85 addMultilibFlag(Enabled: UseI, Flag: "-march=rv32i", Flags);
86 addMultilibFlag(Enabled: UseIm, Flag: "-march=rv32im", Flags);
87 addMultilibFlag(Enabled: (Arch == "rv32iac"), Flag: "-march=rv32iac", Flags);
88 addMultilibFlag(Enabled: (Arch == "rv32imac"), Flag: "-march=rv32imac", Flags);
89 addMultilibFlag(Enabled: UseImafc, Flag: "-march=rv32imafc", Flags);
90 addMultilibFlag(Enabled: Abi == "ilp32", Flag: "-mabi=ilp32", Flags);
91 addMultilibFlag(Enabled: Abi == "ilp32f", Flag: "-mabi=ilp32f", Flags);
92
93 Result.Multilibs =
94 MultilibSetBuilder().Either(M1: I, M2: Im, M3: Iac, M4: Imac, M5: Imafc).makeMultilibSet();
95 return Result.Multilibs.select(Flags, Result.SelectedMultilibs);
96 }
97 return false;
98}
99
100BareMetal::BareMetal(const Driver &D, const llvm::Triple &Triple,
101 const ArgList &Args)
102 : ToolChain(D, Triple, Args) {
103 getProgramPaths().push_back(Elt: getDriver().Dir);
104
105 findMultilibs(D, Triple, Args);
106 SmallString<128> SysRoot(computeSysRoot());
107 if (!SysRoot.empty()) {
108 for (const Multilib &M : getOrderedMultilibs()) {
109 SmallString<128> Dir(SysRoot);
110 llvm::sys::path::append(path&: Dir, a: M.osSuffix(), b: "lib");
111 getFilePaths().push_back(Elt: std::string(Dir));
112 getLibraryPaths().push_back(Elt: std::string(Dir));
113 }
114 }
115}
116
117/// Is the triple {arm,armeb,thumb,thumbeb}-none-none-{eabi,eabihf} ?
118static bool isARMBareMetal(const llvm::Triple &Triple) {
119 if (Triple.getArch() != llvm::Triple::arm &&
120 Triple.getArch() != llvm::Triple::thumb &&
121 Triple.getArch() != llvm::Triple::armeb &&
122 Triple.getArch() != llvm::Triple::thumbeb)
123 return false;
124
125 if (Triple.getVendor() != llvm::Triple::UnknownVendor)
126 return false;
127
128 if (Triple.getOS() != llvm::Triple::UnknownOS)
129 return false;
130
131 if (Triple.getEnvironment() != llvm::Triple::EABI &&
132 Triple.getEnvironment() != llvm::Triple::EABIHF)
133 return false;
134
135 return true;
136}
137
138/// Is the triple {aarch64.aarch64_be}-none-elf?
139static bool isAArch64BareMetal(const llvm::Triple &Triple) {
140 if (Triple.getArch() != llvm::Triple::aarch64 &&
141 Triple.getArch() != llvm::Triple::aarch64_be)
142 return false;
143
144 if (Triple.getVendor() != llvm::Triple::UnknownVendor)
145 return false;
146
147 if (Triple.getOS() != llvm::Triple::UnknownOS)
148 return false;
149
150 return Triple.getEnvironmentName() == "elf";
151}
152
153static bool isRISCVBareMetal(const llvm::Triple &Triple) {
154 if (!Triple.isRISCV())
155 return false;
156
157 if (Triple.getVendor() != llvm::Triple::UnknownVendor)
158 return false;
159
160 if (Triple.getOS() != llvm::Triple::UnknownOS)
161 return false;
162
163 return Triple.getEnvironmentName() == "elf";
164}
165
166/// Is the triple powerpc[64][le]-*-none-eabi?
167static bool isPPCBareMetal(const llvm::Triple &Triple) {
168 return Triple.isPPC() && Triple.getOS() == llvm::Triple::UnknownOS &&
169 Triple.getEnvironment() == llvm::Triple::EABI;
170}
171
172static void findMultilibsFromYAML(const ToolChain &TC, const Driver &D,
173 StringRef MultilibPath, const ArgList &Args,
174 DetectedMultilibs &Result) {
175 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB =
176 D.getVFS().getBufferForFile(Name: MultilibPath);
177 if (!MB)
178 return;
179 Multilib::flags_list Flags = TC.getMultilibFlags(Args);
180 llvm::ErrorOr<MultilibSet> ErrorOrMultilibSet =
181 MultilibSet::parseYaml(*MB.get());
182 if (ErrorOrMultilibSet.getError())
183 return;
184 Result.Multilibs = ErrorOrMultilibSet.get();
185 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs))
186 return;
187 D.Diag(clang::diag::DiagID: warn_drv_missing_multilib) << llvm::join(R&: Flags, Separator: " ");
188 std::stringstream ss;
189 for (const Multilib &Multilib : Result.Multilibs)
190 ss << "\n" << llvm::join(R: Multilib.flags(), Separator: " ");
191 D.Diag(clang::diag::DiagID: note_drv_available_multilibs) << ss.str();
192}
193
194static constexpr llvm::StringLiteral MultilibFilename = "multilib.yaml";
195
196// Get the sysroot, before multilib takes effect.
197static std::string computeBaseSysRoot(const Driver &D,
198 const llvm::Triple &Triple) {
199 if (!D.SysRoot.empty())
200 return D.SysRoot;
201
202 SmallString<128> SysRootDir(D.Dir);
203 llvm::sys::path::append(path&: SysRootDir, a: "..", b: "lib", c: "clang-runtimes");
204
205 SmallString<128> MultilibPath(SysRootDir);
206 llvm::sys::path::append(path&: MultilibPath, a: MultilibFilename);
207
208 // New behaviour: if multilib.yaml is found then use clang-runtimes as the
209 // sysroot.
210 if (D.getVFS().exists(Path: MultilibPath))
211 return std::string(SysRootDir);
212
213 // Otherwise fall back to the old behaviour of appending the target triple.
214 llvm::sys::path::append(path&: SysRootDir, a: D.getTargetTriple());
215 return std::string(SysRootDir);
216}
217
218void BareMetal::findMultilibs(const Driver &D, const llvm::Triple &Triple,
219 const ArgList &Args) {
220 DetectedMultilibs Result;
221 if (isRISCVBareMetal(Triple)) {
222 if (findRISCVMultilibs(D, TargetTriple: Triple, Args, Result)) {
223 SelectedMultilibs = Result.SelectedMultilibs;
224 Multilibs = Result.Multilibs;
225 }
226 } else {
227 llvm::SmallString<128> MultilibPath(computeBaseSysRoot(D, Triple));
228 llvm::sys::path::append(path&: MultilibPath, a: MultilibFilename);
229 findMultilibsFromYAML(TC: *this, D, MultilibPath, Args, Result);
230 SelectedMultilibs = Result.SelectedMultilibs;
231 Multilibs = Result.Multilibs;
232 }
233}
234
235bool BareMetal::handlesTarget(const llvm::Triple &Triple) {
236 return isARMBareMetal(Triple) || isAArch64BareMetal(Triple) ||
237 isRISCVBareMetal(Triple) || isPPCBareMetal(Triple);
238}
239
240Tool *BareMetal::buildLinker() const {
241 return new tools::baremetal::Linker(*this);
242}
243
244Tool *BareMetal::buildStaticLibTool() const {
245 return new tools::baremetal::StaticLibTool(*this);
246}
247
248std::string BareMetal::computeSysRoot() const {
249 return computeBaseSysRoot(D: getDriver(), Triple: getTriple());
250}
251
252BareMetal::OrderedMultilibs BareMetal::getOrderedMultilibs() const {
253 // Get multilibs in reverse order because they're ordered most-specific last.
254 if (!SelectedMultilibs.empty())
255 return llvm::reverse(C: SelectedMultilibs);
256
257 // No multilibs selected so return a single default multilib.
258 static const llvm::SmallVector<Multilib> Default = {Multilib()};
259 return llvm::reverse(C: Default);
260}
261
262void BareMetal::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
263 ArgStringList &CC1Args) const {
264 if (DriverArgs.hasArg(options::OPT_nostdinc))
265 return;
266
267 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
268 SmallString<128> Dir(getDriver().ResourceDir);
269 llvm::sys::path::append(path&: Dir, a: "include");
270 addSystemInclude(DriverArgs, CC1Args, Path: Dir.str());
271 }
272
273 if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) {
274 const SmallString<128> SysRoot(computeSysRoot());
275 if (!SysRoot.empty()) {
276 for (const Multilib &M : getOrderedMultilibs()) {
277 SmallString<128> Dir(SysRoot);
278 llvm::sys::path::append(path&: Dir, a: M.includeSuffix());
279 llvm::sys::path::append(path&: Dir, a: "include");
280 addSystemInclude(DriverArgs, CC1Args, Path: Dir.str());
281 }
282 }
283 }
284}
285
286void BareMetal::addClangTargetOptions(const ArgList &DriverArgs,
287 ArgStringList &CC1Args,
288 Action::OffloadKind) const {
289 CC1Args.push_back(Elt: "-nostdsysteminc");
290}
291
292void BareMetal::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
293 ArgStringList &CC1Args) const {
294 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
295 options::OPT_nostdincxx))
296 return;
297
298 const Driver &D = getDriver();
299 std::string SysRoot(computeSysRoot());
300 if (SysRoot.empty())
301 return;
302
303 for (const Multilib &M : getOrderedMultilibs()) {
304 SmallString<128> Dir(SysRoot);
305 llvm::sys::path::append(path&: Dir, a: M.gccSuffix());
306 switch (GetCXXStdlibType(Args: DriverArgs)) {
307 case ToolChain::CST_Libcxx: {
308 // First check sysroot/usr/include/c++/v1 if it exists.
309 SmallString<128> TargetDir(Dir);
310 llvm::sys::path::append(path&: TargetDir, a: "usr", b: "include", c: "c++", d: "v1");
311 if (D.getVFS().exists(Path: TargetDir)) {
312 addSystemInclude(DriverArgs, CC1Args, Path: TargetDir.str());
313 break;
314 }
315 // Add generic path if nothing else succeeded so far.
316 llvm::sys::path::append(path&: Dir, a: "include", b: "c++", c: "v1");
317 addSystemInclude(DriverArgs, CC1Args, Path: Dir.str());
318 break;
319 }
320 case ToolChain::CST_Libstdcxx: {
321 llvm::sys::path::append(path&: Dir, a: "include", b: "c++");
322 std::error_code EC;
323 Generic_GCC::GCCVersion Version = {.Text: "", .Major: -1, .Minor: -1, .Patch: -1, .MajorStr: "", .MinorStr: "", .PatchSuffix: ""};
324 // Walk the subdirs, and find the one with the newest gcc version:
325 for (llvm::vfs::directory_iterator
326 LI = D.getVFS().dir_begin(Dir: Dir.str(), EC),
327 LE;
328 !EC && LI != LE; LI = LI.increment(EC)) {
329 StringRef VersionText = llvm::sys::path::filename(path: LI->path());
330 auto CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText);
331 if (CandidateVersion.Major == -1)
332 continue;
333 if (CandidateVersion <= Version)
334 continue;
335 Version = CandidateVersion;
336 }
337 if (Version.Major != -1) {
338 llvm::sys::path::append(path&: Dir, a: Version.Text);
339 addSystemInclude(DriverArgs, CC1Args, Path: Dir.str());
340 }
341 break;
342 }
343 }
344 }
345}
346
347void BareMetal::AddCXXStdlibLibArgs(const ArgList &Args,
348 ArgStringList &CmdArgs) const {
349 switch (GetCXXStdlibType(Args)) {
350 case ToolChain::CST_Libcxx:
351 CmdArgs.push_back(Elt: "-lc++");
352 if (Args.hasArg(options::OPT_fexperimental_library))
353 CmdArgs.push_back(Elt: "-lc++experimental");
354 CmdArgs.push_back(Elt: "-lc++abi");
355 break;
356 case ToolChain::CST_Libstdcxx:
357 CmdArgs.push_back(Elt: "-lstdc++");
358 CmdArgs.push_back(Elt: "-lsupc++");
359 break;
360 }
361 CmdArgs.push_back(Elt: "-lunwind");
362}
363
364void BareMetal::AddLinkRuntimeLib(const ArgList &Args,
365 ArgStringList &CmdArgs) const {
366 ToolChain::RuntimeLibType RLT = GetRuntimeLibType(Args);
367 switch (RLT) {
368 case ToolChain::RLT_CompilerRT: {
369 CmdArgs.push_back(Elt: getCompilerRTArgString(Args, Component: "builtins"));
370 return;
371 }
372 case ToolChain::RLT_Libgcc:
373 CmdArgs.push_back(Elt: "-lgcc");
374 return;
375 }
376 llvm_unreachable("Unhandled RuntimeLibType.");
377}
378
379void baremetal::StaticLibTool::ConstructJob(Compilation &C, const JobAction &JA,
380 const InputInfo &Output,
381 const InputInfoList &Inputs,
382 const ArgList &Args,
383 const char *LinkingOutput) const {
384 const Driver &D = getToolChain().getDriver();
385
386 // Silence warning for "clang -g foo.o -o foo"
387 Args.ClaimAllArgs(options::OPT_g_Group);
388 // and "clang -emit-llvm foo.o -o foo"
389 Args.ClaimAllArgs(options::OPT_emit_llvm);
390 // and for "clang -w foo.o -o foo". Other warning options are already
391 // handled somewhere else.
392 Args.ClaimAllArgs(options::OPT_w);
393 // Silence warnings when linking C code with a C++ '-stdlib' argument.
394 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
395
396 // ar tool command "llvm-ar <options> <output_file> <input_files>".
397 ArgStringList CmdArgs;
398 // Create and insert file members with a deterministic index.
399 CmdArgs.push_back(Elt: "rcsD");
400 CmdArgs.push_back(Elt: Output.getFilename());
401
402 for (const auto &II : Inputs) {
403 if (II.isFilename()) {
404 CmdArgs.push_back(Elt: II.getFilename());
405 }
406 }
407
408 // Delete old output archive file if it already exists before generating a new
409 // archive file.
410 const char *OutputFileName = Output.getFilename();
411 if (Output.isFilename() && llvm::sys::fs::exists(Path: OutputFileName)) {
412 if (std::error_code EC = llvm::sys::fs::remove(path: OutputFileName)) {
413 D.Diag(diag::DiagID: err_drv_unable_to_remove_file) << EC.message();
414 return;
415 }
416 }
417
418 const char *Exec = Args.MakeArgString(Str: getToolChain().GetStaticLibToolPath());
419 C.addCommand(C: std::make_unique<Command>(args: JA, args: *this,
420 args: ResponseFileSupport::AtFileCurCP(),
421 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
422}
423
424void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA,
425 const InputInfo &Output,
426 const InputInfoList &Inputs,
427 const ArgList &Args,
428 const char *LinkingOutput) const {
429 ArgStringList CmdArgs;
430
431 auto &TC = static_cast<const toolchains::BareMetal &>(getToolChain());
432 const llvm::Triple::ArchType Arch = TC.getArch();
433 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
434
435 AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
436
437 CmdArgs.push_back(Elt: "-Bstatic");
438
439 if (TC.getTriple().isRISCV() && Args.hasArg(options::OPT_mno_relax))
440 CmdArgs.push_back(Elt: "--no-relax");
441
442 if (Triple.isARM() || Triple.isThumb()) {
443 bool IsBigEndian = arm::isARMBigEndian(Triple, Args);
444 if (IsBigEndian)
445 arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
446 CmdArgs.push_back(Elt: IsBigEndian ? "-EB" : "-EL");
447 } else if (Triple.isAArch64()) {
448 CmdArgs.push_back(Elt: Arch == llvm::Triple::aarch64_be ? "-EB" : "-EL");
449 }
450
451 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
452 options::OPT_s, options::OPT_t, options::OPT_r});
453
454 TC.AddFilePathLibArgs(Args, CmdArgs);
455
456 for (const auto &LibPath : TC.getLibraryPaths())
457 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::Twine("-L", LibPath)));
458
459 if (TC.ShouldLinkCXXStdlib(Args))
460 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
461
462 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
463 CmdArgs.push_back(Elt: "-lc");
464 CmdArgs.push_back(Elt: "-lm");
465
466 TC.AddLinkRuntimeLib(Args, CmdArgs);
467 }
468
469 if (TC.getTriple().isRISCV())
470 CmdArgs.push_back(Elt: "-X");
471
472 // The R_ARM_TARGET2 relocation must be treated as R_ARM_REL32 on arm*-*-elf
473 // and arm*-*-eabi (the default is R_ARM_GOT_PREL, used on arm*-*-linux and
474 // arm*-*-*bsd).
475 if (isARMBareMetal(Triple: TC.getTriple()))
476 CmdArgs.push_back(Elt: "--target2=rel");
477
478 CmdArgs.push_back(Elt: "-o");
479 CmdArgs.push_back(Elt: Output.getFilename());
480
481 C.addCommand(C: std::make_unique<Command>(
482 args: JA, args: *this, args: ResponseFileSupport::AtFileCurCP(),
483 args: Args.MakeArgString(Str: TC.GetLinkerPath()), args&: CmdArgs, args: Inputs, args: Output));
484}
485
486// BareMetal toolchain allows all sanitizers where the compiler generates valid
487// code, ignoring all runtime library support issues on the assumption that
488// baremetal targets typically implement their own runtime support.
489SanitizerMask BareMetal::getSupportedSanitizers() const {
490 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
491 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
492 getTriple().getArch() == llvm::Triple::aarch64_be;
493 const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
494 SanitizerMask Res = ToolChain::getSupportedSanitizers();
495 Res |= SanitizerKind::Address;
496 Res |= SanitizerKind::KernelAddress;
497 Res |= SanitizerKind::PointerCompare;
498 Res |= SanitizerKind::PointerSubtract;
499 Res |= SanitizerKind::Fuzzer;
500 Res |= SanitizerKind::FuzzerNoLink;
501 Res |= SanitizerKind::Vptr;
502 Res |= SanitizerKind::SafeStack;
503 Res |= SanitizerKind::Thread;
504 Res |= SanitizerKind::Scudo;
505 if (IsX86_64 || IsAArch64 || IsRISCV64) {
506 Res |= SanitizerKind::HWAddress;
507 Res |= SanitizerKind::KernelHWAddress;
508 }
509 return Res;
510}
511

source code of clang/lib/Driver/ToolChains/BareMetal.cpp