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/SmallString.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Option/Arg.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Option/Option.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FileSystem.h"
25 using namespace clang::driver;
26 using namespace clang;
27 using namespace llvm::opt;
28 
ToolChain(const Driver & D,const llvm::Triple & T,const ArgList & Args)29 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
30                      const ArgList &Args)
31   : D(D), Triple(T), Args(Args) {
32   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
33     if (!isThreadModelSupported(A->getValue()))
34       D.Diag(diag::err_drv_invalid_thread_model_for_target)
35           << A->getValue()
36           << A->getAsString(Args);
37 }
38 
~ToolChain()39 ToolChain::~ToolChain() {
40 }
41 
getDriver() const42 const Driver &ToolChain::getDriver() const {
43  return D;
44 }
45 
useIntegratedAs() const46 bool ToolChain::useIntegratedAs() const {
47   return Args.hasFlag(options::OPT_fintegrated_as,
48                       options::OPT_fno_integrated_as,
49                       IsIntegratedAssemblerDefault());
50 }
51 
getSanitizerArgs() const52 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
53   if (!SanitizerArguments.get())
54     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
55   return *SanitizerArguments.get();
56 }
57 
getDefaultUniversalArchName() const58 StringRef ToolChain::getDefaultUniversalArchName() const {
59   // In universal driver terms, the arch name accepted by -arch isn't exactly
60   // the same as the ones that appear in the triple. Roughly speaking, this is
61   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
62   // only interesting special case is powerpc.
63   switch (Triple.getArch()) {
64   case llvm::Triple::ppc:
65     return "ppc";
66   case llvm::Triple::ppc64:
67     return "ppc64";
68   case llvm::Triple::ppc64le:
69     return "ppc64le";
70   default:
71     return Triple.getArchName();
72   }
73 }
74 
IsUnwindTablesDefault() const75 bool ToolChain::IsUnwindTablesDefault() const {
76   return false;
77 }
78 
getClang() const79 Tool *ToolChain::getClang() const {
80   if (!Clang)
81     Clang.reset(new tools::Clang(*this));
82   return Clang.get();
83 }
84 
buildAssembler() const85 Tool *ToolChain::buildAssembler() const {
86   return new tools::ClangAs(*this);
87 }
88 
buildLinker() const89 Tool *ToolChain::buildLinker() const {
90   llvm_unreachable("Linking is not supported by this toolchain");
91 }
92 
getAssemble() const93 Tool *ToolChain::getAssemble() const {
94   if (!Assemble)
95     Assemble.reset(buildAssembler());
96   return Assemble.get();
97 }
98 
getClangAs() const99 Tool *ToolChain::getClangAs() const {
100   if (!Assemble)
101     Assemble.reset(new tools::ClangAs(*this));
102   return Assemble.get();
103 }
104 
getLink() const105 Tool *ToolChain::getLink() const {
106   if (!Link)
107     Link.reset(buildLinker());
108   return Link.get();
109 }
110 
getTool(Action::ActionClass AC) const111 Tool *ToolChain::getTool(Action::ActionClass AC) const {
112   switch (AC) {
113   case Action::AssembleJobClass:
114     return getAssemble();
115 
116   case Action::LinkJobClass:
117     return getLink();
118 
119   case Action::InputClass:
120   case Action::BindArchClass:
121   case Action::LipoJobClass:
122   case Action::DsymutilJobClass:
123   case Action::VerifyDebugInfoJobClass:
124     llvm_unreachable("Invalid tool kind.");
125 
126   case Action::CompileJobClass:
127   case Action::PrecompileJobClass:
128   case Action::PreprocessJobClass:
129   case Action::AnalyzeJobClass:
130   case Action::MigrateJobClass:
131   case Action::VerifyPCHJobClass:
132   case Action::BackendJobClass:
133     return getClang();
134   }
135 
136   llvm_unreachable("Invalid tool kind.");
137 }
138 
SelectTool(const JobAction & JA) const139 Tool *ToolChain::SelectTool(const JobAction &JA) const {
140   if (getDriver().ShouldUseClangCompiler(JA))
141     return getClang();
142   Action::ActionClass AC = JA.getKind();
143   if (AC == Action::AssembleJobClass && useIntegratedAs())
144     return getClangAs();
145   return getTool(AC);
146 }
147 
GetFilePath(const char * Name) const148 std::string ToolChain::GetFilePath(const char *Name) const {
149   return D.GetFilePath(Name, *this);
150 
151 }
152 
GetProgramPath(const char * Name) const153 std::string ToolChain::GetProgramPath(const char *Name) const {
154   return D.GetProgramPath(Name, *this);
155 }
156 
GetLinkerPath() const157 std::string ToolChain::GetLinkerPath() const {
158   if (Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
159     StringRef Suffix = A->getValue();
160 
161     // If we're passed -fuse-ld= with no argument, or with the argument ld,
162     // then use whatever the default system linker is.
163     if (Suffix.empty() || Suffix == "ld")
164       return GetProgramPath("ld");
165 
166     llvm::SmallString<8> LinkerName("ld.");
167     LinkerName.append(Suffix);
168 
169     std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
170     if (llvm::sys::fs::exists(LinkerPath))
171       return LinkerPath;
172 
173     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
174     return "";
175   }
176 
177   return GetProgramPath("ld");
178 }
179 
180 
LookupTypeForExtension(const char * Ext) const181 types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
182   return types::lookupTypeForExtension(Ext);
183 }
184 
HasNativeLLVMSupport() const185 bool ToolChain::HasNativeLLVMSupport() const {
186   return false;
187 }
188 
isCrossCompiling() const189 bool ToolChain::isCrossCompiling() const {
190   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
191   switch (HostTriple.getArch()) {
192   // The A32/T32/T16 instruction sets are not separate architectures in this
193   // context.
194   case llvm::Triple::arm:
195   case llvm::Triple::armeb:
196   case llvm::Triple::thumb:
197   case llvm::Triple::thumbeb:
198     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
199            getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
200   default:
201     return HostTriple.getArch() != getArch();
202   }
203 }
204 
getDefaultObjCRuntime(bool isNonFragile) const205 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
206   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
207                      VersionTuple());
208 }
209 
isThreadModelSupported(const StringRef Model) const210 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
211   if (Model == "single") {
212     // FIXME: 'single' is only supported on ARM so far.
213     return Triple.getArch() == llvm::Triple::arm ||
214            Triple.getArch() == llvm::Triple::armeb ||
215            Triple.getArch() == llvm::Triple::thumb ||
216            Triple.getArch() == llvm::Triple::thumbeb;
217   } else if (Model == "posix")
218     return true;
219 
220   return false;
221 }
222 
ComputeLLVMTriple(const ArgList & Args,types::ID InputType) const223 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
224                                          types::ID InputType) const {
225   switch (getTriple().getArch()) {
226   default:
227     return getTripleString();
228 
229   case llvm::Triple::x86_64: {
230     llvm::Triple Triple = getTriple();
231     if (!Triple.isOSBinFormatMachO())
232       return getTripleString();
233 
234     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
235       // x86_64h goes in the triple. Other -march options just use the
236       // vanilla triple we already have.
237       StringRef MArch = A->getValue();
238       if (MArch == "x86_64h")
239         Triple.setArchName(MArch);
240     }
241     return Triple.getTriple();
242   }
243   case llvm::Triple::aarch64: {
244     llvm::Triple Triple = getTriple();
245     if (!Triple.isOSBinFormatMachO())
246       return getTripleString();
247 
248     // FIXME: older versions of ld64 expect the "arm64" component in the actual
249     // triple string and query it to determine whether an LTO file can be
250     // handled. Remove this when we don't care any more.
251     Triple.setArchName("arm64");
252     return Triple.getTriple();
253   }
254   case llvm::Triple::arm:
255   case llvm::Triple::armeb:
256   case llvm::Triple::thumb:
257   case llvm::Triple::thumbeb: {
258     // FIXME: Factor into subclasses.
259     llvm::Triple Triple = getTriple();
260     bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
261                        getTriple().getArch() == llvm::Triple::thumbeb;
262 
263     // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
264     // '-mbig-endian'/'-EB'.
265     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
266                                  options::OPT_mbig_endian)) {
267       if (A->getOption().matches(options::OPT_mlittle_endian))
268         IsBigEndian = false;
269       else
270         IsBigEndian = true;
271     }
272 
273     // Thumb2 is the default for V7 on Darwin.
274     //
275     // FIXME: Thumb should just be another -target-feaure, not in the triple.
276 #if defined(__minix) || 1
277     // Minix/ARM-specific force to ARMv7 and EABI.
278     StringRef Suffix = "v7";
279     Triple.setEnvironment(llvm::Triple::EABI);
280 #else
281     StringRef Suffix = Triple.isOSBinFormatMachO()
282       ? tools::arm::getLLVMArchSuffixForARM(tools::arm::getARMCPUForMArch(Args, Triple))
283       : tools::arm::getLLVMArchSuffixForARM(tools::arm::getARMTargetCPU(Args, Triple));
284 #endif /* defined(__minix) || 1 */
285     bool ThumbDefault = Suffix.startswith("v6m") || Suffix.startswith("v7m") ||
286       Suffix.startswith("v7em") ||
287       (Suffix.startswith("v7") && getTriple().isOSBinFormatMachO());
288     // FIXME: this is invalid for WindowsCE
289     if (getTriple().isOSWindows())
290       ThumbDefault = true;
291     std::string ArchName;
292     if (IsBigEndian)
293       ArchName = "armeb";
294     else
295       ArchName = "arm";
296 
297     // Assembly files should start in ARM mode.
298     if (InputType != types::TY_PP_Asm &&
299         Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
300     {
301       if (IsBigEndian)
302         ArchName = "thumbeb";
303       else
304         ArchName = "thumb";
305     }
306     Triple.setArchName(ArchName + Suffix.str());
307 
308     return Triple.getTriple();
309   }
310   }
311 }
312 
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const313 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
314                                                    types::ID InputType) const {
315   return ComputeLLVMTriple(Args, InputType);
316 }
317 
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const318 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
319                                           ArgStringList &CC1Args) const {
320   // Each toolchain should provide the appropriate include flags.
321 }
322 
addClangTargetOptions(const ArgList & DriverArgs,ArgStringList & CC1Args) const323 void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
324                                       ArgStringList &CC1Args) const {
325 }
326 
addClangWarningOptions(ArgStringList & CC1Args) const327 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
328 
GetRuntimeLibType(const ArgList & Args) const329 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
330   const ArgList &Args) const
331 {
332   if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
333     StringRef Value = A->getValue();
334     if (Value == "compiler-rt")
335       return ToolChain::RLT_CompilerRT;
336     if (Value == "libgcc")
337       return ToolChain::RLT_Libgcc;
338     getDriver().Diag(diag::err_drv_invalid_rtlib_name)
339       << A->getAsString(Args);
340   }
341 
342   return GetDefaultRuntimeLibType();
343 }
344 
GetCXXStdlibType(const ArgList & Args) const345 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
346   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
347     StringRef Value = A->getValue();
348     if (Value == "libc++")
349       return ToolChain::CST_Libcxx;
350     if (Value == "libstdc++")
351       return ToolChain::CST_Libstdcxx;
352     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
353       << A->getAsString(Args);
354   }
355 
356   return ToolChain::CST_Libstdcxx;
357 }
358 
359 /// \brief Utility function to add a system include directory to CC1 arguments.
addSystemInclude(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)360 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
361                                             ArgStringList &CC1Args,
362                                             const Twine &Path) {
363   CC1Args.push_back("-internal-isystem");
364   CC1Args.push_back(DriverArgs.MakeArgString(Path));
365 }
366 
367 /// \brief Utility function to add a system include directory with extern "C"
368 /// semantics to CC1 arguments.
369 ///
370 /// Note that this should be used rarely, and only for directories that
371 /// historically and for legacy reasons are treated as having implicit extern
372 /// "C" semantics. These semantics are *ignored* by and large today, but its
373 /// important to preserve the preprocessor changes resulting from the
374 /// classification.
addExternCSystemInclude(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)375 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
376                                                    ArgStringList &CC1Args,
377                                                    const Twine &Path) {
378   CC1Args.push_back("-internal-externc-isystem");
379   CC1Args.push_back(DriverArgs.MakeArgString(Path));
380 }
381 
addExternCSystemIncludeIfExists(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)382 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
383                                                 ArgStringList &CC1Args,
384                                                 const Twine &Path) {
385   if (llvm::sys::fs::exists(Path))
386     addExternCSystemInclude(DriverArgs, CC1Args, Path);
387 }
388 
389 /// \brief Utility function to add a list of system include directories to CC1.
addSystemIncludes(const ArgList & DriverArgs,ArgStringList & CC1Args,ArrayRef<StringRef> Paths)390 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
391                                              ArgStringList &CC1Args,
392                                              ArrayRef<StringRef> Paths) {
393   for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
394        I != E; ++I) {
395     CC1Args.push_back("-internal-isystem");
396     CC1Args.push_back(DriverArgs.MakeArgString(*I));
397   }
398 }
399 
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const400 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
401                                              ArgStringList &CC1Args) const {
402   // Header search paths should be handled by each of the subclasses.
403   // Historically, they have not been, and instead have been handled inside of
404   // the CC1-layer frontend. As the logic is hoisted out, this generic function
405   // will slowly stop being called.
406   //
407   // While it is being called, replicate a bit of a hack to propagate the
408   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
409   // header search paths with it. Once all systems are overriding this
410   // function, the CC1 flag and this line can be removed.
411   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
412 }
413 
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const414 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
415                                     ArgStringList &CmdArgs) const {
416   CXXStdlibType Type = GetCXXStdlibType(Args);
417 
418   switch (Type) {
419   case ToolChain::CST_Libcxx:
420     CmdArgs.push_back("-lc++");
421     break;
422 
423   case ToolChain::CST_Libstdcxx:
424     CmdArgs.push_back("-lstdc++");
425     break;
426   }
427 }
428 
AddCCKextLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const429 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
430                                  ArgStringList &CmdArgs) const {
431   CmdArgs.push_back("-lcc_kext");
432 }
433 
AddFastMathRuntimeIfAvailable(const ArgList & Args,ArgStringList & CmdArgs) const434 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
435                                               ArgStringList &CmdArgs) const {
436   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
437   // (to keep the linker options consistent with gcc and clang itself).
438   if (!isOptimizationLevelFast(Args)) {
439     // Check if -ffast-math or -funsafe-math.
440     Arg *A =
441         Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
442                         options::OPT_funsafe_math_optimizations,
443                         options::OPT_fno_unsafe_math_optimizations);
444 
445     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
446         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
447       return false;
448   }
449   // If crtfastmath.o exists add it to the arguments.
450   std::string Path = GetFilePath("crtfastmath.o");
451   if (Path == "crtfastmath.o") // Not found.
452     return false;
453 
454   CmdArgs.push_back(Args.MakeArgString(Path));
455   return true;
456 }
457