1//===--- RISCVToolchain.cpp - RISC-V ToolChain Implementations --*- 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 "RISCVToolchain.h"
10#include "CommonArgs.h"
11#include "clang/Driver/Compilation.h"
12#include "clang/Driver/InputInfo.h"
13#include "clang/Driver/Options.h"
14#include "llvm/Option/ArgList.h"
15#include "llvm/Support/FileSystem.h"
16#include "llvm/Support/Path.h"
17#include "llvm/Support/raw_ostream.h"
18
19using namespace clang::driver;
20using namespace clang::driver::toolchains;
21using namespace clang::driver::tools;
22using namespace clang;
23using namespace llvm::opt;
24
25static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
26 const Multilib &Multilib,
27 StringRef InstallPath,
28 ToolChain::path_list &Paths) {
29 if (const auto &PathsCallback = Multilibs.filePathsCallback())
30 for (const auto &Path : PathsCallback(Multilib))
31 addPathIfExists(D, Path: InstallPath + Path, Paths);
32}
33
34// This function tests whether a gcc installation is present either
35// through gcc-toolchain argument or in the same prefix where clang
36// is installed. This helps decide whether to instantiate this toolchain
37// or Baremetal toolchain.
38bool RISCVToolChain::hasGCCToolchain(const Driver &D,
39 const llvm::opt::ArgList &Args) {
40 if (Args.getLastArg(Ids: options::OPT_gcc_toolchain))
41 return true;
42
43 SmallString<128> GCCDir;
44 llvm::sys::path::append(path&: GCCDir, a: D.Dir, b: "..", c: D.getTargetTriple(),
45 d: "lib/crt0.o");
46 return llvm::sys::fs::exists(Path: GCCDir);
47}
48
49/// RISC-V Toolchain
50RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
51 const ArgList &Args)
52 : Generic_ELF(D, Triple, Args) {
53 GCCInstallation.init(TargetTriple: Triple, Args);
54 if (GCCInstallation.isValid()) {
55 Multilibs = GCCInstallation.getMultilibs();
56 SelectedMultilibs.assign(IL: {GCCInstallation.getMultilib()});
57 path_list &Paths = getFilePaths();
58 // Add toolchain/multilib specific file paths.
59 addMultilibsFilePaths(D, Multilibs, Multilib: SelectedMultilibs.back(),
60 InstallPath: GCCInstallation.getInstallPath(), Paths);
61 getFilePaths().push_back(Elt: GCCInstallation.getInstallPath().str());
62 ToolChain::path_list &PPaths = getProgramPaths();
63 // Multilib cross-compiler GCC installations put ld in a triple-prefixed
64 // directory off of the parent of the GCC installation.
65 PPaths.push_back(Elt: Twine(GCCInstallation.getParentLibPath() + "/../" +
66 GCCInstallation.getTriple().str() + "/bin")
67 .str());
68 PPaths.push_back(Elt: (GCCInstallation.getParentLibPath() + "/../bin").str());
69 } else {
70 getProgramPaths().push_back(Elt: D.Dir);
71 }
72 getFilePaths().push_back(Elt: computeSysRoot() + "/lib");
73}
74
75Tool *RISCVToolChain::buildLinker() const {
76 return new tools::RISCV::Linker(*this);
77}
78
79ToolChain::RuntimeLibType RISCVToolChain::GetDefaultRuntimeLibType() const {
80 return GCCInstallation.isValid() ?
81 ToolChain::RLT_Libgcc : ToolChain::RLT_CompilerRT;
82}
83
84ToolChain::UnwindLibType
85RISCVToolChain::GetUnwindLibType(const llvm::opt::ArgList &Args) const {
86 return ToolChain::UNW_None;
87}
88
89ToolChain::UnwindTableLevel RISCVToolChain::getDefaultUnwindTableLevel(
90 const llvm::opt::ArgList &Args) const {
91 return UnwindTableLevel::None;
92}
93
94void RISCVToolChain::addClangTargetOptions(
95 const llvm::opt::ArgList &DriverArgs,
96 llvm::opt::ArgStringList &CC1Args,
97 Action::OffloadKind) const {
98 CC1Args.push_back(Elt: "-nostdsysteminc");
99}
100
101void RISCVToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
102 ArgStringList &CC1Args) const {
103 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc))
104 return;
105
106 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc)) {
107 SmallString<128> Dir(getDriver().ResourceDir);
108 llvm::sys::path::append(path&: Dir, a: "include");
109 addSystemInclude(DriverArgs, CC1Args, Path: Dir.str());
110 }
111
112 if (!DriverArgs.hasArg(Ids: options::OPT_nostdlibinc)) {
113 SmallString<128> Dir(computeSysRoot());
114 llvm::sys::path::append(path&: Dir, a: "include");
115 addSystemInclude(DriverArgs, CC1Args, Path: Dir.str());
116 }
117}
118
119void RISCVToolChain::addLibStdCxxIncludePaths(
120 const llvm::opt::ArgList &DriverArgs,
121 llvm::opt::ArgStringList &CC1Args) const {
122 const GCCVersion &Version = GCCInstallation.getVersion();
123 StringRef TripleStr = GCCInstallation.getTriple().str();
124 const Multilib &Multilib = GCCInstallation.getMultilib();
125 addLibStdCXXIncludePaths(IncludeDir: computeSysRoot() + "/include/c++/" + Version.Text,
126 Triple: TripleStr, IncludeSuffix: Multilib.includeSuffix(), DriverArgs,
127 CC1Args);
128}
129
130std::string RISCVToolChain::computeSysRoot() const {
131 if (!getDriver().SysRoot.empty())
132 return getDriver().SysRoot;
133
134 SmallString<128> SysRootDir;
135 if (GCCInstallation.isValid()) {
136 StringRef LibDir = GCCInstallation.getParentLibPath();
137 StringRef TripleStr = GCCInstallation.getTriple().str();
138 llvm::sys::path::append(path&: SysRootDir, a: LibDir, b: "..", c: TripleStr);
139 } else {
140 // Use the triple as provided to the driver. Unlike the parsed triple
141 // this has not been normalized to always contain every field.
142 llvm::sys::path::append(path&: SysRootDir, a: getDriver().Dir, b: "..",
143 c: getDriver().getTargetTriple());
144 }
145
146 if (!llvm::sys::fs::exists(Path: SysRootDir))
147 return std::string();
148
149 return std::string(SysRootDir);
150}
151
152void RISCV::Linker::ConstructJob(Compilation &C, const JobAction &JA,
153 const InputInfo &Output,
154 const InputInfoList &Inputs,
155 const ArgList &Args,
156 const char *LinkingOutput) const {
157 const ToolChain &ToolChain = getToolChain();
158 const Driver &D = ToolChain.getDriver();
159 ArgStringList CmdArgs;
160
161 if (!D.SysRoot.empty())
162 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--sysroot=" + D.SysRoot));
163
164 if (Args.hasArg(Ids: options::OPT_mno_relax))
165 CmdArgs.push_back(Elt: "--no-relax");
166
167 bool IsRV64 = ToolChain.getArch() == llvm::Triple::riscv64;
168 CmdArgs.push_back(Elt: "-m");
169 if (IsRV64) {
170 CmdArgs.push_back(Elt: "elf64lriscv");
171 } else {
172 CmdArgs.push_back(Elt: "elf32lriscv");
173 }
174 CmdArgs.push_back(Elt: "-X");
175
176 std::string Linker = getToolChain().GetLinkerPath();
177
178 bool WantCRTs =
179 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles);
180
181 const char *crtbegin, *crtend;
182 auto RuntimeLib = ToolChain.GetRuntimeLibType(Args);
183 if (RuntimeLib == ToolChain::RLT_Libgcc) {
184 crtbegin = "crtbegin.o";
185 crtend = "crtend.o";
186 } else {
187 assert (RuntimeLib == ToolChain::RLT_CompilerRT);
188 crtbegin = ToolChain.getCompilerRTArgString(Args, Component: "crtbegin",
189 Type: ToolChain::FT_Object);
190 crtend = ToolChain.getCompilerRTArgString(Args, Component: "crtend",
191 Type: ToolChain::FT_Object);
192 }
193
194 if (WantCRTs) {
195 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: "crt0.o")));
196 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: crtbegin)));
197 }
198
199 AddLinkerInputs(TC: ToolChain, Inputs, Args, CmdArgs, JA);
200
201 Args.addAllArgs(Output&: CmdArgs, Ids: {options::OPT_L, options::OPT_u});
202
203 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
204 Args.addAllArgs(Output&: CmdArgs, Ids: {options::OPT_T_Group, options::OPT_s,
205 options::OPT_t, options::OPT_r});
206
207 // TODO: add C++ includes and libs if compiling C++.
208
209 if (!Args.hasArg(Ids: options::OPT_nostdlib) &&
210 !Args.hasArg(Ids: options::OPT_nodefaultlibs)) {
211 if (D.CCCIsCXX()) {
212 if (ToolChain.ShouldLinkCXXStdlib(Args))
213 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
214 CmdArgs.push_back(Elt: "-lm");
215 }
216 CmdArgs.push_back(Elt: "--start-group");
217 CmdArgs.push_back(Elt: "-lc");
218 CmdArgs.push_back(Elt: "-lgloss");
219 CmdArgs.push_back(Elt: "--end-group");
220 AddRunTimeLibs(TC: ToolChain, D: ToolChain.getDriver(), CmdArgs, Args);
221 }
222
223 if (WantCRTs)
224 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: crtend)));
225
226 CmdArgs.push_back(Elt: "-o");
227 CmdArgs.push_back(Elt: Output.getFilename());
228 C.addCommand(C: std::make_unique<Command>(
229 args: JA, args: *this, args: ResponseFileSupport::AtFileCurCP(), args: Args.MakeArgString(Str: Linker),
230 args&: CmdArgs, args: Inputs, args: Output));
231}
232// RISCV tools end.
233