1 //===--- ToolChain.cpp - Collections of tools for one platform ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Tools.h"
11 #include "clang/Basic/ObjCRuntime.h"
12 #include "clang/Driver/Action.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Options.h"
16 #include "clang/Driver/SanitizerArgs.h"
17 #include "clang/Driver/ToolChain.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/Option/Arg.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/Option/Option.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/FileSystem.h"
24 using namespace clang::driver;
25 using namespace clang;
26 using namespace llvm::opt;
27 
28 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
29                      const ArgList &A)
30   : D(D), Triple(T), Args(A) {
31 }
32 
33 ToolChain::~ToolChain() {
34 }
35 
36 const Driver &ToolChain::getDriver() const {
37  return D;
38 }
39 
40 bool ToolChain::useIntegratedAs() const {
41   return Args.hasFlag(options::OPT_integrated_as,
42                       options::OPT_no_integrated_as,
43                       IsIntegratedAssemblerDefault());
44 }
45 
46 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
47   if (!SanitizerArguments.get())
48     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
49   return *SanitizerArguments.get();
50 }
51 
52 std::string ToolChain::getDefaultUniversalArchName() const {
53   // In universal driver terms, the arch name accepted by -arch isn't exactly
54   // the same as the ones that appear in the triple. Roughly speaking, this is
55   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
56   // only interesting special case is powerpc.
57   switch (Triple.getArch()) {
58   case llvm::Triple::ppc:
59     return "ppc";
60   case llvm::Triple::ppc64:
61     return "ppc64";
62   case llvm::Triple::ppc64le:
63     return "ppc64le";
64   default:
65     return Triple.getArchName();
66   }
67 }
68 
69 bool ToolChain::IsUnwindTablesDefault() const {
70   return false;
71 }
72 
73 Tool *ToolChain::getClang() const {
74   if (!Clang)
75     Clang.reset(new tools::Clang(*this));
76   return Clang.get();
77 }
78 
79 Tool *ToolChain::buildAssembler() const {
80   return new tools::ClangAs(*this);
81 }
82 
83 Tool *ToolChain::buildLinker() const {
84   llvm_unreachable("Linking is not supported by this toolchain");
85 }
86 
87 Tool *ToolChain::getAssemble() const {
88   if (!Assemble)
89     Assemble.reset(buildAssembler());
90   return Assemble.get();
91 }
92 
93 Tool *ToolChain::getClangAs() const {
94   if (!Assemble)
95     Assemble.reset(new tools::ClangAs(*this));
96   return Assemble.get();
97 }
98 
99 Tool *ToolChain::getLink() const {
100   if (!Link)
101     Link.reset(buildLinker());
102   return Link.get();
103 }
104 
105 Tool *ToolChain::getTool(Action::ActionClass AC) const {
106   switch (AC) {
107   case Action::AssembleJobClass:
108     return getAssemble();
109 
110   case Action::LinkJobClass:
111     return getLink();
112 
113   case Action::InputClass:
114   case Action::BindArchClass:
115   case Action::LipoJobClass:
116   case Action::DsymutilJobClass:
117   case Action::VerifyJobClass:
118     llvm_unreachable("Invalid tool kind.");
119 
120   case Action::CompileJobClass:
121   case Action::PrecompileJobClass:
122   case Action::PreprocessJobClass:
123   case Action::AnalyzeJobClass:
124   case Action::MigrateJobClass:
125     return getClang();
126   }
127 
128   llvm_unreachable("Invalid tool kind.");
129 }
130 
131 Tool *ToolChain::SelectTool(const JobAction &JA) const {
132   if (getDriver().ShouldUseClangCompiler(JA))
133     return getClang();
134   Action::ActionClass AC = JA.getKind();
135   if (AC == Action::AssembleJobClass && useIntegratedAs())
136     return getClangAs();
137   return getTool(AC);
138 }
139 
140 std::string ToolChain::GetFilePath(const char *Name) const {
141   return D.GetFilePath(Name, *this);
142 
143 }
144 
145 std::string ToolChain::GetProgramPath(const char *Name) const {
146   return D.GetProgramPath(Name, *this);
147 }
148 
149 types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
150   return types::lookupTypeForExtension(Ext);
151 }
152 
153 bool ToolChain::HasNativeLLVMSupport() const {
154   return false;
155 }
156 
157 bool ToolChain::isCrossCompiling() const {
158   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
159   switch (HostTriple.getArch()) {
160   // The A32/T32/T16 instruction sets are not separate architectures in this
161   // context.
162   case llvm::Triple::arm:
163   case llvm::Triple::thumb:
164     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb;
165   default:
166     return HostTriple.getArch() != getArch();
167   }
168 }
169 
170 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
171   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
172                      VersionTuple());
173 }
174 
175 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
176                                          types::ID InputType) const {
177   switch (getTriple().getArch()) {
178   default:
179     return getTripleString();
180 
181   case llvm::Triple::x86_64: {
182     llvm::Triple Triple = getTriple();
183     if (!Triple.isOSBinFormatMachO())
184       return getTripleString();
185 
186     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
187       // x86_64h goes in the triple. Other -march options just use the
188       // vanilla triple we already have.
189       StringRef MArch = A->getValue();
190       if (MArch == "x86_64h")
191         Triple.setArchName(MArch);
192     }
193     return Triple.getTriple();
194   }
195   case llvm::Triple::arm:
196   case llvm::Triple::thumb: {
197     // FIXME: Factor into subclasses.
198     llvm::Triple Triple = getTriple();
199 
200     // Thumb2 is the default for V7 on Darwin.
201     //
202     // FIXME: Thumb should just be another -target-feaure, not in the triple.
203     StringRef Suffix = Triple.isOSBinFormatMachO()
204       ? tools::arm::getLLVMArchSuffixForARM(tools::arm::getARMCPUForMArch(Args, Triple))
205       : tools::arm::getLLVMArchSuffixForARM(tools::arm::getARMTargetCPU(Args, Triple));
206     bool ThumbDefault = Suffix.startswith("v6m") || Suffix.startswith("v7m") ||
207       Suffix.startswith("v7em") ||
208       (Suffix.startswith("v7") && getTriple().isOSBinFormatMachO());
209     std::string ArchName = "arm";
210 
211     // Assembly files should start in ARM mode.
212     if (InputType != types::TY_PP_Asm &&
213         Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
214       ArchName = "thumb";
215     Triple.setArchName(ArchName + Suffix.str());
216 
217     return Triple.getTriple();
218   }
219   }
220 }
221 
222 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
223                                                    types::ID InputType) const {
224   return ComputeLLVMTriple(Args, InputType);
225 }
226 
227 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
228                                           ArgStringList &CC1Args) const {
229   // Each toolchain should provide the appropriate include flags.
230 }
231 
232 void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
233                                       ArgStringList &CC1Args) const {
234 }
235 
236 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
237   const ArgList &Args) const
238 {
239   if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
240     StringRef Value = A->getValue();
241     if (Value == "compiler-rt")
242       return ToolChain::RLT_CompilerRT;
243     if (Value == "libgcc")
244       return ToolChain::RLT_Libgcc;
245     getDriver().Diag(diag::err_drv_invalid_rtlib_name)
246       << A->getAsString(Args);
247   }
248 
249   return GetDefaultRuntimeLibType();
250 }
251 
252 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
253   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
254     StringRef Value = A->getValue();
255     if (Value == "libc++")
256       return ToolChain::CST_Libcxx;
257     if (Value == "libstdc++")
258       return ToolChain::CST_Libstdcxx;
259     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
260       << A->getAsString(Args);
261   }
262 
263   return ToolChain::CST_Libstdcxx;
264 }
265 
266 /// \brief Utility function to add a system include directory to CC1 arguments.
267 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
268                                             ArgStringList &CC1Args,
269                                             const Twine &Path) {
270   CC1Args.push_back("-internal-isystem");
271   CC1Args.push_back(DriverArgs.MakeArgString(Path));
272 }
273 
274 /// \brief Utility function to add a system include directory with extern "C"
275 /// semantics to CC1 arguments.
276 ///
277 /// Note that this should be used rarely, and only for directories that
278 /// historically and for legacy reasons are treated as having implicit extern
279 /// "C" semantics. These semantics are *ignored* by and large today, but its
280 /// important to preserve the preprocessor changes resulting from the
281 /// classification.
282 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
283                                                    ArgStringList &CC1Args,
284                                                    const Twine &Path) {
285   CC1Args.push_back("-internal-externc-isystem");
286   CC1Args.push_back(DriverArgs.MakeArgString(Path));
287 }
288 
289 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
290                                                 ArgStringList &CC1Args,
291                                                 const Twine &Path) {
292   if (llvm::sys::fs::exists(Path))
293     addExternCSystemInclude(DriverArgs, CC1Args, Path);
294 }
295 
296 /// \brief Utility function to add a list of system include directories to CC1.
297 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
298                                              ArgStringList &CC1Args,
299                                              ArrayRef<StringRef> Paths) {
300   for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
301        I != E; ++I) {
302     CC1Args.push_back("-internal-isystem");
303     CC1Args.push_back(DriverArgs.MakeArgString(*I));
304   }
305 }
306 
307 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
308                                              ArgStringList &CC1Args) const {
309   // Header search paths should be handled by each of the subclasses.
310   // Historically, they have not been, and instead have been handled inside of
311   // the CC1-layer frontend. As the logic is hoisted out, this generic function
312   // will slowly stop being called.
313   //
314   // While it is being called, replicate a bit of a hack to propagate the
315   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
316   // header search paths with it. Once all systems are overriding this
317   // function, the CC1 flag and this line can be removed.
318   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
319 }
320 
321 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
322                                     ArgStringList &CmdArgs) const {
323   CXXStdlibType Type = GetCXXStdlibType(Args);
324 
325   switch (Type) {
326   case ToolChain::CST_Libcxx:
327     CmdArgs.push_back("-lc++");
328     break;
329 
330   case ToolChain::CST_Libstdcxx:
331     CmdArgs.push_back("-lstdc++");
332     break;
333   }
334 }
335 
336 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
337                                  ArgStringList &CmdArgs) const {
338   CmdArgs.push_back("-lcc_kext");
339 }
340 
341 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
342                                               ArgStringList &CmdArgs) const {
343   // Check if -ffast-math or -funsafe-math is enabled.
344   Arg *A = Args.getLastArg(options::OPT_ffast_math,
345                            options::OPT_fno_fast_math,
346                            options::OPT_funsafe_math_optimizations,
347                            options::OPT_fno_unsafe_math_optimizations);
348 
349   if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
350       A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
351     return false;
352 
353   // If crtfastmath.o exists add it to the arguments.
354   std::string Path = GetFilePath("crtfastmath.o");
355   if (Path == "crtfastmath.o") // Not found.
356     return false;
357 
358   CmdArgs.push_back(Args.MakeArgString(Path));
359   return true;
360 }
361