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 "InputInfo.h"
13 #include "Gnu.h"
14 
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "llvm/Option/ArgList.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/VirtualFileSystem.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace llvm::opt;
25 using namespace clang;
26 using namespace clang::driver;
27 using namespace clang::driver::tools;
28 using namespace clang::driver::toolchains;
29 
30 BareMetal::BareMetal(const Driver &D, const llvm::Triple &Triple,
31                            const ArgList &Args)
32     : ToolChain(D, Triple, Args) {
33   getProgramPaths().push_back(getDriver().getInstalledDir());
34   if (getDriver().getInstalledDir() != getDriver().Dir)
35     getProgramPaths().push_back(getDriver().Dir);
36 }
37 
38 /// Is the triple {arm,thumb}-none-none-{eabi,eabihf} ?
39 static bool isARMBareMetal(const llvm::Triple &Triple) {
40   if (Triple.getArch() != llvm::Triple::arm &&
41       Triple.getArch() != llvm::Triple::thumb)
42     return false;
43 
44   if (Triple.getVendor() != llvm::Triple::UnknownVendor)
45     return false;
46 
47   if (Triple.getOS() != llvm::Triple::UnknownOS)
48     return false;
49 
50   if (Triple.getEnvironment() != llvm::Triple::EABI &&
51       Triple.getEnvironment() != llvm::Triple::EABIHF)
52     return false;
53 
54   return true;
55 }
56 
57 bool BareMetal::handlesTarget(const llvm::Triple &Triple) {
58   return isARMBareMetal(Triple);
59 }
60 
61 Tool *BareMetal::buildLinker() const {
62   return new tools::baremetal::Linker(*this);
63 }
64 
65 std::string BareMetal::getCompilerRTPath() const { return getRuntimesDir(); }
66 
67 std::string BareMetal::getCompilerRTBasename(const llvm::opt::ArgList &,
68                                              StringRef, FileType, bool) const {
69   return ("libclang_rt.builtins-" + getTriple().getArchName() + ".a").str();
70 }
71 
72 std::string BareMetal::getRuntimesDir() const {
73   SmallString<128> Dir(getDriver().ResourceDir);
74   llvm::sys::path::append(Dir, "lib", "baremetal");
75   return std::string(Dir.str());
76 }
77 
78 void BareMetal::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
79                                           ArgStringList &CC1Args) const {
80   if (DriverArgs.hasArg(options::OPT_nostdinc))
81     return;
82 
83   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
84     SmallString<128> Dir(getDriver().ResourceDir);
85     llvm::sys::path::append(Dir, "include");
86     addSystemInclude(DriverArgs, CC1Args, Dir.str());
87   }
88 
89   if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) {
90     SmallString<128> Dir(getDriver().SysRoot);
91     llvm::sys::path::append(Dir, "include");
92     addSystemInclude(DriverArgs, CC1Args, Dir.str());
93   }
94 }
95 
96 void BareMetal::addClangTargetOptions(const ArgList &DriverArgs,
97                                       ArgStringList &CC1Args,
98                                       Action::OffloadKind) const {
99   CC1Args.push_back("-nostdsysteminc");
100 }
101 
102 void BareMetal::AddClangCXXStdlibIncludeArgs(
103     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
104   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
105       DriverArgs.hasArg(options::OPT_nostdlibinc) ||
106       DriverArgs.hasArg(options::OPT_nostdincxx))
107     return;
108 
109   StringRef SysRoot = getDriver().SysRoot;
110   if (SysRoot.empty())
111     return;
112 
113   switch (GetCXXStdlibType(DriverArgs)) {
114   case ToolChain::CST_Libcxx: {
115     SmallString<128> Dir(SysRoot);
116     llvm::sys::path::append(Dir, "include", "c++", "v1");
117     addSystemInclude(DriverArgs, CC1Args, Dir.str());
118     break;
119   }
120   case ToolChain::CST_Libstdcxx: {
121     SmallString<128> Dir(SysRoot);
122     llvm::sys::path::append(Dir, "include", "c++");
123     std::error_code EC;
124     Generic_GCC::GCCVersion Version = {"", -1, -1, -1, "", "", ""};
125     // Walk the subdirs, and find the one with the newest gcc version:
126     for (llvm::vfs::directory_iterator
127              LI = getDriver().getVFS().dir_begin(Dir.str(), EC),
128              LE;
129          !EC && LI != LE; LI = LI.increment(EC)) {
130       StringRef VersionText = llvm::sys::path::filename(LI->path());
131       auto CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText);
132       if (CandidateVersion.Major == -1)
133         continue;
134       if (CandidateVersion <= Version)
135         continue;
136       Version = CandidateVersion;
137     }
138     if (Version.Major == -1)
139       return;
140     llvm::sys::path::append(Dir, Version.Text);
141     addSystemInclude(DriverArgs, CC1Args, Dir.str());
142     break;
143   }
144   }
145 }
146 
147 void BareMetal::AddCXXStdlibLibArgs(const ArgList &Args,
148                                     ArgStringList &CmdArgs) const {
149   switch (GetCXXStdlibType(Args)) {
150   case ToolChain::CST_Libcxx:
151     CmdArgs.push_back("-lc++");
152     CmdArgs.push_back("-lc++abi");
153     break;
154   case ToolChain::CST_Libstdcxx:
155     CmdArgs.push_back("-lstdc++");
156     CmdArgs.push_back("-lsupc++");
157     break;
158   }
159   CmdArgs.push_back("-lunwind");
160 }
161 
162 void BareMetal::AddLinkRuntimeLib(const ArgList &Args,
163                                   ArgStringList &CmdArgs) const {
164   ToolChain::RuntimeLibType RLT = GetRuntimeLibType(Args);
165   switch (RLT) {
166   case ToolChain::RLT_CompilerRT:
167     CmdArgs.push_back(
168         Args.MakeArgString("-lclang_rt.builtins-" + getTriple().getArchName()));
169     return;
170   case ToolChain::RLT_Libgcc:
171     CmdArgs.push_back("-lgcc");
172     return;
173   }
174   llvm_unreachable("Unhandled RuntimeLibType.");
175 }
176 
177 void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA,
178                                      const InputInfo &Output,
179                                      const InputInfoList &Inputs,
180                                      const ArgList &Args,
181                                      const char *LinkingOutput) const {
182   ArgStringList CmdArgs;
183 
184   auto &TC = static_cast<const toolchains::BareMetal&>(getToolChain());
185 
186   AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
187 
188   CmdArgs.push_back("-Bstatic");
189 
190   CmdArgs.push_back(Args.MakeArgString("-L" + TC.getRuntimesDir()));
191 
192   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
193                             options::OPT_e, options::OPT_s, options::OPT_t,
194                             options::OPT_Z_Flag, options::OPT_r});
195 
196   if (TC.ShouldLinkCXXStdlib(Args))
197     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
198   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
199     CmdArgs.push_back("-lc");
200     CmdArgs.push_back("-lm");
201 
202     TC.AddLinkRuntimeLib(Args, CmdArgs);
203   }
204 
205   CmdArgs.push_back("-o");
206   CmdArgs.push_back(Output.getFilename());
207 
208   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
209                                          Args.MakeArgString(TC.GetLinkerPath()),
210                                          CmdArgs, Inputs, Output));
211 }
212