1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
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 "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/TargetParser.h"
45
46 #ifdef LLVM_ON_UNIX
47 #include <unistd.h> // For getuid().
48 #endif
49
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
54
getSparcAsmModeForCPU(StringRef Name,const llvm::Triple & Triple)55 static const char *getSparcAsmModeForCPU(StringRef Name,
56 const llvm::Triple &Triple) {
57 if (Triple.getArch() == llvm::Triple::sparcv9) {
58 return llvm::StringSwitch<const char *>(Name)
59 .Case("niagara", "-Av9b")
60 .Case("niagara2", "-Av9b")
61 .Case("niagara3", "-Av9d")
62 .Case("niagara4", "-Av9d")
63 .Default("-Av9");
64 } else {
65 return llvm::StringSwitch<const char *>(Name)
66 .Case("v8", "-Av8")
67 .Case("supersparc", "-Av8")
68 .Case("sparclite", "-Asparclite")
69 .Case("f934", "-Asparclite")
70 .Case("hypersparc", "-Av8")
71 .Case("sparclite86x", "-Asparclite")
72 .Case("sparclet", "-Asparclet")
73 .Case("tsc701", "-Asparclet")
74 .Case("v9", "-Av8plus")
75 .Case("ultrasparc", "-Av8plus")
76 .Case("ultrasparc3", "-Av8plus")
77 .Case("niagara", "-Av8plusb")
78 .Case("niagara2", "-Av8plusb")
79 .Case("niagara3", "-Av8plusd")
80 .Case("niagara4", "-Av8plusd")
81 .Default("-Av8");
82 }
83 }
84
85 /// CheckPreprocessingOptions - Perform some validation of preprocessing
86 /// arguments that is shared with gcc.
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)87 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
88 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
89 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
90 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
91 D.Diag(diag::err_drv_argument_only_allowed_with)
92 << A->getBaseArg().getAsString(Args)
93 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
94 }
95 }
96 }
97
98 /// CheckCodeGenerationOptions - Perform some validation of code generation
99 /// arguments that is shared with gcc.
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)100 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
101 // In gcc, only ARM checks this, but it seems reasonable to check universally.
102 if (Args.hasArg(options::OPT_static))
103 if (const Arg *A =
104 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
105 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
106 << "-static";
107 }
108
109 // Add backslashes to escape spaces and other backslashes.
110 // This is used for the space-separated argument list specified with
111 // the -dwarf-debug-flags option.
EscapeSpacesAndBackslashes(const char * Arg,SmallVectorImpl<char> & Res)112 static void EscapeSpacesAndBackslashes(const char *Arg,
113 SmallVectorImpl<char> &Res) {
114 for (; *Arg; ++Arg) {
115 switch (*Arg) {
116 default:
117 break;
118 case ' ':
119 case '\\':
120 Res.push_back('\\');
121 break;
122 }
123 Res.push_back(*Arg);
124 }
125 }
126
127 // Quote target names for inclusion in GNU Make dependency files.
128 // Only the characters '$', '#', ' ', '\t' are quoted.
QuoteTarget(StringRef Target,SmallVectorImpl<char> & Res)129 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
130 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
131 switch (Target[i]) {
132 case ' ':
133 case '\t':
134 // Escape the preceding backslashes
135 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
136 Res.push_back('\\');
137
138 // Escape the space/tab
139 Res.push_back('\\');
140 break;
141 case '$':
142 Res.push_back('$');
143 break;
144 case '#':
145 Res.push_back('\\');
146 break;
147 default:
148 break;
149 }
150
151 Res.push_back(Target[i]);
152 }
153 }
154
addDirectoryList(const ArgList & Args,ArgStringList & CmdArgs,const char * ArgName,const char * EnvVar)155 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
156 const char *ArgName, const char *EnvVar) {
157 const char *DirList = ::getenv(EnvVar);
158 bool CombinedArg = false;
159
160 if (!DirList)
161 return; // Nothing to do.
162
163 StringRef Name(ArgName);
164 if (Name.equals("-I") || Name.equals("-L"))
165 CombinedArg = true;
166
167 StringRef Dirs(DirList);
168 if (Dirs.empty()) // Empty string should not add '.'.
169 return;
170
171 StringRef::size_type Delim;
172 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
173 if (Delim == 0) { // Leading colon.
174 if (CombinedArg) {
175 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
176 } else {
177 CmdArgs.push_back(ArgName);
178 CmdArgs.push_back(".");
179 }
180 } else {
181 if (CombinedArg) {
182 CmdArgs.push_back(
183 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
184 } else {
185 CmdArgs.push_back(ArgName);
186 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
187 }
188 }
189 Dirs = Dirs.substr(Delim + 1);
190 }
191
192 if (Dirs.empty()) { // Trailing colon.
193 if (CombinedArg) {
194 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
195 } else {
196 CmdArgs.push_back(ArgName);
197 CmdArgs.push_back(".");
198 }
199 } else { // Add the last path.
200 if (CombinedArg) {
201 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
202 } else {
203 CmdArgs.push_back(ArgName);
204 CmdArgs.push_back(Args.MakeArgString(Dirs));
205 }
206 }
207 }
208
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs)209 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
210 const ArgList &Args, ArgStringList &CmdArgs) {
211 const Driver &D = TC.getDriver();
212
213 // Add extra linker input arguments which are not treated as inputs
214 // (constructed via -Xarch_).
215 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
216
217 for (const auto &II : Inputs) {
218 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
219 // Don't try to pass LLVM inputs unless we have native support.
220 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
221
222 // Add filenames immediately.
223 if (II.isFilename()) {
224 CmdArgs.push_back(II.getFilename());
225 continue;
226 }
227
228 // Otherwise, this is a linker input argument.
229 const Arg &A = II.getInputArg();
230
231 // Handle reserved library options.
232 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
233 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
234 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
235 TC.AddCCKextLibArgs(Args, CmdArgs);
236 else if (A.getOption().matches(options::OPT_z)) {
237 // Pass -z prefix for gcc linker compatibility.
238 A.claim();
239 A.render(Args, CmdArgs);
240 } else {
241 A.renderAsInput(Args, CmdArgs);
242 }
243 }
244
245 // LIBRARY_PATH - included following the user specified library paths.
246 // and only supported on native toolchains.
247 if (!TC.isCrossCompiling())
248 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
249 }
250
251 /// \brief Determine whether Objective-C automated reference counting is
252 /// enabled.
isObjCAutoRefCount(const ArgList & Args)253 static bool isObjCAutoRefCount(const ArgList &Args) {
254 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
255 }
256
257 /// \brief Determine whether we are linking the ObjC runtime.
isObjCRuntimeLinked(const ArgList & Args)258 static bool isObjCRuntimeLinked(const ArgList &Args) {
259 if (isObjCAutoRefCount(Args)) {
260 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
261 return true;
262 }
263 return Args.hasArg(options::OPT_fobjc_link_runtime);
264 }
265
forwardToGCC(const Option & O)266 static bool forwardToGCC(const Option &O) {
267 // Don't forward inputs from the original command line. They are added from
268 // InputInfoList.
269 return O.getKind() != Option::InputClass &&
270 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
271 }
272
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs,const ToolChain * AuxToolChain) const273 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
274 const Driver &D, const ArgList &Args,
275 ArgStringList &CmdArgs,
276 const InputInfo &Output,
277 const InputInfoList &Inputs,
278 const ToolChain *AuxToolChain) const {
279 Arg *A;
280
281 CheckPreprocessingOptions(D, Args);
282
283 Args.AddLastArg(CmdArgs, options::OPT_C);
284 Args.AddLastArg(CmdArgs, options::OPT_CC);
285
286 // Handle dependency file generation.
287 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
288 (A = Args.getLastArg(options::OPT_MD)) ||
289 (A = Args.getLastArg(options::OPT_MMD))) {
290 // Determine the output location.
291 const char *DepFile;
292 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
293 DepFile = MF->getValue();
294 C.addFailureResultFile(DepFile, &JA);
295 } else if (Output.getType() == types::TY_Dependencies) {
296 DepFile = Output.getFilename();
297 } else if (A->getOption().matches(options::OPT_M) ||
298 A->getOption().matches(options::OPT_MM)) {
299 DepFile = "-";
300 } else {
301 DepFile = getDependencyFileName(Args, Inputs);
302 C.addFailureResultFile(DepFile, &JA);
303 }
304 CmdArgs.push_back("-dependency-file");
305 CmdArgs.push_back(DepFile);
306
307 // Add a default target if one wasn't specified.
308 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
309 const char *DepTarget;
310
311 // If user provided -o, that is the dependency target, except
312 // when we are only generating a dependency file.
313 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
314 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
315 DepTarget = OutputOpt->getValue();
316 } else {
317 // Otherwise derive from the base input.
318 //
319 // FIXME: This should use the computed output file location.
320 SmallString<128> P(Inputs[0].getBaseInput());
321 llvm::sys::path::replace_extension(P, "o");
322 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
323 }
324
325 CmdArgs.push_back("-MT");
326 SmallString<128> Quoted;
327 QuoteTarget(DepTarget, Quoted);
328 CmdArgs.push_back(Args.MakeArgString(Quoted));
329 }
330
331 if (A->getOption().matches(options::OPT_M) ||
332 A->getOption().matches(options::OPT_MD))
333 CmdArgs.push_back("-sys-header-deps");
334 if ((isa<PrecompileJobAction>(JA) &&
335 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
336 Args.hasArg(options::OPT_fmodule_file_deps))
337 CmdArgs.push_back("-module-file-deps");
338 }
339
340 if (Args.hasArg(options::OPT_MG)) {
341 if (!A || A->getOption().matches(options::OPT_MD) ||
342 A->getOption().matches(options::OPT_MMD))
343 D.Diag(diag::err_drv_mg_requires_m_or_mm);
344 CmdArgs.push_back("-MG");
345 }
346
347 Args.AddLastArg(CmdArgs, options::OPT_MP);
348 Args.AddLastArg(CmdArgs, options::OPT_MV);
349
350 // Convert all -MQ <target> args to -MT <quoted target>
351 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
352 A->claim();
353
354 if (A->getOption().matches(options::OPT_MQ)) {
355 CmdArgs.push_back("-MT");
356 SmallString<128> Quoted;
357 QuoteTarget(A->getValue(), Quoted);
358 CmdArgs.push_back(Args.MakeArgString(Quoted));
359
360 // -MT flag - no change
361 } else {
362 A->render(Args, CmdArgs);
363 }
364 }
365
366 // Add -i* options, and automatically translate to
367 // -include-pch/-include-pth for transparent PCH support. It's
368 // wonky, but we include looking for .gch so we can support seamless
369 // replacement into a build system already set up to be generating
370 // .gch files.
371 bool RenderedImplicitInclude = false;
372 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
373 if (A->getOption().matches(options::OPT_include)) {
374 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
375 RenderedImplicitInclude = true;
376
377 // Use PCH if the user requested it.
378 bool UsePCH = D.CCCUsePCH;
379
380 bool FoundPTH = false;
381 bool FoundPCH = false;
382 SmallString<128> P(A->getValue());
383 // We want the files to have a name like foo.h.pch. Add a dummy extension
384 // so that replace_extension does the right thing.
385 P += ".dummy";
386 if (UsePCH) {
387 llvm::sys::path::replace_extension(P, "pch");
388 if (llvm::sys::fs::exists(P))
389 FoundPCH = true;
390 }
391
392 if (!FoundPCH) {
393 llvm::sys::path::replace_extension(P, "pth");
394 if (llvm::sys::fs::exists(P))
395 FoundPTH = true;
396 }
397
398 if (!FoundPCH && !FoundPTH) {
399 llvm::sys::path::replace_extension(P, "gch");
400 if (llvm::sys::fs::exists(P)) {
401 FoundPCH = UsePCH;
402 FoundPTH = !UsePCH;
403 }
404 }
405
406 if (FoundPCH || FoundPTH) {
407 if (IsFirstImplicitInclude) {
408 A->claim();
409 if (UsePCH)
410 CmdArgs.push_back("-include-pch");
411 else
412 CmdArgs.push_back("-include-pth");
413 CmdArgs.push_back(Args.MakeArgString(P));
414 continue;
415 } else {
416 // Ignore the PCH if not first on command line and emit warning.
417 D.Diag(diag::warn_drv_pch_not_first_include) << P
418 << A->getAsString(Args);
419 }
420 }
421 }
422
423 // Not translated, render as usual.
424 A->claim();
425 A->render(Args, CmdArgs);
426 }
427
428 Args.AddAllArgs(CmdArgs,
429 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
430 options::OPT_F, options::OPT_index_header_map});
431
432 // Add -Wp, and -Xpreprocessor if using the preprocessor.
433
434 // FIXME: There is a very unfortunate problem here, some troubled
435 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
436 // really support that we would have to parse and then translate
437 // those options. :(
438 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
439 options::OPT_Xpreprocessor);
440
441 // -I- is a deprecated GCC feature, reject it.
442 if (Arg *A = Args.getLastArg(options::OPT_I_))
443 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
444
445 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
446 // -isysroot to the CC1 invocation.
447 StringRef sysroot = C.getSysRoot();
448 if (sysroot != "") {
449 if (!Args.hasArg(options::OPT_isysroot)) {
450 CmdArgs.push_back("-isysroot");
451 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
452 }
453 }
454
455 // Parse additional include paths from environment variables.
456 // FIXME: We should probably sink the logic for handling these from the
457 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
458 // CPATH - included following the user specified includes (but prior to
459 // builtin and standard includes).
460 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
461 // C_INCLUDE_PATH - system includes enabled when compiling C.
462 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
463 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
464 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
465 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
466 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
467 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
468 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
469
470 // Optional AuxToolChain indicates that we need to include headers
471 // for more than one target. If that's the case, add include paths
472 // from AuxToolChain right after include paths of the same kind for
473 // the current target.
474
475 // Add C++ include arguments, if needed.
476 if (types::isCXX(Inputs[0].getType())) {
477 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
478 if (AuxToolChain)
479 AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
480 }
481
482 // Add system include arguments.
483 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
484 if (AuxToolChain)
485 AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
486
487 // Add CUDA include arguments, if needed.
488 if (types::isCuda(Inputs[0].getType()))
489 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
490 }
491
492 // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)493 static bool isSignedCharDefault(const llvm::Triple &Triple) {
494 switch (Triple.getArch()) {
495 default:
496 return true;
497
498 case llvm::Triple::aarch64:
499 case llvm::Triple::aarch64_be:
500 case llvm::Triple::arm:
501 case llvm::Triple::armeb:
502 case llvm::Triple::thumb:
503 case llvm::Triple::thumbeb:
504 if (Triple.isOSDarwin() || Triple.isOSWindows())
505 return true;
506 return false;
507
508 case llvm::Triple::ppc:
509 case llvm::Triple::ppc64:
510 if (Triple.isOSDarwin())
511 return true;
512 return false;
513
514 case llvm::Triple::hexagon:
515 case llvm::Triple::ppc64le:
516 case llvm::Triple::systemz:
517 case llvm::Triple::xcore:
518 return false;
519 }
520 }
521
isNoCommonDefault(const llvm::Triple & Triple)522 static bool isNoCommonDefault(const llvm::Triple &Triple) {
523 switch (Triple.getArch()) {
524 default:
525 return false;
526
527 case llvm::Triple::xcore:
528 case llvm::Triple::wasm32:
529 case llvm::Triple::wasm64:
530 return true;
531 }
532 }
533
534 // ARM tools start.
535
536 // Get SubArch (vN).
getARMSubArchVersionNumber(const llvm::Triple & Triple)537 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
538 llvm::StringRef Arch = Triple.getArchName();
539 return llvm::ARM::parseArchVersion(Arch);
540 }
541
542 // True if M-profile.
isARMMProfile(const llvm::Triple & Triple)543 static bool isARMMProfile(const llvm::Triple &Triple) {
544 llvm::StringRef Arch = Triple.getArchName();
545 unsigned Profile = llvm::ARM::parseArchProfile(Arch);
546 return Profile == llvm::ARM::PK_M;
547 }
548
549 // Get Arch/CPU from args.
getARMArchCPUFromArgs(const ArgList & Args,llvm::StringRef & Arch,llvm::StringRef & CPU,bool FromAs=false)550 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
551 llvm::StringRef &CPU, bool FromAs = false) {
552 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
553 CPU = A->getValue();
554 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
555 Arch = A->getValue();
556 if (!FromAs)
557 return;
558
559 for (const Arg *A :
560 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
561 StringRef Value = A->getValue();
562 if (Value.startswith("-mcpu="))
563 CPU = Value.substr(6);
564 if (Value.startswith("-march="))
565 Arch = Value.substr(7);
566 }
567 }
568
569 // Handle -mhwdiv=.
570 // FIXME: Use ARMTargetParser.
getARMHWDivFeatures(const Driver & D,const Arg * A,const ArgList & Args,StringRef HWDiv,std::vector<const char * > & Features)571 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
572 const ArgList &Args, StringRef HWDiv,
573 std::vector<const char *> &Features) {
574 unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
575 if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
576 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
577 }
578
579 // Handle -mfpu=.
getARMFPUFeatures(const Driver & D,const Arg * A,const ArgList & Args,StringRef FPU,std::vector<const char * > & Features)580 static void getARMFPUFeatures(const Driver &D, const Arg *A,
581 const ArgList &Args, StringRef FPU,
582 std::vector<const char *> &Features) {
583 unsigned FPUID = llvm::ARM::parseFPU(FPU);
584 if (!llvm::ARM::getFPUFeatures(FPUID, Features))
585 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
586 }
587
588 // Decode ARM features from string like +[no]featureA+[no]featureB+...
DecodeARMFeatures(const Driver & D,StringRef text,std::vector<const char * > & Features)589 static bool DecodeARMFeatures(const Driver &D, StringRef text,
590 std::vector<const char *> &Features) {
591 SmallVector<StringRef, 8> Split;
592 text.split(Split, StringRef("+"), -1, false);
593
594 for (StringRef Feature : Split) {
595 const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
596 if (FeatureName)
597 Features.push_back(FeatureName);
598 else
599 return false;
600 }
601 return true;
602 }
603
604 // Check if -march is valid by checking if it can be canonicalised and parsed.
605 // getARMArch is used here instead of just checking the -march value in order
606 // to handle -march=native correctly.
checkARMArchName(const Driver & D,const Arg * A,const ArgList & Args,llvm::StringRef ArchName,std::vector<const char * > & Features,const llvm::Triple & Triple)607 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
608 llvm::StringRef ArchName,
609 std::vector<const char *> &Features,
610 const llvm::Triple &Triple) {
611 std::pair<StringRef, StringRef> Split = ArchName.split("+");
612
613 std::string MArch = arm::getARMArch(ArchName, Triple);
614 if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
615 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
616 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
617 }
618
619 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
checkARMCPUName(const Driver & D,const Arg * A,const ArgList & Args,llvm::StringRef CPUName,llvm::StringRef ArchName,std::vector<const char * > & Features,const llvm::Triple & Triple)620 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
621 llvm::StringRef CPUName, llvm::StringRef ArchName,
622 std::vector<const char *> &Features,
623 const llvm::Triple &Triple) {
624 std::pair<StringRef, StringRef> Split = CPUName.split("+");
625
626 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
627 if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
628 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
629 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
630 }
631
useAAPCSForMachO(const llvm::Triple & T)632 static bool useAAPCSForMachO(const llvm::Triple &T) {
633 // The backend is hardwired to assume AAPCS for M-class processors, ensure
634 // the frontend matches that.
635 return T.getEnvironment() == llvm::Triple::EABI ||
636 T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
637 }
638
639 // Select the float ABI as determined by -msoft-float, -mhard-float, and
640 // -mfloat-abi=.
getARMFloatABI(const ToolChain & TC,const ArgList & Args)641 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
642 const Driver &D = TC.getDriver();
643 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
644 auto SubArch = getARMSubArchVersionNumber(Triple);
645 arm::FloatABI ABI = FloatABI::Invalid;
646 if (Arg *A =
647 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
648 options::OPT_mfloat_abi_EQ)) {
649 if (A->getOption().matches(options::OPT_msoft_float)) {
650 ABI = FloatABI::Soft;
651 } else if (A->getOption().matches(options::OPT_mhard_float)) {
652 ABI = FloatABI::Hard;
653 } else {
654 ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
655 .Case("soft", FloatABI::Soft)
656 .Case("softfp", FloatABI::SoftFP)
657 .Case("hard", FloatABI::Hard)
658 .Default(FloatABI::Invalid);
659 if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
660 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
661 ABI = FloatABI::Soft;
662 }
663 }
664
665 // It is incorrect to select hard float ABI on MachO platforms if the ABI is
666 // "apcs-gnu".
667 if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
668 ABI == FloatABI::Hard) {
669 D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
670 << Triple.getArchName();
671 }
672 }
673
674 // If unspecified, choose the default based on the platform.
675 if (ABI == FloatABI::Invalid) {
676 switch (Triple.getOS()) {
677 case llvm::Triple::Darwin:
678 case llvm::Triple::MacOSX:
679 case llvm::Triple::IOS:
680 case llvm::Triple::TvOS: {
681 // Darwin defaults to "softfp" for v6 and v7.
682 ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
683 break;
684 }
685 case llvm::Triple::WatchOS:
686 ABI = FloatABI::Hard;
687 break;
688
689 // FIXME: this is invalid for WindowsCE
690 case llvm::Triple::Win32:
691 ABI = FloatABI::Hard;
692 break;
693
694 case llvm::Triple::FreeBSD:
695 switch (Triple.getEnvironment()) {
696 case llvm::Triple::GNUEABIHF:
697 ABI = FloatABI::Hard;
698 break;
699 default:
700 // FreeBSD defaults to soft float
701 ABI = FloatABI::Soft;
702 break;
703 }
704 break;
705
706 default:
707 switch (Triple.getEnvironment()) {
708 case llvm::Triple::GNUEABIHF:
709 case llvm::Triple::EABIHF:
710 ABI = FloatABI::Hard;
711 break;
712 case llvm::Triple::GNUEABI:
713 case llvm::Triple::EABI:
714 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
715 ABI = FloatABI::SoftFP;
716 break;
717 case llvm::Triple::Android:
718 ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
719 break;
720 default:
721 // Assume "soft", but warn the user we are guessing.
722 ABI = FloatABI::Soft;
723 if (Triple.getOS() != llvm::Triple::UnknownOS ||
724 !Triple.isOSBinFormatMachO())
725 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
726 break;
727 }
728 }
729 }
730
731 assert(ABI != FloatABI::Invalid && "must select an ABI");
732 return ABI;
733 }
734
getARMTargetFeatures(const ToolChain & TC,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features,bool ForAS)735 static void getARMTargetFeatures(const ToolChain &TC,
736 const llvm::Triple &Triple,
737 const ArgList &Args,
738 std::vector<const char *> &Features,
739 bool ForAS) {
740 const Driver &D = TC.getDriver();
741
742 bool KernelOrKext =
743 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
744 arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
745 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
746 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
747
748 if (!ForAS) {
749 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
750 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
751 // stripped out by the ARM target. We should probably pass this a new
752 // -target-option, which is handled by the -cc1/-cc1as invocation.
753 //
754 // FIXME2: For consistency, it would be ideal if we set up the target
755 // machine state the same when using the frontend or the assembler. We don't
756 // currently do that for the assembler, we pass the options directly to the
757 // backend and never even instantiate the frontend TargetInfo. If we did,
758 // and used its handleTargetFeatures hook, then we could ensure the
759 // assembler and the frontend behave the same.
760
761 // Use software floating point operations?
762 if (ABI == arm::FloatABI::Soft)
763 Features.push_back("+soft-float");
764
765 // Use software floating point argument passing?
766 if (ABI != arm::FloatABI::Hard)
767 Features.push_back("+soft-float-abi");
768 } else {
769 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
770 // to the assembler correctly.
771 for (const Arg *A :
772 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
773 StringRef Value = A->getValue();
774 if (Value.startswith("-mfpu=")) {
775 WaFPU = A;
776 } else if (Value.startswith("-mcpu=")) {
777 WaCPU = A;
778 } else if (Value.startswith("-mhwdiv=")) {
779 WaHDiv = A;
780 } else if (Value.startswith("-march=")) {
781 WaArch = A;
782 }
783 }
784 }
785
786 // Check -march. ClangAs gives preference to -Wa,-march=.
787 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
788 StringRef ArchName;
789 if (WaArch) {
790 if (ArchArg)
791 D.Diag(clang::diag::warn_drv_unused_argument)
792 << ArchArg->getAsString(Args);
793 ArchName = StringRef(WaArch->getValue()).substr(7);
794 checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
795 // FIXME: Set Arch.
796 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
797 } else if (ArchArg) {
798 ArchName = ArchArg->getValue();
799 checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
800 }
801
802 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
803 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
804 StringRef CPUName;
805 if (WaCPU) {
806 if (CPUArg)
807 D.Diag(clang::diag::warn_drv_unused_argument)
808 << CPUArg->getAsString(Args);
809 CPUName = StringRef(WaCPU->getValue()).substr(6);
810 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
811 } else if (CPUArg) {
812 CPUName = CPUArg->getValue();
813 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
814 }
815
816 // Add CPU features for generic CPUs
817 if (CPUName == "native") {
818 llvm::StringMap<bool> HostFeatures;
819 if (llvm::sys::getHostCPUFeatures(HostFeatures))
820 for (auto &F : HostFeatures)
821 Features.push_back(
822 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
823 }
824
825 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
826 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
827 if (WaFPU) {
828 if (FPUArg)
829 D.Diag(clang::diag::warn_drv_unused_argument)
830 << FPUArg->getAsString(Args);
831 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
832 Features);
833 } else if (FPUArg) {
834 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
835 }
836
837 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
838 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
839 if (WaHDiv) {
840 if (HDivArg)
841 D.Diag(clang::diag::warn_drv_unused_argument)
842 << HDivArg->getAsString(Args);
843 getARMHWDivFeatures(D, WaHDiv, Args,
844 StringRef(WaHDiv->getValue()).substr(8), Features);
845 } else if (HDivArg)
846 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
847
848 // Setting -msoft-float effectively disables NEON because of the GCC
849 // implementation, although the same isn't true of VFP or VFP3.
850 if (ABI == arm::FloatABI::Soft) {
851 Features.push_back("-neon");
852 // Also need to explicitly disable features which imply NEON.
853 Features.push_back("-crypto");
854 }
855
856 // En/disable crc code generation.
857 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
858 if (A->getOption().matches(options::OPT_mcrc))
859 Features.push_back("+crc");
860 else
861 Features.push_back("-crc");
862 }
863
864 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
865 Features.insert(Features.begin(), "+v8.1a");
866 }
867
868 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
869 // neither options are specified, see if we are compiling for kernel/kext and
870 // decide whether to pass "+long-calls" based on the OS and its version.
871 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
872 options::OPT_mno_long_calls)) {
873 if (A->getOption().matches(options::OPT_mlong_calls))
874 Features.push_back("+long-calls");
875 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
876 !Triple.isWatchOS()) {
877 Features.push_back("+long-calls");
878 }
879
880 // Kernel code has more strict alignment requirements.
881 if (KernelOrKext)
882 Features.push_back("+strict-align");
883 else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
884 options::OPT_munaligned_access)) {
885 if (A->getOption().matches(options::OPT_munaligned_access)) {
886 // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
887 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
888 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
889 } else
890 Features.push_back("+strict-align");
891 } else {
892 // Assume pre-ARMv6 doesn't support unaligned accesses.
893 //
894 // ARMv6 may or may not support unaligned accesses depending on the
895 // SCTLR.U bit, which is architecture-specific. We assume ARMv6
896 // Darwin and NetBSD targets support unaligned accesses, and others don't.
897 //
898 // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
899 // which raises an alignment fault on unaligned accesses. Linux
900 // defaults this bit to 0 and handles it as a system-wide (not
901 // per-process) setting. It is therefore safe to assume that ARMv7+
902 // Linux targets support unaligned accesses. The same goes for NaCl.
903 //
904 // The above behavior is consistent with GCC.
905 int VersionNum = getARMSubArchVersionNumber(Triple);
906 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
907 if (VersionNum < 6 ||
908 Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
909 Features.push_back("+strict-align");
910 } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
911 if (VersionNum < 7)
912 Features.push_back("+strict-align");
913 } else
914 Features.push_back("+strict-align");
915 }
916
917 // llvm does not support reserving registers in general. There is support
918 // for reserving r9 on ARM though (defined as a platform-specific register
919 // in ARM EABI).
920 if (Args.hasArg(options::OPT_ffixed_r9))
921 Features.push_back("+reserve-r9");
922
923 // The kext linker doesn't know how to deal with movw/movt.
924 if (KernelOrKext)
925 Features.push_back("+no-movt");
926 }
927
AddARMTargetArgs(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const928 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
929 ArgStringList &CmdArgs, bool KernelOrKext) const {
930 // Select the ABI to use.
931 // FIXME: Support -meabi.
932 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
933 const char *ABIName = nullptr;
934 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
935 ABIName = A->getValue();
936 } else if (Triple.isOSBinFormatMachO()) {
937 if (useAAPCSForMachO(Triple)) {
938 ABIName = "aapcs";
939 } else if (Triple.isWatchOS()) {
940 ABIName = "aapcs16";
941 } else {
942 ABIName = "apcs-gnu";
943 }
944 } else if (Triple.isOSWindows()) {
945 // FIXME: this is invalid for WindowsCE
946 ABIName = "aapcs";
947 } else {
948 // Select the default based on the platform.
949 switch (Triple.getEnvironment()) {
950 case llvm::Triple::Android:
951 case llvm::Triple::GNUEABI:
952 case llvm::Triple::GNUEABIHF:
953 ABIName = "aapcs-linux";
954 break;
955 case llvm::Triple::EABIHF:
956 case llvm::Triple::EABI:
957 ABIName = "aapcs";
958 break;
959 default:
960 if (Triple.getOS() == llvm::Triple::NetBSD)
961 ABIName = "apcs-gnu";
962 else
963 ABIName = "aapcs";
964 break;
965 }
966 }
967 CmdArgs.push_back("-target-abi");
968 CmdArgs.push_back(ABIName);
969
970 // Determine floating point ABI from the options & target defaults.
971 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
972 if (ABI == arm::FloatABI::Soft) {
973 // Floating point operations and argument passing are soft.
974 // FIXME: This changes CPP defines, we need -target-soft-float.
975 CmdArgs.push_back("-msoft-float");
976 CmdArgs.push_back("-mfloat-abi");
977 CmdArgs.push_back("soft");
978 } else if (ABI == arm::FloatABI::SoftFP) {
979 // Floating point operations are hard, but argument passing is soft.
980 CmdArgs.push_back("-mfloat-abi");
981 CmdArgs.push_back("soft");
982 } else {
983 // Floating point operations and argument passing are hard.
984 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
985 CmdArgs.push_back("-mfloat-abi");
986 CmdArgs.push_back("hard");
987 }
988
989 // Forward the -mglobal-merge option for explicit control over the pass.
990 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
991 options::OPT_mno_global_merge)) {
992 CmdArgs.push_back("-backend-option");
993 if (A->getOption().matches(options::OPT_mno_global_merge))
994 CmdArgs.push_back("-arm-global-merge=false");
995 else
996 CmdArgs.push_back("-arm-global-merge=true");
997 }
998
999 if (!Args.hasFlag(options::OPT_mimplicit_float,
1000 options::OPT_mno_implicit_float, true))
1001 CmdArgs.push_back("-no-implicit-float");
1002 }
1003 // ARM tools end.
1004
1005 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1006 /// targeting.
getAArch64TargetCPU(const ArgList & Args)1007 static std::string getAArch64TargetCPU(const ArgList &Args) {
1008 Arg *A;
1009 std::string CPU;
1010 // If we have -mtune or -mcpu, use that.
1011 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1012 CPU = StringRef(A->getValue()).lower();
1013 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1014 StringRef Mcpu = A->getValue();
1015 CPU = Mcpu.split("+").first.lower();
1016 }
1017
1018 // Handle CPU name is 'native'.
1019 if (CPU == "native")
1020 return llvm::sys::getHostCPUName();
1021 else if (CPU.size())
1022 return CPU;
1023
1024 // Make sure we pick "cyclone" if -arch is used.
1025 // FIXME: Should this be picked by checking the target triple instead?
1026 if (Args.getLastArg(options::OPT_arch))
1027 return "cyclone";
1028
1029 return "generic";
1030 }
1031
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1032 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1033 ArgStringList &CmdArgs) const {
1034 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1035 llvm::Triple Triple(TripleStr);
1036
1037 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1038 Args.hasArg(options::OPT_mkernel) ||
1039 Args.hasArg(options::OPT_fapple_kext))
1040 CmdArgs.push_back("-disable-red-zone");
1041
1042 if (!Args.hasFlag(options::OPT_mimplicit_float,
1043 options::OPT_mno_implicit_float, true))
1044 CmdArgs.push_back("-no-implicit-float");
1045
1046 const char *ABIName = nullptr;
1047 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1048 ABIName = A->getValue();
1049 else if (Triple.isOSDarwin())
1050 ABIName = "darwinpcs";
1051 else
1052 ABIName = "aapcs";
1053
1054 CmdArgs.push_back("-target-abi");
1055 CmdArgs.push_back(ABIName);
1056
1057 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1058 options::OPT_mno_fix_cortex_a53_835769)) {
1059 CmdArgs.push_back("-backend-option");
1060 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1061 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1062 else
1063 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1064 } else if (Triple.isAndroid()) {
1065 // Enabled A53 errata (835769) workaround by default on android
1066 CmdArgs.push_back("-backend-option");
1067 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1068 }
1069
1070 // Forward the -mglobal-merge option for explicit control over the pass.
1071 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1072 options::OPT_mno_global_merge)) {
1073 CmdArgs.push_back("-backend-option");
1074 if (A->getOption().matches(options::OPT_mno_global_merge))
1075 CmdArgs.push_back("-aarch64-global-merge=false");
1076 else
1077 CmdArgs.push_back("-aarch64-global-merge=true");
1078 }
1079 }
1080
1081 // Get CPU and ABI names. They are not independent
1082 // so we have to calculate them together.
getMipsCPUAndABI(const ArgList & Args,const llvm::Triple & Triple,StringRef & CPUName,StringRef & ABIName)1083 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1084 StringRef &CPUName, StringRef &ABIName) {
1085 const char *DefMips32CPU = "mips32r2";
1086 const char *DefMips64CPU = "mips64r2";
1087
1088 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1089 // default for mips64(el)?-img-linux-gnu.
1090 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1091 Triple.getEnvironment() == llvm::Triple::GNU) {
1092 DefMips32CPU = "mips32r6";
1093 DefMips64CPU = "mips64r6";
1094 }
1095
1096 // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1097 if (Triple.isAndroid())
1098 DefMips64CPU = "mips64r6";
1099
1100 // MIPS3 is the default for mips64*-unknown-openbsd.
1101 if (Triple.getOS() == llvm::Triple::OpenBSD)
1102 DefMips64CPU = "mips3";
1103
1104 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1105 CPUName = A->getValue();
1106
1107 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1108 ABIName = A->getValue();
1109 // Convert a GNU style Mips ABI name to the name
1110 // accepted by LLVM Mips backend.
1111 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1112 .Case("32", "o32")
1113 .Case("64", "n64")
1114 .Default(ABIName);
1115 }
1116
1117 // Setup default CPU and ABI names.
1118 if (CPUName.empty() && ABIName.empty()) {
1119 switch (Triple.getArch()) {
1120 default:
1121 llvm_unreachable("Unexpected triple arch name");
1122 case llvm::Triple::mips:
1123 case llvm::Triple::mipsel:
1124 CPUName = DefMips32CPU;
1125 break;
1126 case llvm::Triple::mips64:
1127 case llvm::Triple::mips64el:
1128 CPUName = DefMips64CPU;
1129 break;
1130 }
1131 }
1132
1133 if (ABIName.empty()) {
1134 // Deduce ABI name from the target triple.
1135 if (Triple.getArch() == llvm::Triple::mips ||
1136 Triple.getArch() == llvm::Triple::mipsel)
1137 ABIName = "o32";
1138 else
1139 ABIName = "n64";
1140 }
1141
1142 if (CPUName.empty()) {
1143 // Deduce CPU name from ABI name.
1144 CPUName = llvm::StringSwitch<const char *>(ABIName)
1145 .Cases("o32", "eabi", DefMips32CPU)
1146 .Cases("n32", "n64", DefMips64CPU)
1147 .Default("");
1148 }
1149
1150 // FIXME: Warn on inconsistent use of -march and -mabi.
1151 }
1152
getMipsABILibSuffix(const ArgList & Args,const llvm::Triple & Triple)1153 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1154 const llvm::Triple &Triple) {
1155 StringRef CPUName, ABIName;
1156 tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1157 return llvm::StringSwitch<std::string>(ABIName)
1158 .Case("o32", "")
1159 .Case("n32", "32")
1160 .Case("n64", "64");
1161 }
1162
1163 // Convert ABI name to the GNU tools acceptable variant.
getGnuCompatibleMipsABIName(StringRef ABI)1164 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1165 return llvm::StringSwitch<llvm::StringRef>(ABI)
1166 .Case("o32", "32")
1167 .Case("n64", "64")
1168 .Default(ABI);
1169 }
1170
1171 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1172 // and -mfloat-abi=.
getMipsFloatABI(const Driver & D,const ArgList & Args)1173 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1174 mips::FloatABI ABI = mips::FloatABI::Invalid;
1175 if (Arg *A =
1176 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1177 options::OPT_mfloat_abi_EQ)) {
1178 if (A->getOption().matches(options::OPT_msoft_float))
1179 ABI = mips::FloatABI::Soft;
1180 else if (A->getOption().matches(options::OPT_mhard_float))
1181 ABI = mips::FloatABI::Hard;
1182 else {
1183 ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1184 .Case("soft", mips::FloatABI::Soft)
1185 .Case("hard", mips::FloatABI::Hard)
1186 .Default(mips::FloatABI::Invalid);
1187 if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1188 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1189 ABI = mips::FloatABI::Hard;
1190 }
1191 }
1192 }
1193
1194 // If unspecified, choose the default based on the platform.
1195 if (ABI == mips::FloatABI::Invalid) {
1196 // Assume "hard", because it's a default value used by gcc.
1197 // When we start to recognize specific target MIPS processors,
1198 // we will be able to select the default more correctly.
1199 ABI = mips::FloatABI::Hard;
1200 }
1201
1202 assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1203 return ABI;
1204 }
1205
AddTargetFeature(const ArgList & Args,std::vector<const char * > & Features,OptSpecifier OnOpt,OptSpecifier OffOpt,StringRef FeatureName)1206 static void AddTargetFeature(const ArgList &Args,
1207 std::vector<const char *> &Features,
1208 OptSpecifier OnOpt, OptSpecifier OffOpt,
1209 StringRef FeatureName) {
1210 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1211 if (A->getOption().matches(OnOpt))
1212 Features.push_back(Args.MakeArgString("+" + FeatureName));
1213 else
1214 Features.push_back(Args.MakeArgString("-" + FeatureName));
1215 }
1216 }
1217
getMIPSTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)1218 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1219 const ArgList &Args,
1220 std::vector<const char *> &Features) {
1221 StringRef CPUName;
1222 StringRef ABIName;
1223 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1224 ABIName = getGnuCompatibleMipsABIName(ABIName);
1225
1226 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1227 options::OPT_mabicalls, "noabicalls");
1228
1229 mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1230 if (FloatABI == mips::FloatABI::Soft) {
1231 // FIXME: Note, this is a hack. We need to pass the selected float
1232 // mode to the MipsTargetInfoBase to define appropriate macros there.
1233 // Now it is the only method.
1234 Features.push_back("+soft-float");
1235 }
1236
1237 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1238 StringRef Val = StringRef(A->getValue());
1239 if (Val == "2008") {
1240 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1241 Features.push_back("+nan2008");
1242 else {
1243 Features.push_back("-nan2008");
1244 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1245 }
1246 } else if (Val == "legacy") {
1247 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1248 Features.push_back("-nan2008");
1249 else {
1250 Features.push_back("+nan2008");
1251 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1252 }
1253 } else
1254 D.Diag(diag::err_drv_unsupported_option_argument)
1255 << A->getOption().getName() << Val;
1256 }
1257
1258 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1259 options::OPT_mdouble_float, "single-float");
1260 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1261 "mips16");
1262 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1263 options::OPT_mno_micromips, "micromips");
1264 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1265 "dsp");
1266 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1267 "dspr2");
1268 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1269 "msa");
1270
1271 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1272 // pass -mfpxx
1273 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1274 options::OPT_mfp64)) {
1275 if (A->getOption().matches(options::OPT_mfp32))
1276 Features.push_back(Args.MakeArgString("-fp64"));
1277 else if (A->getOption().matches(options::OPT_mfpxx)) {
1278 Features.push_back(Args.MakeArgString("+fpxx"));
1279 Features.push_back(Args.MakeArgString("+nooddspreg"));
1280 } else
1281 Features.push_back(Args.MakeArgString("+fp64"));
1282 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1283 Features.push_back(Args.MakeArgString("+fpxx"));
1284 Features.push_back(Args.MakeArgString("+nooddspreg"));
1285 }
1286
1287 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1288 options::OPT_modd_spreg, "nooddspreg");
1289 }
1290
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1291 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1292 ArgStringList &CmdArgs) const {
1293 const Driver &D = getToolChain().getDriver();
1294 StringRef CPUName;
1295 StringRef ABIName;
1296 const llvm::Triple &Triple = getToolChain().getTriple();
1297 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1298
1299 CmdArgs.push_back("-target-abi");
1300 CmdArgs.push_back(ABIName.data());
1301
1302 mips::FloatABI ABI = getMipsFloatABI(D, Args);
1303 if (ABI == mips::FloatABI::Soft) {
1304 // Floating point operations and argument passing are soft.
1305 CmdArgs.push_back("-msoft-float");
1306 CmdArgs.push_back("-mfloat-abi");
1307 CmdArgs.push_back("soft");
1308 } else {
1309 // Floating point operations and argument passing are hard.
1310 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1311 CmdArgs.push_back("-mfloat-abi");
1312 CmdArgs.push_back("hard");
1313 }
1314
1315 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1316 if (A->getOption().matches(options::OPT_mxgot)) {
1317 CmdArgs.push_back("-mllvm");
1318 CmdArgs.push_back("-mxgot");
1319 }
1320 }
1321
1322 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1323 options::OPT_mno_ldc1_sdc1)) {
1324 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1325 CmdArgs.push_back("-mllvm");
1326 CmdArgs.push_back("-mno-ldc1-sdc1");
1327 }
1328 }
1329
1330 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1331 options::OPT_mno_check_zero_division)) {
1332 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1333 CmdArgs.push_back("-mllvm");
1334 CmdArgs.push_back("-mno-check-zero-division");
1335 }
1336 }
1337
1338 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1339 StringRef v = A->getValue();
1340 CmdArgs.push_back("-mllvm");
1341 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1342 A->claim();
1343 }
1344 }
1345
1346 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
getPPCTargetCPU(const ArgList & Args)1347 static std::string getPPCTargetCPU(const ArgList &Args) {
1348 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1349 StringRef CPUName = A->getValue();
1350
1351 if (CPUName == "native") {
1352 std::string CPU = llvm::sys::getHostCPUName();
1353 if (!CPU.empty() && CPU != "generic")
1354 return CPU;
1355 else
1356 return "";
1357 }
1358
1359 return llvm::StringSwitch<const char *>(CPUName)
1360 .Case("common", "generic")
1361 .Case("440", "440")
1362 .Case("440fp", "440")
1363 .Case("450", "450")
1364 .Case("601", "601")
1365 .Case("602", "602")
1366 .Case("603", "603")
1367 .Case("603e", "603e")
1368 .Case("603ev", "603ev")
1369 .Case("604", "604")
1370 .Case("604e", "604e")
1371 .Case("620", "620")
1372 .Case("630", "pwr3")
1373 .Case("G3", "g3")
1374 .Case("7400", "7400")
1375 .Case("G4", "g4")
1376 .Case("7450", "7450")
1377 .Case("G4+", "g4+")
1378 .Case("750", "750")
1379 .Case("970", "970")
1380 .Case("G5", "g5")
1381 .Case("a2", "a2")
1382 .Case("a2q", "a2q")
1383 .Case("e500mc", "e500mc")
1384 .Case("e5500", "e5500")
1385 .Case("power3", "pwr3")
1386 .Case("power4", "pwr4")
1387 .Case("power5", "pwr5")
1388 .Case("power5x", "pwr5x")
1389 .Case("power6", "pwr6")
1390 .Case("power6x", "pwr6x")
1391 .Case("power7", "pwr7")
1392 .Case("power8", "pwr8")
1393 .Case("pwr3", "pwr3")
1394 .Case("pwr4", "pwr4")
1395 .Case("pwr5", "pwr5")
1396 .Case("pwr5x", "pwr5x")
1397 .Case("pwr6", "pwr6")
1398 .Case("pwr6x", "pwr6x")
1399 .Case("pwr7", "pwr7")
1400 .Case("pwr8", "pwr8")
1401 .Case("powerpc", "ppc")
1402 .Case("powerpc64", "ppc64")
1403 .Case("powerpc64le", "ppc64le")
1404 .Default("");
1405 }
1406
1407 return "";
1408 }
1409
getPPCTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)1410 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1411 const ArgList &Args,
1412 std::vector<const char *> &Features) {
1413 for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
1414 StringRef Name = A->getOption().getName();
1415 A->claim();
1416
1417 // Skip over "-m".
1418 assert(Name.startswith("m") && "Invalid feature name.");
1419 Name = Name.substr(1);
1420
1421 bool IsNegative = Name.startswith("no-");
1422 if (IsNegative)
1423 Name = Name.substr(3);
1424 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1425 }
1426
1427 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1428 if (FloatABI == ppc::FloatABI::Soft &&
1429 !(Triple.getArch() == llvm::Triple::ppc64 ||
1430 Triple.getArch() == llvm::Triple::ppc64le))
1431 Features.push_back("+soft-float");
1432 else if (FloatABI == ppc::FloatABI::Soft &&
1433 (Triple.getArch() == llvm::Triple::ppc64 ||
1434 Triple.getArch() == llvm::Triple::ppc64le))
1435 D.Diag(diag::err_drv_invalid_mfloat_abi)
1436 << "soft float is not supported for ppc64";
1437
1438 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1439 AddTargetFeature(Args, Features, options::OPT_faltivec,
1440 options::OPT_fno_altivec, "altivec");
1441 }
1442
getPPCFloatABI(const Driver & D,const ArgList & Args)1443 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1444 ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1445 if (Arg *A =
1446 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1447 options::OPT_mfloat_abi_EQ)) {
1448 if (A->getOption().matches(options::OPT_msoft_float))
1449 ABI = ppc::FloatABI::Soft;
1450 else if (A->getOption().matches(options::OPT_mhard_float))
1451 ABI = ppc::FloatABI::Hard;
1452 else {
1453 ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1454 .Case("soft", ppc::FloatABI::Soft)
1455 .Case("hard", ppc::FloatABI::Hard)
1456 .Default(ppc::FloatABI::Invalid);
1457 if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1458 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1459 ABI = ppc::FloatABI::Hard;
1460 }
1461 }
1462 }
1463
1464 // If unspecified, choose the default based on the platform.
1465 if (ABI == ppc::FloatABI::Invalid) {
1466 ABI = ppc::FloatABI::Hard;
1467 }
1468
1469 return ABI;
1470 }
1471
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1472 void Clang::AddPPCTargetArgs(const ArgList &Args,
1473 ArgStringList &CmdArgs) const {
1474 // Select the ABI to use.
1475 const char *ABIName = nullptr;
1476 if (getToolChain().getTriple().isOSLinux())
1477 switch (getToolChain().getArch()) {
1478 case llvm::Triple::ppc64: {
1479 // When targeting a processor that supports QPX, or if QPX is
1480 // specifically enabled, default to using the ABI that supports QPX (so
1481 // long as it is not specifically disabled).
1482 bool HasQPX = false;
1483 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1484 HasQPX = A->getValue() == StringRef("a2q");
1485 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1486 if (HasQPX) {
1487 ABIName = "elfv1-qpx";
1488 break;
1489 }
1490
1491 ABIName = "elfv1";
1492 break;
1493 }
1494 case llvm::Triple::ppc64le:
1495 ABIName = "elfv2";
1496 break;
1497 default:
1498 break;
1499 }
1500
1501 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1502 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1503 // the option if given as we don't have backend support for any targets
1504 // that don't use the altivec abi.
1505 if (StringRef(A->getValue()) != "altivec")
1506 ABIName = A->getValue();
1507
1508 ppc::FloatABI FloatABI =
1509 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1510
1511 if (FloatABI == ppc::FloatABI::Soft) {
1512 // Floating point operations and argument passing are soft.
1513 CmdArgs.push_back("-msoft-float");
1514 CmdArgs.push_back("-mfloat-abi");
1515 CmdArgs.push_back("soft");
1516 } else {
1517 // Floating point operations and argument passing are hard.
1518 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1519 CmdArgs.push_back("-mfloat-abi");
1520 CmdArgs.push_back("hard");
1521 }
1522
1523 if (ABIName) {
1524 CmdArgs.push_back("-target-abi");
1525 CmdArgs.push_back(ABIName);
1526 }
1527 }
1528
hasPPCAbiArg(const ArgList & Args,const char * Value)1529 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1530 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1531 return A && (A->getValue() == StringRef(Value));
1532 }
1533
1534 /// Get the (LLVM) name of the R600 gpu we are targeting.
getR600TargetGPU(const ArgList & Args)1535 static std::string getR600TargetGPU(const ArgList &Args) {
1536 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1537 const char *GPUName = A->getValue();
1538 return llvm::StringSwitch<const char *>(GPUName)
1539 .Cases("rv630", "rv635", "r600")
1540 .Cases("rv610", "rv620", "rs780", "rs880")
1541 .Case("rv740", "rv770")
1542 .Case("palm", "cedar")
1543 .Cases("sumo", "sumo2", "sumo")
1544 .Case("hemlock", "cypress")
1545 .Case("aruba", "cayman")
1546 .Default(GPUName);
1547 }
1548 return "";
1549 }
1550
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1551 void Clang::AddSparcTargetArgs(const ArgList &Args,
1552 ArgStringList &CmdArgs) const {
1553 const Driver &D = getToolChain().getDriver();
1554 std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1555
1556 bool SoftFloatABI = false;
1557 if (Arg *A =
1558 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1559 if (A->getOption().matches(options::OPT_msoft_float))
1560 SoftFloatABI = true;
1561 }
1562
1563 // Only the hard-float ABI on Sparc is standardized, and it is the
1564 // default. GCC also supports a nonstandard soft-float ABI mode, and
1565 // perhaps LLVM should implement that, too. However, since llvm
1566 // currently does not support Sparc soft-float, at all, display an
1567 // error if it's requested.
1568 if (SoftFloatABI) {
1569 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1570 << Triple;
1571 }
1572 }
1573
getSystemZTargetCPU(const ArgList & Args)1574 static const char *getSystemZTargetCPU(const ArgList &Args) {
1575 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1576 return A->getValue();
1577 return "z10";
1578 }
1579
getSystemZTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)1580 static void getSystemZTargetFeatures(const ArgList &Args,
1581 std::vector<const char *> &Features) {
1582 // -m(no-)htm overrides use of the transactional-execution facility.
1583 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1584 if (A->getOption().matches(options::OPT_mhtm))
1585 Features.push_back("+transactional-execution");
1586 else
1587 Features.push_back("-transactional-execution");
1588 }
1589 // -m(no-)vx overrides use of the vector facility.
1590 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1591 if (A->getOption().matches(options::OPT_mvx))
1592 Features.push_back("+vector");
1593 else
1594 Features.push_back("-vector");
1595 }
1596 }
1597
getX86TargetCPU(const ArgList & Args,const llvm::Triple & Triple)1598 static const char *getX86TargetCPU(const ArgList &Args,
1599 const llvm::Triple &Triple) {
1600 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1601 if (StringRef(A->getValue()) != "native") {
1602 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1603 return "core-avx2";
1604
1605 return A->getValue();
1606 }
1607
1608 // FIXME: Reject attempts to use -march=native unless the target matches
1609 // the host.
1610 //
1611 // FIXME: We should also incorporate the detected target features for use
1612 // with -native.
1613 std::string CPU = llvm::sys::getHostCPUName();
1614 if (!CPU.empty() && CPU != "generic")
1615 return Args.MakeArgString(CPU);
1616 }
1617
1618 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1619 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1620 StringRef Arch = A->getValue();
1621 const char *CPU;
1622 if (Triple.getArch() == llvm::Triple::x86) {
1623 CPU = llvm::StringSwitch<const char *>(Arch)
1624 .Case("IA32", "i386")
1625 .Case("SSE", "pentium3")
1626 .Case("SSE2", "pentium4")
1627 .Case("AVX", "sandybridge")
1628 .Case("AVX2", "haswell")
1629 .Default(nullptr);
1630 } else {
1631 CPU = llvm::StringSwitch<const char *>(Arch)
1632 .Case("AVX", "sandybridge")
1633 .Case("AVX2", "haswell")
1634 .Default(nullptr);
1635 }
1636 if (CPU)
1637 return CPU;
1638 }
1639
1640 // Select the default CPU if none was given (or detection failed).
1641
1642 if (Triple.getArch() != llvm::Triple::x86_64 &&
1643 Triple.getArch() != llvm::Triple::x86)
1644 return nullptr; // This routine is only handling x86 targets.
1645
1646 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1647
1648 // FIXME: Need target hooks.
1649 if (Triple.isOSDarwin()) {
1650 if (Triple.getArchName() == "x86_64h")
1651 return "core-avx2";
1652 return Is64Bit ? "core2" : "yonah";
1653 }
1654
1655 // Set up default CPU name for PS4 compilers.
1656 if (Triple.isPS4CPU())
1657 return "btver2";
1658
1659 // On Android use targets compatible with gcc
1660 if (Triple.isAndroid())
1661 return Is64Bit ? "x86-64" : "i686";
1662
1663 // Everything else goes to x86-64 in 64-bit mode.
1664 if (Is64Bit)
1665 return "x86-64";
1666
1667 switch (Triple.getOS()) {
1668 case llvm::Triple::FreeBSD:
1669 case llvm::Triple::NetBSD:
1670 case llvm::Triple::OpenBSD:
1671 return "i486";
1672 case llvm::Triple::Haiku:
1673 return "i586";
1674 case llvm::Triple::Bitrig:
1675 return "i686";
1676 default:
1677 // Fallback to p4.
1678 return "pentium4";
1679 }
1680 }
1681
1682 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
getWebAssemblyTargetCPU(const ArgList & Args)1683 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1684 // If we have -mcpu=, use that.
1685 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1686 StringRef CPU = A->getValue();
1687
1688 #ifdef __wasm__
1689 // Handle "native" by examining the host. "native" isn't meaningful when
1690 // cross compiling, so only support this when the host is also WebAssembly.
1691 if (CPU == "native")
1692 return llvm::sys::getHostCPUName();
1693 #endif
1694
1695 return CPU;
1696 }
1697
1698 return "generic";
1699 }
1700
getCPUName(const ArgList & Args,const llvm::Triple & T,bool FromAs=false)1701 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1702 bool FromAs = false) {
1703 switch (T.getArch()) {
1704 default:
1705 return "";
1706
1707 case llvm::Triple::aarch64:
1708 case llvm::Triple::aarch64_be:
1709 return getAArch64TargetCPU(Args);
1710
1711 case llvm::Triple::arm:
1712 case llvm::Triple::armeb:
1713 case llvm::Triple::thumb:
1714 case llvm::Triple::thumbeb: {
1715 StringRef MArch, MCPU;
1716 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1717 return arm::getARMTargetCPU(MCPU, MArch, T);
1718 }
1719 case llvm::Triple::mips:
1720 case llvm::Triple::mipsel:
1721 case llvm::Triple::mips64:
1722 case llvm::Triple::mips64el: {
1723 StringRef CPUName;
1724 StringRef ABIName;
1725 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1726 return CPUName;
1727 }
1728
1729 case llvm::Triple::nvptx:
1730 case llvm::Triple::nvptx64:
1731 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1732 return A->getValue();
1733 return "";
1734
1735 case llvm::Triple::ppc:
1736 case llvm::Triple::ppc64:
1737 case llvm::Triple::ppc64le: {
1738 std::string TargetCPUName = getPPCTargetCPU(Args);
1739 // LLVM may default to generating code for the native CPU,
1740 // but, like gcc, we default to a more generic option for
1741 // each architecture. (except on Darwin)
1742 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1743 if (T.getArch() == llvm::Triple::ppc64)
1744 TargetCPUName = "ppc64";
1745 else if (T.getArch() == llvm::Triple::ppc64le)
1746 TargetCPUName = "ppc64le";
1747 else
1748 TargetCPUName = "ppc";
1749 }
1750 return TargetCPUName;
1751 }
1752
1753 case llvm::Triple::sparc:
1754 case llvm::Triple::sparcel:
1755 case llvm::Triple::sparcv9:
1756 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1757 return A->getValue();
1758 return "";
1759
1760 case llvm::Triple::x86:
1761 case llvm::Triple::x86_64:
1762 return getX86TargetCPU(Args, T);
1763
1764 case llvm::Triple::hexagon:
1765 return "hexagon" +
1766 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1767
1768 case llvm::Triple::systemz:
1769 return getSystemZTargetCPU(Args);
1770
1771 case llvm::Triple::r600:
1772 case llvm::Triple::amdgcn:
1773 return getR600TargetGPU(Args);
1774
1775 case llvm::Triple::wasm32:
1776 case llvm::Triple::wasm64:
1777 return getWebAssemblyTargetCPU(Args);
1778 }
1779 }
1780
AddGoldPlugin(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs,bool IsThinLTO)1781 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1782 ArgStringList &CmdArgs, bool IsThinLTO) {
1783 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1784 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1785 // forward.
1786 CmdArgs.push_back("-plugin");
1787 std::string Plugin =
1788 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1789 CmdArgs.push_back(Args.MakeArgString(Plugin));
1790
1791 // Try to pass driver level flags relevant to LTO code generation down to
1792 // the plugin.
1793
1794 // Handle flags for selecting CPU variants.
1795 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1796 if (!CPU.empty())
1797 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1798
1799 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1800 StringRef OOpt;
1801 if (A->getOption().matches(options::OPT_O4) ||
1802 A->getOption().matches(options::OPT_Ofast))
1803 OOpt = "3";
1804 else if (A->getOption().matches(options::OPT_O))
1805 OOpt = A->getValue();
1806 else if (A->getOption().matches(options::OPT_O0))
1807 OOpt = "0";
1808 if (!OOpt.empty())
1809 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
1810 }
1811
1812 if (IsThinLTO)
1813 CmdArgs.push_back("-plugin-opt=thinlto");
1814 }
1815
1816 /// This is a helper function for validating the optional refinement step
1817 /// parameter in reciprocal argument strings. Return false if there is an error
1818 /// parsing the refinement step. Otherwise, return true and set the Position
1819 /// of the refinement step in the input string.
getRefinementStep(StringRef In,const Driver & D,const Arg & A,size_t & Position)1820 static bool getRefinementStep(StringRef In, const Driver &D,
1821 const Arg &A, size_t &Position) {
1822 const char RefinementStepToken = ':';
1823 Position = In.find(RefinementStepToken);
1824 if (Position != StringRef::npos) {
1825 StringRef Option = A.getOption().getName();
1826 StringRef RefStep = In.substr(Position + 1);
1827 // Allow exactly one numeric character for the additional refinement
1828 // step parameter. This is reasonable for all currently-supported
1829 // operations and architectures because we would expect that a larger value
1830 // of refinement steps would cause the estimate "optimization" to
1831 // under-perform the native operation. Also, if the estimate does not
1832 // converge quickly, it probably will not ever converge, so further
1833 // refinement steps will not produce a better answer.
1834 if (RefStep.size() != 1) {
1835 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1836 return false;
1837 }
1838 char RefStepChar = RefStep[0];
1839 if (RefStepChar < '0' || RefStepChar > '9') {
1840 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1841 return false;
1842 }
1843 }
1844 return true;
1845 }
1846
1847 /// The -mrecip flag requires processing of many optional parameters.
ParseMRecip(const Driver & D,const ArgList & Args,ArgStringList & OutStrings)1848 static void ParseMRecip(const Driver &D, const ArgList &Args,
1849 ArgStringList &OutStrings) {
1850 StringRef DisabledPrefixIn = "!";
1851 StringRef DisabledPrefixOut = "!";
1852 StringRef EnabledPrefixOut = "";
1853 StringRef Out = "-mrecip=";
1854
1855 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1856 if (!A)
1857 return;
1858
1859 unsigned NumOptions = A->getNumValues();
1860 if (NumOptions == 0) {
1861 // No option is the same as "all".
1862 OutStrings.push_back(Args.MakeArgString(Out + "all"));
1863 return;
1864 }
1865
1866 // Pass through "all", "none", or "default" with an optional refinement step.
1867 if (NumOptions == 1) {
1868 StringRef Val = A->getValue(0);
1869 size_t RefStepLoc;
1870 if (!getRefinementStep(Val, D, *A, RefStepLoc))
1871 return;
1872 StringRef ValBase = Val.slice(0, RefStepLoc);
1873 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1874 OutStrings.push_back(Args.MakeArgString(Out + Val));
1875 return;
1876 }
1877 }
1878
1879 // Each reciprocal type may be enabled or disabled individually.
1880 // Check each input value for validity, concatenate them all back together,
1881 // and pass through.
1882
1883 llvm::StringMap<bool> OptionStrings;
1884 OptionStrings.insert(std::make_pair("divd", false));
1885 OptionStrings.insert(std::make_pair("divf", false));
1886 OptionStrings.insert(std::make_pair("vec-divd", false));
1887 OptionStrings.insert(std::make_pair("vec-divf", false));
1888 OptionStrings.insert(std::make_pair("sqrtd", false));
1889 OptionStrings.insert(std::make_pair("sqrtf", false));
1890 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1891 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1892
1893 for (unsigned i = 0; i != NumOptions; ++i) {
1894 StringRef Val = A->getValue(i);
1895
1896 bool IsDisabled = Val.startswith(DisabledPrefixIn);
1897 // Ignore the disablement token for string matching.
1898 if (IsDisabled)
1899 Val = Val.substr(1);
1900
1901 size_t RefStep;
1902 if (!getRefinementStep(Val, D, *A, RefStep))
1903 return;
1904
1905 StringRef ValBase = Val.slice(0, RefStep);
1906 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1907 if (OptionIter == OptionStrings.end()) {
1908 // Try again specifying float suffix.
1909 OptionIter = OptionStrings.find(ValBase.str() + 'f');
1910 if (OptionIter == OptionStrings.end()) {
1911 // The input name did not match any known option string.
1912 D.Diag(diag::err_drv_unknown_argument) << Val;
1913 return;
1914 }
1915 // The option was specified without a float or double suffix.
1916 // Make sure that the double entry was not already specified.
1917 // The float entry will be checked below.
1918 if (OptionStrings[ValBase.str() + 'd']) {
1919 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1920 return;
1921 }
1922 }
1923
1924 if (OptionIter->second == true) {
1925 // Duplicate option specified.
1926 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1927 return;
1928 }
1929
1930 // Mark the matched option as found. Do not allow duplicate specifiers.
1931 OptionIter->second = true;
1932
1933 // If the precision was not specified, also mark the double entry as found.
1934 if (ValBase.back() != 'f' && ValBase.back() != 'd')
1935 OptionStrings[ValBase.str() + 'd'] = true;
1936
1937 // Build the output string.
1938 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1939 Out = Args.MakeArgString(Out + Prefix + Val);
1940 if (i != NumOptions - 1)
1941 Out = Args.MakeArgString(Out + ",");
1942 }
1943
1944 OutStrings.push_back(Args.MakeArgString(Out));
1945 }
1946
getX86TargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)1947 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1948 const ArgList &Args,
1949 std::vector<const char *> &Features) {
1950 // If -march=native, autodetect the feature list.
1951 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1952 if (StringRef(A->getValue()) == "native") {
1953 llvm::StringMap<bool> HostFeatures;
1954 if (llvm::sys::getHostCPUFeatures(HostFeatures))
1955 for (auto &F : HostFeatures)
1956 Features.push_back(
1957 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1958 }
1959 }
1960
1961 if (Triple.getArchName() == "x86_64h") {
1962 // x86_64h implies quite a few of the more modern subtarget features
1963 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1964 Features.push_back("-rdrnd");
1965 Features.push_back("-aes");
1966 Features.push_back("-pclmul");
1967 Features.push_back("-rtm");
1968 Features.push_back("-hle");
1969 Features.push_back("-fsgsbase");
1970 }
1971
1972 const llvm::Triple::ArchType ArchType = Triple.getArch();
1973 // Add features to be compatible with gcc for Android.
1974 if (Triple.isAndroid()) {
1975 if (ArchType == llvm::Triple::x86_64) {
1976 Features.push_back("+sse4.2");
1977 Features.push_back("+popcnt");
1978 } else
1979 Features.push_back("+ssse3");
1980 }
1981
1982 // Set features according to the -arch flag on MSVC.
1983 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1984 StringRef Arch = A->getValue();
1985 bool ArchUsed = false;
1986 // First, look for flags that are shared in x86 and x86-64.
1987 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1988 if (Arch == "AVX" || Arch == "AVX2") {
1989 ArchUsed = true;
1990 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1991 }
1992 }
1993 // Then, look for x86-specific flags.
1994 if (ArchType == llvm::Triple::x86) {
1995 if (Arch == "IA32") {
1996 ArchUsed = true;
1997 } else if (Arch == "SSE" || Arch == "SSE2") {
1998 ArchUsed = true;
1999 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2000 }
2001 }
2002 if (!ArchUsed)
2003 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2004 }
2005
2006 // Now add any that the user explicitly requested on the command line,
2007 // which may override the defaults.
2008 for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
2009 StringRef Name = A->getOption().getName();
2010 A->claim();
2011
2012 // Skip over "-m".
2013 assert(Name.startswith("m") && "Invalid feature name.");
2014 Name = Name.substr(1);
2015
2016 bool IsNegative = Name.startswith("no-");
2017 if (IsNegative)
2018 Name = Name.substr(3);
2019
2020 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
2021 }
2022 }
2023
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2024 void Clang::AddX86TargetArgs(const ArgList &Args,
2025 ArgStringList &CmdArgs) const {
2026 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2027 Args.hasArg(options::OPT_mkernel) ||
2028 Args.hasArg(options::OPT_fapple_kext))
2029 CmdArgs.push_back("-disable-red-zone");
2030
2031 // Default to avoid implicit floating-point for kernel/kext code, but allow
2032 // that to be overridden with -mno-soft-float.
2033 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2034 Args.hasArg(options::OPT_fapple_kext));
2035 if (Arg *A = Args.getLastArg(
2036 options::OPT_msoft_float, options::OPT_mno_soft_float,
2037 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2038 const Option &O = A->getOption();
2039 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2040 O.matches(options::OPT_msoft_float));
2041 }
2042 if (NoImplicitFloat)
2043 CmdArgs.push_back("-no-implicit-float");
2044
2045 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2046 StringRef Value = A->getValue();
2047 if (Value == "intel" || Value == "att") {
2048 CmdArgs.push_back("-mllvm");
2049 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2050 } else {
2051 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2052 << A->getOption().getName() << Value;
2053 }
2054 }
2055 }
2056
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2057 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2058 ArgStringList &CmdArgs) const {
2059 CmdArgs.push_back("-mqdsp6-compat");
2060 CmdArgs.push_back("-Wreturn-type");
2061
2062 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2063 std::string N = llvm::utostr(G.getValue());
2064 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2065 CmdArgs.push_back("-mllvm");
2066 CmdArgs.push_back(Args.MakeArgString(Opt));
2067 }
2068
2069 if (!Args.hasArg(options::OPT_fno_short_enums))
2070 CmdArgs.push_back("-fshort-enums");
2071 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2072 CmdArgs.push_back("-mllvm");
2073 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2074 }
2075 CmdArgs.push_back("-mllvm");
2076 CmdArgs.push_back("-machine-sink-split=0");
2077 }
2078
2079 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
DecodeAArch64Features(const Driver & D,StringRef text,std::vector<const char * > & Features)2080 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2081 std::vector<const char *> &Features) {
2082 SmallVector<StringRef, 8> Split;
2083 text.split(Split, StringRef("+"), -1, false);
2084
2085 for (StringRef Feature : Split) {
2086 const char *result = llvm::StringSwitch<const char *>(Feature)
2087 .Case("fp", "+fp-armv8")
2088 .Case("simd", "+neon")
2089 .Case("crc", "+crc")
2090 .Case("crypto", "+crypto")
2091 .Case("fp16", "+fullfp16")
2092 .Case("profile", "+spe")
2093 .Case("nofp", "-fp-armv8")
2094 .Case("nosimd", "-neon")
2095 .Case("nocrc", "-crc")
2096 .Case("nocrypto", "-crypto")
2097 .Case("nofp16", "-fullfp16")
2098 .Case("noprofile", "-spe")
2099 .Default(nullptr);
2100 if (result)
2101 Features.push_back(result);
2102 else if (Feature == "neon" || Feature == "noneon")
2103 D.Diag(diag::err_drv_no_neon_modifier);
2104 else
2105 return false;
2106 }
2107 return true;
2108 }
2109
2110 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2111 // decode CPU and feature.
DecodeAArch64Mcpu(const Driver & D,StringRef Mcpu,StringRef & CPU,std::vector<const char * > & Features)2112 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2113 std::vector<const char *> &Features) {
2114 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2115 CPU = Split.first;
2116 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
2117 CPU == "cortex-a72" || CPU == "cortex-a35") {
2118 Features.push_back("+neon");
2119 Features.push_back("+crc");
2120 Features.push_back("+crypto");
2121 } else if (CPU == "generic") {
2122 Features.push_back("+neon");
2123 } else {
2124 return false;
2125 }
2126
2127 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2128 return false;
2129
2130 return true;
2131 }
2132
2133 static bool
getAArch64ArchFeaturesFromMarch(const Driver & D,StringRef March,const ArgList & Args,std::vector<const char * > & Features)2134 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2135 const ArgList &Args,
2136 std::vector<const char *> &Features) {
2137 std::string MarchLowerCase = March.lower();
2138 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2139
2140 if (Split.first == "armv8-a" || Split.first == "armv8a") {
2141 // ok, no additional features.
2142 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2143 Features.push_back("+v8.1a");
2144 } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2145 Features.push_back("+v8.2a");
2146 } else {
2147 return false;
2148 }
2149
2150 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2151 return false;
2152
2153 return true;
2154 }
2155
2156 static bool
getAArch64ArchFeaturesFromMcpu(const Driver & D,StringRef Mcpu,const ArgList & Args,std::vector<const char * > & Features)2157 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2158 const ArgList &Args,
2159 std::vector<const char *> &Features) {
2160 StringRef CPU;
2161 std::string McpuLowerCase = Mcpu.lower();
2162 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2163 return false;
2164
2165 return true;
2166 }
2167
2168 static bool
getAArch64MicroArchFeaturesFromMtune(const Driver & D,StringRef Mtune,const ArgList & Args,std::vector<const char * > & Features)2169 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2170 const ArgList &Args,
2171 std::vector<const char *> &Features) {
2172 std::string MtuneLowerCase = Mtune.lower();
2173 // Handle CPU name is 'native'.
2174 if (MtuneLowerCase == "native")
2175 MtuneLowerCase = llvm::sys::getHostCPUName();
2176 if (MtuneLowerCase == "cyclone") {
2177 Features.push_back("+zcm");
2178 Features.push_back("+zcz");
2179 }
2180 return true;
2181 }
2182
2183 static bool
getAArch64MicroArchFeaturesFromMcpu(const Driver & D,StringRef Mcpu,const ArgList & Args,std::vector<const char * > & Features)2184 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2185 const ArgList &Args,
2186 std::vector<const char *> &Features) {
2187 StringRef CPU;
2188 std::vector<const char *> DecodedFeature;
2189 std::string McpuLowerCase = Mcpu.lower();
2190 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2191 return false;
2192
2193 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2194 }
2195
getAArch64TargetFeatures(const Driver & D,const ArgList & Args,std::vector<const char * > & Features)2196 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2197 std::vector<const char *> &Features) {
2198 Arg *A;
2199 bool success = true;
2200 // Enable NEON by default.
2201 Features.push_back("+neon");
2202 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2203 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2204 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2205 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2206 else if (Args.hasArg(options::OPT_arch))
2207 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2208 Features);
2209
2210 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2211 success =
2212 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2213 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2214 success =
2215 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2216 else if (Args.hasArg(options::OPT_arch))
2217 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2218 Args, Features);
2219
2220 if (!success)
2221 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2222
2223 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2224 Features.push_back("-fp-armv8");
2225 Features.push_back("-crypto");
2226 Features.push_back("-neon");
2227 }
2228
2229 // En/disable crc
2230 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2231 if (A->getOption().matches(options::OPT_mcrc))
2232 Features.push_back("+crc");
2233 else
2234 Features.push_back("-crc");
2235 }
2236
2237 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2238 options::OPT_munaligned_access))
2239 if (A->getOption().matches(options::OPT_mno_unaligned_access))
2240 Features.push_back("+strict-align");
2241
2242 if (Args.hasArg(options::OPT_ffixed_x18))
2243 Features.push_back("+reserve-x18");
2244 }
2245
getHexagonTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)2246 static void getHexagonTargetFeatures(const ArgList &Args,
2247 std::vector<const char *> &Features) {
2248 bool HasHVX = false, HasHVXD = false;
2249
2250 for (auto &A : Args) {
2251 auto &Opt = A->getOption();
2252 if (Opt.matches(options::OPT_mhexagon_hvx))
2253 HasHVX = true;
2254 else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2255 HasHVXD = HasHVX = false;
2256 else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2257 HasHVXD = HasHVX = true;
2258 else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2259 HasHVXD = false;
2260 else
2261 continue;
2262 A->claim();
2263 }
2264
2265 Features.push_back(HasHVX ? "+hvx" : "-hvx");
2266 Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2267 }
2268
getWebAssemblyTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)2269 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2270 std::vector<const char *> &Features) {
2271 for (const Arg *A : Args.filtered(options::OPT_m_wasm_Features_Group)) {
2272 StringRef Name = A->getOption().getName();
2273 A->claim();
2274
2275 // Skip over "-m".
2276 assert(Name.startswith("m") && "Invalid feature name.");
2277 Name = Name.substr(1);
2278
2279 bool IsNegative = Name.startswith("no-");
2280 if (IsNegative)
2281 Name = Name.substr(3);
2282
2283 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
2284 }
2285 }
2286
getTargetFeatures(const ToolChain & TC,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool ForAS)2287 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2288 const ArgList &Args, ArgStringList &CmdArgs,
2289 bool ForAS) {
2290 const Driver &D = TC.getDriver();
2291 std::vector<const char *> Features;
2292 switch (Triple.getArch()) {
2293 default:
2294 break;
2295 case llvm::Triple::mips:
2296 case llvm::Triple::mipsel:
2297 case llvm::Triple::mips64:
2298 case llvm::Triple::mips64el:
2299 getMIPSTargetFeatures(D, Triple, Args, Features);
2300 break;
2301
2302 case llvm::Triple::arm:
2303 case llvm::Triple::armeb:
2304 case llvm::Triple::thumb:
2305 case llvm::Triple::thumbeb:
2306 getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2307 break;
2308
2309 case llvm::Triple::ppc:
2310 case llvm::Triple::ppc64:
2311 case llvm::Triple::ppc64le:
2312 getPPCTargetFeatures(D, Triple, Args, Features);
2313 break;
2314 case llvm::Triple::systemz:
2315 getSystemZTargetFeatures(Args, Features);
2316 break;
2317 case llvm::Triple::aarch64:
2318 case llvm::Triple::aarch64_be:
2319 getAArch64TargetFeatures(D, Args, Features);
2320 break;
2321 case llvm::Triple::x86:
2322 case llvm::Triple::x86_64:
2323 getX86TargetFeatures(D, Triple, Args, Features);
2324 break;
2325 case llvm::Triple::hexagon:
2326 getHexagonTargetFeatures(Args, Features);
2327 break;
2328 case llvm::Triple::wasm32:
2329 case llvm::Triple::wasm64:
2330 getWebAssemblyTargetFeatures(Args, Features);
2331 break;
2332 }
2333
2334 // Find the last of each feature.
2335 llvm::StringMap<unsigned> LastOpt;
2336 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2337 const char *Name = Features[I];
2338 assert(Name[0] == '-' || Name[0] == '+');
2339 LastOpt[Name + 1] = I;
2340 }
2341
2342 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2343 // If this feature was overridden, ignore it.
2344 const char *Name = Features[I];
2345 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2346 assert(LastI != LastOpt.end());
2347 unsigned Last = LastI->second;
2348 if (Last != I)
2349 continue;
2350
2351 CmdArgs.push_back("-target-feature");
2352 CmdArgs.push_back(Name);
2353 }
2354 }
2355
2356 static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)2357 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2358 const llvm::Triple &Triple) {
2359 // We use the zero-cost exception tables for Objective-C if the non-fragile
2360 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2361 // later.
2362 if (runtime.isNonFragile())
2363 return true;
2364
2365 if (!Triple.isMacOSX())
2366 return false;
2367
2368 return (!Triple.isMacOSXVersionLT(10, 5) &&
2369 (Triple.getArch() == llvm::Triple::x86_64 ||
2370 Triple.getArch() == llvm::Triple::arm));
2371 }
2372
2373 /// Adds exception related arguments to the driver command arguments. There's a
2374 /// master flag, -fexceptions and also language specific flags to enable/disable
2375 /// C++ and Objective-C exceptions. This makes it possible to for example
2376 /// disable C++ exceptions but enable Objective-C exceptions.
addExceptionArgs(const ArgList & Args,types::ID InputType,const ToolChain & TC,bool KernelOrKext,const ObjCRuntime & objcRuntime,ArgStringList & CmdArgs)2377 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2378 const ToolChain &TC, bool KernelOrKext,
2379 const ObjCRuntime &objcRuntime,
2380 ArgStringList &CmdArgs) {
2381 const Driver &D = TC.getDriver();
2382 const llvm::Triple &Triple = TC.getTriple();
2383
2384 if (KernelOrKext) {
2385 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2386 // arguments now to avoid warnings about unused arguments.
2387 Args.ClaimAllArgs(options::OPT_fexceptions);
2388 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2389 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2390 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2391 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2392 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2393 return;
2394 }
2395
2396 // See if the user explicitly enabled exceptions.
2397 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2398 false);
2399
2400 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2401 // is not necessarily sensible, but follows GCC.
2402 if (types::isObjC(InputType) &&
2403 Args.hasFlag(options::OPT_fobjc_exceptions,
2404 options::OPT_fno_objc_exceptions, true)) {
2405 CmdArgs.push_back("-fobjc-exceptions");
2406
2407 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2408 }
2409
2410 if (types::isCXX(InputType)) {
2411 // Disable C++ EH by default on XCore, PS4, and MSVC.
2412 // FIXME: Remove MSVC from this list once things work.
2413 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2414 !Triple.isPS4CPU() &&
2415 !Triple.isWindowsMSVCEnvironment();
2416 Arg *ExceptionArg = Args.getLastArg(
2417 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2418 options::OPT_fexceptions, options::OPT_fno_exceptions);
2419 if (ExceptionArg)
2420 CXXExceptionsEnabled =
2421 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2422 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2423
2424 if (CXXExceptionsEnabled) {
2425 if (Triple.isPS4CPU()) {
2426 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2427 assert(ExceptionArg &&
2428 "On the PS4 exceptions should only be enabled if passing "
2429 "an argument");
2430 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2431 const Arg *RTTIArg = TC.getRTTIArg();
2432 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2433 D.Diag(diag::err_drv_argument_not_allowed_with)
2434 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2435 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2436 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2437 } else
2438 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2439
2440 CmdArgs.push_back("-fcxx-exceptions");
2441
2442 EH = true;
2443 }
2444 }
2445
2446 if (EH)
2447 CmdArgs.push_back("-fexceptions");
2448 }
2449
ShouldDisableAutolink(const ArgList & Args,const ToolChain & TC)2450 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2451 bool Default = true;
2452 if (TC.getTriple().isOSDarwin()) {
2453 // The native darwin assembler doesn't support the linker_option directives,
2454 // so we disable them if we think the .s file will be passed to it.
2455 Default = TC.useIntegratedAs();
2456 }
2457 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2458 Default);
2459 }
2460
ShouldDisableDwarfDirectory(const ArgList & Args,const ToolChain & TC)2461 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2462 const ToolChain &TC) {
2463 bool UseDwarfDirectory =
2464 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2465 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2466 return !UseDwarfDirectory;
2467 }
2468
2469 /// \brief Check whether the given input tree contains any compilation actions.
ContainsCompileAction(const Action * A)2470 static bool ContainsCompileAction(const Action *A) {
2471 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2472 return true;
2473
2474 for (const auto &Act : *A)
2475 if (ContainsCompileAction(Act))
2476 return true;
2477
2478 return false;
2479 }
2480
2481 /// \brief Check if -relax-all should be passed to the internal assembler.
2482 /// This is done by default when compiling non-assembler source with -O0.
UseRelaxAll(Compilation & C,const ArgList & Args)2483 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2484 bool RelaxDefault = true;
2485
2486 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2487 RelaxDefault = A->getOption().matches(options::OPT_O0);
2488
2489 if (RelaxDefault) {
2490 RelaxDefault = false;
2491 for (const auto &Act : C.getActions()) {
2492 if (ContainsCompileAction(Act)) {
2493 RelaxDefault = true;
2494 break;
2495 }
2496 }
2497 }
2498
2499 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2500 RelaxDefault);
2501 }
2502
2503 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2504 // to the corresponding DebugInfoKind.
DebugLevelToInfoKind(const Arg & A)2505 static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2506 assert(A.getOption().matches(options::OPT_gN_Group) &&
2507 "Not a -g option that specifies a debug-info level");
2508 if (A.getOption().matches(options::OPT_g0) ||
2509 A.getOption().matches(options::OPT_ggdb0))
2510 return CodeGenOptions::NoDebugInfo;
2511 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2512 A.getOption().matches(options::OPT_ggdb1))
2513 return CodeGenOptions::DebugLineTablesOnly;
2514 return CodeGenOptions::LimitedDebugInfo;
2515 }
2516
2517 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2518 // on mismatch. The StringRef input (rather than an Arg) allows
2519 // for use by the "-Xassembler" option parser.
DwarfVersionNum(StringRef ArgValue)2520 static unsigned DwarfVersionNum(StringRef ArgValue) {
2521 return llvm::StringSwitch<unsigned>(ArgValue)
2522 .Case("-gdwarf-2", 2)
2523 .Case("-gdwarf-3", 3)
2524 .Case("-gdwarf-4", 4)
2525 .Default(0);
2526 }
2527
RenderDebugEnablingArgs(const ArgList & Args,ArgStringList & CmdArgs,CodeGenOptions::DebugInfoKind DebugInfoKind,unsigned DwarfVersion,llvm::DebuggerKind DebuggerTuning)2528 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2529 CodeGenOptions::DebugInfoKind DebugInfoKind,
2530 unsigned DwarfVersion,
2531 llvm::DebuggerKind DebuggerTuning) {
2532 switch (DebugInfoKind) {
2533 case CodeGenOptions::DebugLineTablesOnly:
2534 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2535 break;
2536 case CodeGenOptions::LimitedDebugInfo:
2537 CmdArgs.push_back("-debug-info-kind=limited");
2538 break;
2539 case CodeGenOptions::FullDebugInfo:
2540 CmdArgs.push_back("-debug-info-kind=standalone");
2541 break;
2542 default:
2543 break;
2544 }
2545 if (DwarfVersion > 0)
2546 CmdArgs.push_back(
2547 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2548 switch (DebuggerTuning) {
2549 case llvm::DebuggerKind::GDB:
2550 CmdArgs.push_back("-debugger-tuning=gdb");
2551 break;
2552 case llvm::DebuggerKind::LLDB:
2553 CmdArgs.push_back("-debugger-tuning=lldb");
2554 break;
2555 case llvm::DebuggerKind::SCE:
2556 CmdArgs.push_back("-debugger-tuning=sce");
2557 break;
2558 default:
2559 break;
2560 }
2561 }
2562
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)2563 static void CollectArgsForIntegratedAssembler(Compilation &C,
2564 const ArgList &Args,
2565 ArgStringList &CmdArgs,
2566 const Driver &D) {
2567 if (UseRelaxAll(C, Args))
2568 CmdArgs.push_back("-mrelax-all");
2569
2570 // Only default to -mincremental-linker-compatible if we think we are
2571 // targeting the MSVC linker.
2572 bool DefaultIncrementalLinkerCompatible =
2573 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2574 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2575 options::OPT_mno_incremental_linker_compatible,
2576 DefaultIncrementalLinkerCompatible))
2577 CmdArgs.push_back("-mincremental-linker-compatible");
2578
2579 // When passing -I arguments to the assembler we sometimes need to
2580 // unconditionally take the next argument. For example, when parsing
2581 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2582 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2583 // arg after parsing the '-I' arg.
2584 bool TakeNextArg = false;
2585
2586 // When using an integrated assembler, translate -Wa, and -Xassembler
2587 // options.
2588 bool CompressDebugSections = false;
2589 for (const Arg *A :
2590 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2591 A->claim();
2592
2593 for (StringRef Value : A->getValues()) {
2594 if (TakeNextArg) {
2595 CmdArgs.push_back(Value.data());
2596 TakeNextArg = false;
2597 continue;
2598 }
2599
2600 switch (C.getDefaultToolChain().getArch()) {
2601 default:
2602 break;
2603 case llvm::Triple::mips:
2604 case llvm::Triple::mipsel:
2605 case llvm::Triple::mips64:
2606 case llvm::Triple::mips64el:
2607 if (Value == "--trap") {
2608 CmdArgs.push_back("-target-feature");
2609 CmdArgs.push_back("+use-tcc-in-div");
2610 continue;
2611 }
2612 if (Value == "--break") {
2613 CmdArgs.push_back("-target-feature");
2614 CmdArgs.push_back("-use-tcc-in-div");
2615 continue;
2616 }
2617 if (Value.startswith("-msoft-float")) {
2618 CmdArgs.push_back("-target-feature");
2619 CmdArgs.push_back("+soft-float");
2620 continue;
2621 }
2622 if (Value.startswith("-mhard-float")) {
2623 CmdArgs.push_back("-target-feature");
2624 CmdArgs.push_back("-soft-float");
2625 continue;
2626 }
2627 break;
2628 }
2629
2630 if (Value == "-force_cpusubtype_ALL") {
2631 // Do nothing, this is the default and we don't support anything else.
2632 } else if (Value == "-L") {
2633 CmdArgs.push_back("-msave-temp-labels");
2634 } else if (Value == "--fatal-warnings") {
2635 CmdArgs.push_back("-massembler-fatal-warnings");
2636 } else if (Value == "--noexecstack") {
2637 CmdArgs.push_back("-mnoexecstack");
2638 } else if (Value == "-compress-debug-sections" ||
2639 Value == "--compress-debug-sections") {
2640 CompressDebugSections = true;
2641 } else if (Value == "-nocompress-debug-sections" ||
2642 Value == "--nocompress-debug-sections") {
2643 CompressDebugSections = false;
2644 } else if (Value.startswith("-I")) {
2645 CmdArgs.push_back(Value.data());
2646 // We need to consume the next argument if the current arg is a plain
2647 // -I. The next arg will be the include directory.
2648 if (Value == "-I")
2649 TakeNextArg = true;
2650 } else if (Value.startswith("-gdwarf-")) {
2651 // "-gdwarf-N" options are not cc1as options.
2652 unsigned DwarfVersion = DwarfVersionNum(Value);
2653 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2654 CmdArgs.push_back(Value.data());
2655 } else {
2656 RenderDebugEnablingArgs(
2657 Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
2658 llvm::DebuggerKind::Default);
2659 }
2660 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2661 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2662 // Do nothing, we'll validate it later.
2663 } else {
2664 D.Diag(diag::err_drv_unsupported_option_argument)
2665 << A->getOption().getName() << Value;
2666 }
2667 }
2668 }
2669 if (CompressDebugSections) {
2670 if (llvm::zlib::isAvailable())
2671 CmdArgs.push_back("-compress-debug-sections");
2672 else
2673 D.Diag(diag::warn_debug_compression_unavailable);
2674 }
2675 }
2676
2677 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2678 // FIXME: Make sure we can also emit shared objects if they're requested
2679 // and available, check for possible errors, etc.
addClangRT(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2680 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2681 ArgStringList &CmdArgs) {
2682 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2683 }
2684
2685 namespace {
2686 enum OpenMPRuntimeKind {
2687 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2688 /// without knowing what runtime to target.
2689 OMPRT_Unknown,
2690
2691 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2692 /// the default for Clang.
2693 OMPRT_OMP,
2694
2695 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2696 /// this runtime but can swallow the pragmas, and find and link against the
2697 /// runtime library itself.
2698 OMPRT_GOMP,
2699
2700 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2701 /// OpenMP runtime. We support this mode for users with existing dependencies
2702 /// on this runtime library name.
2703 OMPRT_IOMP5
2704 };
2705 }
2706
2707 /// Compute the desired OpenMP runtime from the flag provided.
getOpenMPRuntime(const ToolChain & TC,const ArgList & Args)2708 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2709 const ArgList &Args) {
2710 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2711
2712 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2713 if (A)
2714 RuntimeName = A->getValue();
2715
2716 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2717 .Case("libomp", OMPRT_OMP)
2718 .Case("libgomp", OMPRT_GOMP)
2719 .Case("libiomp5", OMPRT_IOMP5)
2720 .Default(OMPRT_Unknown);
2721
2722 if (RT == OMPRT_Unknown) {
2723 if (A)
2724 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2725 << A->getOption().getName() << A->getValue();
2726 else
2727 // FIXME: We could use a nicer diagnostic here.
2728 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2729 }
2730
2731 return RT;
2732 }
2733
addOpenMPRuntime(ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args)2734 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2735 const ArgList &Args) {
2736 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2737 options::OPT_fno_openmp, false))
2738 return;
2739
2740 switch (getOpenMPRuntime(TC, Args)) {
2741 case OMPRT_OMP:
2742 CmdArgs.push_back("-lomp");
2743 break;
2744 case OMPRT_GOMP:
2745 CmdArgs.push_back("-lgomp");
2746 break;
2747 case OMPRT_IOMP5:
2748 CmdArgs.push_back("-liomp5");
2749 break;
2750 case OMPRT_Unknown:
2751 // Already diagnosed.
2752 break;
2753 }
2754 }
2755
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared)2756 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2757 ArgStringList &CmdArgs, StringRef Sanitizer,
2758 bool IsShared) {
2759 // Static runtimes must be forced into executable, so we wrap them in
2760 // whole-archive.
2761 if (!IsShared) CmdArgs.push_back("-whole-archive");
2762 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
2763 if (!IsShared) CmdArgs.push_back("-no-whole-archive");
2764 }
2765
2766 // Tries to use a file with the list of dynamic symbols that need to be exported
2767 // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)2768 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2769 ArgStringList &CmdArgs,
2770 StringRef Sanitizer) {
2771 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
2772 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2773 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2774 return true;
2775 }
2776 return false;
2777 }
2778
linkSanitizerRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)2779 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2780 ArgStringList &CmdArgs) {
2781 // Force linking against the system libraries sanitizers depends on
2782 // (see PR15823 why this is necessary).
2783 CmdArgs.push_back("--no-as-needed");
2784 CmdArgs.push_back("-lpthread");
2785 CmdArgs.push_back("-lrt");
2786 CmdArgs.push_back("-lm");
2787 // There's no libdl on FreeBSD.
2788 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2789 CmdArgs.push_back("-ldl");
2790 }
2791
2792 static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes)2793 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2794 SmallVectorImpl<StringRef> &SharedRuntimes,
2795 SmallVectorImpl<StringRef> &StaticRuntimes,
2796 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2797 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2798 // Collect shared runtimes.
2799 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2800 SharedRuntimes.push_back("asan");
2801 }
2802
2803 // Collect static runtimes.
2804 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
2805 // Don't link static runtimes into DSOs or if compiling for Android.
2806 return;
2807 }
2808 if (SanArgs.needsAsanRt()) {
2809 if (SanArgs.needsSharedAsanRt()) {
2810 HelperStaticRuntimes.push_back("asan-preinit");
2811 } else {
2812 StaticRuntimes.push_back("asan");
2813 if (SanArgs.linkCXXRuntimes())
2814 StaticRuntimes.push_back("asan_cxx");
2815 }
2816 }
2817 if (SanArgs.needsDfsanRt())
2818 StaticRuntimes.push_back("dfsan");
2819 if (SanArgs.needsLsanRt())
2820 StaticRuntimes.push_back("lsan");
2821 if (SanArgs.needsMsanRt()) {
2822 StaticRuntimes.push_back("msan");
2823 if (SanArgs.linkCXXRuntimes())
2824 StaticRuntimes.push_back("msan_cxx");
2825 }
2826 if (SanArgs.needsTsanRt()) {
2827 StaticRuntimes.push_back("tsan");
2828 if (SanArgs.linkCXXRuntimes())
2829 StaticRuntimes.push_back("tsan_cxx");
2830 }
2831 if (SanArgs.needsUbsanRt()) {
2832 StaticRuntimes.push_back("ubsan_standalone");
2833 if (SanArgs.linkCXXRuntimes())
2834 StaticRuntimes.push_back("ubsan_standalone_cxx");
2835 }
2836 if (SanArgs.needsSafeStackRt())
2837 StaticRuntimes.push_back("safestack");
2838 if (SanArgs.needsCfiRt())
2839 StaticRuntimes.push_back("cfi");
2840 if (SanArgs.needsCfiDiagRt())
2841 StaticRuntimes.push_back("cfi_diag");
2842 }
2843
2844 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2845 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2846 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2847 ArgStringList &CmdArgs) {
2848 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2849 HelperStaticRuntimes;
2850 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2851 HelperStaticRuntimes);
2852 for (auto RT : SharedRuntimes)
2853 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2854 for (auto RT : HelperStaticRuntimes)
2855 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2856 bool AddExportDynamic = false;
2857 for (auto RT : StaticRuntimes) {
2858 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2859 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2860 }
2861 // If there is a static runtime with no dynamic list, force all the symbols
2862 // to be dynamic to be sure we export sanitizer interface functions.
2863 if (AddExportDynamic)
2864 CmdArgs.push_back("-export-dynamic");
2865 return !StaticRuntimes.empty();
2866 }
2867
areOptimizationsEnabled(const ArgList & Args)2868 static bool areOptimizationsEnabled(const ArgList &Args) {
2869 // Find the last -O arg and see if it is non-zero.
2870 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2871 return !A->getOption().matches(options::OPT_O0);
2872 // Defaults to -O0.
2873 return false;
2874 }
2875
shouldUseFramePointerForTarget(const ArgList & Args,const llvm::Triple & Triple)2876 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2877 const llvm::Triple &Triple) {
2878 switch (Triple.getArch()) {
2879 case llvm::Triple::xcore:
2880 case llvm::Triple::wasm32:
2881 case llvm::Triple::wasm64:
2882 // XCore never wants frame pointers, regardless of OS.
2883 // WebAssembly never wants frame pointers.
2884 return false;
2885 default:
2886 break;
2887 }
2888
2889 if (Triple.isOSLinux()) {
2890 switch (Triple.getArch()) {
2891 // Don't use a frame pointer on linux if optimizing for certain targets.
2892 case llvm::Triple::mips64:
2893 case llvm::Triple::mips64el:
2894 case llvm::Triple::mips:
2895 case llvm::Triple::mipsel:
2896 case llvm::Triple::systemz:
2897 case llvm::Triple::x86:
2898 case llvm::Triple::x86_64:
2899 return !areOptimizationsEnabled(Args);
2900 default:
2901 return true;
2902 }
2903 }
2904
2905 if (Triple.isOSWindows()) {
2906 switch (Triple.getArch()) {
2907 case llvm::Triple::x86:
2908 return !areOptimizationsEnabled(Args);
2909 case llvm::Triple::arm:
2910 case llvm::Triple::thumb:
2911 // Windows on ARM builds with FPO disabled to aid fast stack walking
2912 return true;
2913 default:
2914 // All other supported Windows ISAs use xdata unwind information, so frame
2915 // pointers are not generally useful.
2916 return false;
2917 }
2918 }
2919
2920 return true;
2921 }
2922
shouldUseFramePointer(const ArgList & Args,const llvm::Triple & Triple)2923 static bool shouldUseFramePointer(const ArgList &Args,
2924 const llvm::Triple &Triple) {
2925 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2926 options::OPT_fomit_frame_pointer))
2927 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2928 if (Args.hasArg(options::OPT_pg))
2929 return true;
2930
2931 return shouldUseFramePointerForTarget(Args, Triple);
2932 }
2933
shouldUseLeafFramePointer(const ArgList & Args,const llvm::Triple & Triple)2934 static bool shouldUseLeafFramePointer(const ArgList &Args,
2935 const llvm::Triple &Triple) {
2936 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2937 options::OPT_momit_leaf_frame_pointer))
2938 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2939 if (Args.hasArg(options::OPT_pg))
2940 return true;
2941
2942 if (Triple.isPS4CPU())
2943 return false;
2944
2945 return shouldUseFramePointerForTarget(Args, Triple);
2946 }
2947
2948 /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs)2949 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2950 SmallString<128> cwd;
2951 if (!llvm::sys::fs::current_path(cwd)) {
2952 CmdArgs.push_back("-fdebug-compilation-dir");
2953 CmdArgs.push_back(Args.MakeArgString(cwd));
2954 }
2955 }
2956
SplitDebugName(const ArgList & Args,const InputInfo & Input)2957 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2958 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2959 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2960 SmallString<128> T(FinalOutput->getValue());
2961 llvm::sys::path::replace_extension(T, "dwo");
2962 return Args.MakeArgString(T);
2963 } else {
2964 // Use the compilation dir.
2965 SmallString<128> T(
2966 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2967 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2968 llvm::sys::path::replace_extension(F, "dwo");
2969 T += F;
2970 return Args.MakeArgString(F);
2971 }
2972 }
2973
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)2974 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2975 const JobAction &JA, const ArgList &Args,
2976 const InputInfo &Output, const char *OutFile) {
2977 ArgStringList ExtractArgs;
2978 ExtractArgs.push_back("--extract-dwo");
2979
2980 ArgStringList StripArgs;
2981 StripArgs.push_back("--strip-dwo");
2982
2983 // Grabbing the output of the earlier compile step.
2984 StripArgs.push_back(Output.getFilename());
2985 ExtractArgs.push_back(Output.getFilename());
2986 ExtractArgs.push_back(OutFile);
2987
2988 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2989 InputInfo II(Output.getFilename(), types::TY_Object, Output.getFilename());
2990
2991 // First extract the dwo sections.
2992 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
2993
2994 // Then remove them from the original .o file.
2995 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
2996 }
2997
2998 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2999 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
shouldEnableVectorizerAtOLevel(const ArgList & Args,bool isSlpVec)3000 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3001 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3002 if (A->getOption().matches(options::OPT_O4) ||
3003 A->getOption().matches(options::OPT_Ofast))
3004 return true;
3005
3006 if (A->getOption().matches(options::OPT_O0))
3007 return false;
3008
3009 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3010
3011 // Vectorize -Os.
3012 StringRef S(A->getValue());
3013 if (S == "s")
3014 return true;
3015
3016 // Don't vectorize -Oz, unless it's the slp vectorizer.
3017 if (S == "z")
3018 return isSlpVec;
3019
3020 unsigned OptLevel = 0;
3021 if (S.getAsInteger(10, OptLevel))
3022 return false;
3023
3024 return OptLevel > 1;
3025 }
3026
3027 return false;
3028 }
3029
3030 /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)3031 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3032 ArgStringList &CmdArgs) {
3033 // When using -verify-pch, we don't want to provide the type
3034 // 'precompiled-header' if it was inferred from the file extension
3035 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3036 return;
3037
3038 CmdArgs.push_back("-x");
3039 if (Args.hasArg(options::OPT_rewrite_objc))
3040 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3041 else
3042 CmdArgs.push_back(types::getTypeName(Input.getType()));
3043 }
3044
getMSCompatibilityVersion(unsigned Version)3045 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3046 if (Version < 100)
3047 return VersionTuple(Version);
3048
3049 if (Version < 10000)
3050 return VersionTuple(Version / 100, Version % 100);
3051
3052 unsigned Build = 0, Factor = 1;
3053 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3054 Build = Build + (Version % 10) * Factor;
3055 return VersionTuple(Version / 100, Version % 100, Build);
3056 }
3057
3058 // Claim options we don't want to warn if they are unused. We do this for
3059 // options that build systems might add but are unused when assembling or only
3060 // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)3061 static void claimNoWarnArgs(const ArgList &Args) {
3062 // Don't warn about unused -f(no-)?lto. This can happen when we're
3063 // preprocessing, precompiling or assembling.
3064 Args.ClaimAllArgs(options::OPT_flto_EQ);
3065 Args.ClaimAllArgs(options::OPT_flto);
3066 Args.ClaimAllArgs(options::OPT_fno_lto);
3067 }
3068
appendUserToPath(SmallVectorImpl<char> & Result)3069 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3070 #ifdef LLVM_ON_UNIX
3071 const char *Username = getenv("LOGNAME");
3072 #else
3073 const char *Username = getenv("USERNAME");
3074 #endif
3075 if (Username) {
3076 // Validate that LoginName can be used in a path, and get its length.
3077 size_t Len = 0;
3078 for (const char *P = Username; *P; ++P, ++Len) {
3079 if (!isAlphanumeric(*P) && *P != '_') {
3080 Username = nullptr;
3081 break;
3082 }
3083 }
3084
3085 if (Username && Len > 0) {
3086 Result.append(Username, Username + Len);
3087 return;
3088 }
3089 }
3090
3091 // Fallback to user id.
3092 #ifdef LLVM_ON_UNIX
3093 std::string UID = llvm::utostr(getuid());
3094 #else
3095 // FIXME: Windows seems to have an 'SID' that might work.
3096 std::string UID = "9999";
3097 #endif
3098 Result.append(UID.begin(), UID.end());
3099 }
3100
getMSVCVersion(const Driver * D,const llvm::Triple & Triple,const llvm::opt::ArgList & Args,bool IsWindowsMSVC)3101 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
3102 const llvm::Triple &Triple,
3103 const llvm::opt::ArgList &Args,
3104 bool IsWindowsMSVC) {
3105 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3106 IsWindowsMSVC) ||
3107 Args.hasArg(options::OPT_fmsc_version) ||
3108 Args.hasArg(options::OPT_fms_compatibility_version)) {
3109 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3110 const Arg *MSCompatibilityVersion =
3111 Args.getLastArg(options::OPT_fms_compatibility_version);
3112
3113 if (MSCVersion && MSCompatibilityVersion) {
3114 if (D)
3115 D->Diag(diag::err_drv_argument_not_allowed_with)
3116 << MSCVersion->getAsString(Args)
3117 << MSCompatibilityVersion->getAsString(Args);
3118 return VersionTuple();
3119 }
3120
3121 if (MSCompatibilityVersion) {
3122 VersionTuple MSVT;
3123 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3124 D->Diag(diag::err_drv_invalid_value)
3125 << MSCompatibilityVersion->getAsString(Args)
3126 << MSCompatibilityVersion->getValue();
3127 return MSVT;
3128 }
3129
3130 if (MSCVersion) {
3131 unsigned Version = 0;
3132 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3133 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3134 << MSCVersion->getValue();
3135 return getMSCompatibilityVersion(Version);
3136 }
3137
3138 unsigned Major, Minor, Micro;
3139 Triple.getEnvironmentVersion(Major, Minor, Micro);
3140 if (Major || Minor || Micro)
3141 return VersionTuple(Major, Minor, Micro);
3142
3143 return VersionTuple(18);
3144 }
3145 return VersionTuple();
3146 }
3147
addPGOAndCoverageFlags(Compilation & C,const Driver & D,const InputInfo & Output,const ArgList & Args,ArgStringList & CmdArgs)3148 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3149 const InputInfo &Output, const ArgList &Args,
3150 ArgStringList &CmdArgs) {
3151 auto *ProfileGenerateArg = Args.getLastArg(
3152 options::OPT_fprofile_instr_generate,
3153 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3154 options::OPT_fprofile_generate_EQ,
3155 options::OPT_fno_profile_instr_generate);
3156 if (ProfileGenerateArg &&
3157 ProfileGenerateArg->getOption().matches(
3158 options::OPT_fno_profile_instr_generate))
3159 ProfileGenerateArg = nullptr;
3160
3161 auto *ProfileUseArg = Args.getLastArg(
3162 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3163 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3164 options::OPT_fno_profile_instr_use);
3165 if (ProfileUseArg &&
3166 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3167 ProfileUseArg = nullptr;
3168
3169 if (ProfileGenerateArg && ProfileUseArg)
3170 D.Diag(diag::err_drv_argument_not_allowed_with)
3171 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3172
3173 if (ProfileGenerateArg) {
3174 if (ProfileGenerateArg->getOption().matches(
3175 options::OPT_fprofile_instr_generate_EQ))
3176 ProfileGenerateArg->render(Args, CmdArgs);
3177 else if (ProfileGenerateArg->getOption().matches(
3178 options::OPT_fprofile_generate_EQ)) {
3179 SmallString<128> Path(ProfileGenerateArg->getValue());
3180 llvm::sys::path::append(Path, "default.profraw");
3181 CmdArgs.push_back(
3182 Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
3183 } else
3184 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3185 }
3186
3187 if (ProfileUseArg) {
3188 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3189 ProfileUseArg->render(Args, CmdArgs);
3190 else if ((ProfileUseArg->getOption().matches(
3191 options::OPT_fprofile_use_EQ) ||
3192 ProfileUseArg->getOption().matches(
3193 options::OPT_fprofile_instr_use))) {
3194 SmallString<128> Path(
3195 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3196 if (Path.empty() || llvm::sys::fs::is_directory(Path))
3197 llvm::sys::path::append(Path, "default.profdata");
3198 CmdArgs.push_back(
3199 Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
3200 }
3201 }
3202
3203 if (Args.hasArg(options::OPT_ftest_coverage) ||
3204 Args.hasArg(options::OPT_coverage))
3205 CmdArgs.push_back("-femit-coverage-notes");
3206 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3207 false) ||
3208 Args.hasArg(options::OPT_coverage))
3209 CmdArgs.push_back("-femit-coverage-data");
3210
3211 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3212 options::OPT_fno_coverage_mapping, false) &&
3213 !ProfileGenerateArg)
3214 D.Diag(diag::err_drv_argument_only_allowed_with)
3215 << "-fcoverage-mapping"
3216 << "-fprofile-instr-generate";
3217
3218 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3219 options::OPT_fno_coverage_mapping, false))
3220 CmdArgs.push_back("-fcoverage-mapping");
3221
3222 if (C.getArgs().hasArg(options::OPT_c) ||
3223 C.getArgs().hasArg(options::OPT_S)) {
3224 if (Output.isFilename()) {
3225 CmdArgs.push_back("-coverage-file");
3226 SmallString<128> CoverageFilename;
3227 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3228 CoverageFilename = FinalOutput->getValue();
3229 } else {
3230 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3231 }
3232 if (llvm::sys::path::is_relative(CoverageFilename)) {
3233 SmallString<128> Pwd;
3234 if (!llvm::sys::fs::current_path(Pwd)) {
3235 llvm::sys::path::append(Pwd, CoverageFilename);
3236 CoverageFilename.swap(Pwd);
3237 }
3238 }
3239 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3240 }
3241 }
3242 }
3243
addPS4ProfileRTArgs(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3244 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3245 ArgStringList &CmdArgs) {
3246 if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3247 false) ||
3248 Args.hasFlag(options::OPT_fprofile_generate,
3249 options::OPT_fno_profile_instr_generate, false) ||
3250 Args.hasFlag(options::OPT_fprofile_generate_EQ,
3251 options::OPT_fno_profile_instr_generate, false) ||
3252 Args.hasFlag(options::OPT_fprofile_instr_generate,
3253 options::OPT_fno_profile_instr_generate, false) ||
3254 Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3255 options::OPT_fno_profile_instr_generate, false) ||
3256 Args.hasArg(options::OPT_fcreate_profile) ||
3257 Args.hasArg(options::OPT_coverage)))
3258 CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3259 }
3260
3261 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
3262 /// smooshes them together with platform defaults, to decide whether
3263 /// this compile should be using PIC mode or not. Returns a tuple of
3264 /// (RelocationModel, PICLevel, IsPIE).
3265 static std::tuple<llvm::Reloc::Model, unsigned, bool>
ParsePICArgs(const ToolChain & ToolChain,const llvm::Triple & Triple,const ArgList & Args)3266 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3267 const ArgList &Args) {
3268 // FIXME: why does this code...and so much everywhere else, use both
3269 // ToolChain.getTriple() and Triple?
3270 bool PIE = ToolChain.isPIEDefault();
3271 bool PIC = PIE || ToolChain.isPICDefault();
3272 // The Darwin default to use PIC does not apply when using -static.
3273 if (ToolChain.getTriple().isOSDarwin() && Args.hasArg(options::OPT_static))
3274 PIE = PIC = false;
3275 bool IsPICLevelTwo = PIC;
3276
3277 bool KernelOrKext =
3278 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3279
3280 // Android-specific defaults for PIC/PIE
3281 if (ToolChain.getTriple().isAndroid()) {
3282 switch (ToolChain.getArch()) {
3283 case llvm::Triple::arm:
3284 case llvm::Triple::armeb:
3285 case llvm::Triple::thumb:
3286 case llvm::Triple::thumbeb:
3287 case llvm::Triple::aarch64:
3288 case llvm::Triple::mips:
3289 case llvm::Triple::mipsel:
3290 case llvm::Triple::mips64:
3291 case llvm::Triple::mips64el:
3292 PIC = true; // "-fpic"
3293 break;
3294
3295 case llvm::Triple::x86:
3296 case llvm::Triple::x86_64:
3297 PIC = true; // "-fPIC"
3298 IsPICLevelTwo = true;
3299 break;
3300
3301 default:
3302 break;
3303 }
3304 }
3305
3306 // OpenBSD-specific defaults for PIE
3307 if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3308 switch (ToolChain.getArch()) {
3309 case llvm::Triple::mips64:
3310 case llvm::Triple::mips64el:
3311 case llvm::Triple::sparcel:
3312 case llvm::Triple::x86:
3313 case llvm::Triple::x86_64:
3314 IsPICLevelTwo = false; // "-fpie"
3315 break;
3316
3317 case llvm::Triple::ppc:
3318 case llvm::Triple::sparc:
3319 case llvm::Triple::sparcv9:
3320 IsPICLevelTwo = true; // "-fPIE"
3321 break;
3322
3323 default:
3324 break;
3325 }
3326 }
3327
3328 // The last argument relating to either PIC or PIE wins, and no
3329 // other argument is used. If the last argument is any flavor of the
3330 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3331 // option implicitly enables PIC at the same level.
3332 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3333 options::OPT_fpic, options::OPT_fno_pic,
3334 options::OPT_fPIE, options::OPT_fno_PIE,
3335 options::OPT_fpie, options::OPT_fno_pie);
3336 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3337 // is forced, then neither PIC nor PIE flags will have no effect.
3338 if (!ToolChain.isPICDefaultForced()) {
3339 if (LastPICArg) {
3340 Option O = LastPICArg->getOption();
3341 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3342 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3343 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3344 PIC =
3345 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3346 IsPICLevelTwo =
3347 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3348 } else {
3349 PIE = PIC = false;
3350 if (Triple.isPS4CPU()) {
3351 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3352 StringRef Model = ModelArg ? ModelArg->getValue() : "";
3353 if (Model != "kernel") {
3354 PIC = true;
3355 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3356 << LastPICArg->getSpelling();
3357 }
3358 }
3359 }
3360 }
3361 }
3362
3363 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3364 // PIC level would've been set to level 1, force it back to level 2 PIC
3365 // instead.
3366 if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3367 IsPICLevelTwo |= ToolChain.isPICDefault();
3368
3369 // This kernel flags are a trump-card: they will disable PIC/PIE
3370 // generation, independent of the argument order.
3371 if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3372 !Triple.isWatchOS()))
3373 PIC = PIE = false;
3374
3375 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3376 // This is a very special mode. It trumps the other modes, almost no one
3377 // uses it, and it isn't even valid on any OS but Darwin.
3378 if (!ToolChain.getTriple().isOSDarwin())
3379 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3380 << A->getSpelling() << ToolChain.getTriple().str();
3381
3382 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3383
3384 // Only a forced PIC mode can cause the actual compile to have PIC defines
3385 // etc., no flags are sufficient. This behavior was selected to closely
3386 // match that of llvm-gcc and Apple GCC before that.
3387 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3388
3389 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3390 }
3391
3392 if (PIC)
3393 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3394
3395 return std::make_tuple(llvm::Reloc::Static, 0, false);
3396 }
3397
RelocationModelName(llvm::Reloc::Model Model)3398 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3399 switch (Model) {
3400 case llvm::Reloc::Default:
3401 return nullptr;
3402 case llvm::Reloc::Static:
3403 return "static";
3404 case llvm::Reloc::PIC_:
3405 return "pic";
3406 case llvm::Reloc::DynamicNoPIC:
3407 return "dynamic-no-pic";
3408 }
3409 llvm_unreachable("Unknown Reloc::Model kind");
3410 }
3411
AddAssemblerKPIC(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)3412 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3413 ArgStringList &CmdArgs) {
3414 llvm::Reloc::Model RelocationModel;
3415 unsigned PICLevel;
3416 bool IsPIE;
3417 std::tie(RelocationModel, PICLevel, IsPIE) =
3418 ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3419
3420 if (RelocationModel != llvm::Reloc::Static)
3421 CmdArgs.push_back("-KPIC");
3422 }
3423
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3424 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3425 const InputInfo &Output, const InputInfoList &Inputs,
3426 const ArgList &Args, const char *LinkingOutput) const {
3427 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3428 const llvm::Triple Triple(TripleStr);
3429
3430 bool KernelOrKext =
3431 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3432 const Driver &D = getToolChain().getDriver();
3433 ArgStringList CmdArgs;
3434
3435 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3436 bool IsWindowsCygnus =
3437 getToolChain().getTriple().isWindowsCygwinEnvironment();
3438 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3439 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3440
3441 // Check number of inputs for sanity. We need at least one input.
3442 assert(Inputs.size() >= 1 && "Must have at least one input.");
3443 const InputInfo &Input = Inputs[0];
3444 // CUDA compilation may have multiple inputs (source file + results of
3445 // device-side compilations). All other jobs are expected to have exactly one
3446 // input.
3447 bool IsCuda = types::isCuda(Input.getType());
3448 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3449
3450 // Invoke ourselves in -cc1 mode.
3451 //
3452 // FIXME: Implement custom jobs for internal actions.
3453 CmdArgs.push_back("-cc1");
3454
3455 // Add the "effective" target triple.
3456 CmdArgs.push_back("-triple");
3457 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3458
3459 const ToolChain *AuxToolChain = nullptr;
3460 if (IsCuda) {
3461 // FIXME: We need a (better) way to pass information about
3462 // particular compilation pass we're constructing here. For now we
3463 // can check which toolchain we're using and pick the other one to
3464 // extract the triple.
3465 if (&getToolChain() == C.getCudaDeviceToolChain())
3466 AuxToolChain = C.getCudaHostToolChain();
3467 else if (&getToolChain() == C.getCudaHostToolChain())
3468 AuxToolChain = C.getCudaDeviceToolChain();
3469 else
3470 llvm_unreachable("Can't figure out CUDA compilation mode.");
3471 assert(AuxToolChain != nullptr && "No aux toolchain.");
3472 CmdArgs.push_back("-aux-triple");
3473 CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3474 CmdArgs.push_back("-fcuda-target-overloads");
3475 CmdArgs.push_back("-fcuda-disable-target-call-checks");
3476 }
3477
3478 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3479 Triple.getArch() == llvm::Triple::thumb)) {
3480 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3481 unsigned Version;
3482 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3483 if (Version < 7)
3484 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3485 << TripleStr;
3486 }
3487
3488 // Push all default warning arguments that are specific to
3489 // the given target. These come before user provided warning options
3490 // are provided.
3491 getToolChain().addClangWarningOptions(CmdArgs);
3492
3493 // Select the appropriate action.
3494 RewriteKind rewriteKind = RK_None;
3495
3496 if (isa<AnalyzeJobAction>(JA)) {
3497 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3498 CmdArgs.push_back("-analyze");
3499 } else if (isa<MigrateJobAction>(JA)) {
3500 CmdArgs.push_back("-migrate");
3501 } else if (isa<PreprocessJobAction>(JA)) {
3502 if (Output.getType() == types::TY_Dependencies)
3503 CmdArgs.push_back("-Eonly");
3504 else {
3505 CmdArgs.push_back("-E");
3506 if (Args.hasArg(options::OPT_rewrite_objc) &&
3507 !Args.hasArg(options::OPT_g_Group))
3508 CmdArgs.push_back("-P");
3509 }
3510 } else if (isa<AssembleJobAction>(JA)) {
3511 CmdArgs.push_back("-emit-obj");
3512
3513 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3514
3515 // Also ignore explicit -force_cpusubtype_ALL option.
3516 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3517 } else if (isa<PrecompileJobAction>(JA)) {
3518 // Use PCH if the user requested it.
3519 bool UsePCH = D.CCCUsePCH;
3520
3521 if (JA.getType() == types::TY_Nothing)
3522 CmdArgs.push_back("-fsyntax-only");
3523 else if (UsePCH)
3524 CmdArgs.push_back("-emit-pch");
3525 else
3526 CmdArgs.push_back("-emit-pth");
3527 } else if (isa<VerifyPCHJobAction>(JA)) {
3528 CmdArgs.push_back("-verify-pch");
3529 } else {
3530 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3531 "Invalid action for clang tool.");
3532 if (JA.getType() == types::TY_Nothing) {
3533 CmdArgs.push_back("-fsyntax-only");
3534 } else if (JA.getType() == types::TY_LLVM_IR ||
3535 JA.getType() == types::TY_LTO_IR) {
3536 CmdArgs.push_back("-emit-llvm");
3537 } else if (JA.getType() == types::TY_LLVM_BC ||
3538 JA.getType() == types::TY_LTO_BC) {
3539 CmdArgs.push_back("-emit-llvm-bc");
3540 } else if (JA.getType() == types::TY_PP_Asm) {
3541 CmdArgs.push_back("-S");
3542 } else if (JA.getType() == types::TY_AST) {
3543 CmdArgs.push_back("-emit-pch");
3544 } else if (JA.getType() == types::TY_ModuleFile) {
3545 CmdArgs.push_back("-module-file-info");
3546 } else if (JA.getType() == types::TY_RewrittenObjC) {
3547 CmdArgs.push_back("-rewrite-objc");
3548 rewriteKind = RK_NonFragile;
3549 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3550 CmdArgs.push_back("-rewrite-objc");
3551 rewriteKind = RK_Fragile;
3552 } else {
3553 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3554 }
3555
3556 // Preserve use-list order by default when emitting bitcode, so that
3557 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3558 // same result as running passes here. For LTO, we don't need to preserve
3559 // the use-list order, since serialization to bitcode is part of the flow.
3560 if (JA.getType() == types::TY_LLVM_BC)
3561 CmdArgs.push_back("-emit-llvm-uselists");
3562
3563 if (D.isUsingLTO())
3564 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3565 }
3566
3567 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3568 if (!types::isLLVMIR(Input.getType()))
3569 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3570 << "-x ir";
3571 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3572 }
3573
3574 // We normally speed up the clang process a bit by skipping destructors at
3575 // exit, but when we're generating diagnostics we can rely on some of the
3576 // cleanup.
3577 if (!C.isForDiagnostics())
3578 CmdArgs.push_back("-disable-free");
3579
3580 // Disable the verification pass in -asserts builds.
3581 #ifdef NDEBUG
3582 CmdArgs.push_back("-disable-llvm-verifier");
3583 #endif
3584
3585 // Set the main file name, so that debug info works even with
3586 // -save-temps.
3587 CmdArgs.push_back("-main-file-name");
3588 CmdArgs.push_back(getBaseInputName(Args, Input));
3589
3590 // Some flags which affect the language (via preprocessor
3591 // defines).
3592 if (Args.hasArg(options::OPT_static))
3593 CmdArgs.push_back("-static-define");
3594
3595 if (isa<AnalyzeJobAction>(JA)) {
3596 // Enable region store model by default.
3597 CmdArgs.push_back("-analyzer-store=region");
3598
3599 // Treat blocks as analysis entry points.
3600 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3601
3602 CmdArgs.push_back("-analyzer-eagerly-assume");
3603
3604 // Add default argument set.
3605 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3606 CmdArgs.push_back("-analyzer-checker=core");
3607
3608 if (!IsWindowsMSVC)
3609 CmdArgs.push_back("-analyzer-checker=unix");
3610
3611 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3612 CmdArgs.push_back("-analyzer-checker=osx");
3613
3614 CmdArgs.push_back("-analyzer-checker=deadcode");
3615
3616 if (types::isCXX(Input.getType()))
3617 CmdArgs.push_back("-analyzer-checker=cplusplus");
3618
3619 // Enable the following experimental checkers for testing.
3620 CmdArgs.push_back(
3621 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3622 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3623 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3624 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3625 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3626 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3627
3628 // Default nullability checks.
3629 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3630 CmdArgs.push_back(
3631 "-analyzer-checker=nullability.NullReturnedFromNonnull");
3632 }
3633
3634 // Set the output format. The default is plist, for (lame) historical
3635 // reasons.
3636 CmdArgs.push_back("-analyzer-output");
3637 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3638 CmdArgs.push_back(A->getValue());
3639 else
3640 CmdArgs.push_back("plist");
3641
3642 // Disable the presentation of standard compiler warnings when
3643 // using --analyze. We only want to show static analyzer diagnostics
3644 // or frontend errors.
3645 CmdArgs.push_back("-w");
3646
3647 // Add -Xanalyzer arguments when running as analyzer.
3648 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3649 }
3650
3651 CheckCodeGenerationOptions(D, Args);
3652
3653 llvm::Reloc::Model RelocationModel;
3654 unsigned PICLevel;
3655 bool IsPIE;
3656 std::tie(RelocationModel, PICLevel, IsPIE) =
3657 ParsePICArgs(getToolChain(), Triple, Args);
3658
3659 const char *RMName = RelocationModelName(RelocationModel);
3660 if (RMName) {
3661 CmdArgs.push_back("-mrelocation-model");
3662 CmdArgs.push_back(RMName);
3663 }
3664 if (PICLevel > 0) {
3665 CmdArgs.push_back("-pic-level");
3666 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3667 if (IsPIE) {
3668 CmdArgs.push_back("-pie-level");
3669 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3670 }
3671 }
3672
3673 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3674 CmdArgs.push_back("-meabi");
3675 CmdArgs.push_back(A->getValue());
3676 }
3677
3678 CmdArgs.push_back("-mthread-model");
3679 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3680 CmdArgs.push_back(A->getValue());
3681 else
3682 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3683
3684 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3685
3686 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3687 options::OPT_fno_merge_all_constants))
3688 CmdArgs.push_back("-fno-merge-all-constants");
3689
3690 // LLVM Code Generator Options.
3691
3692 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3693 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3694 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3695 options::OPT_frewrite_map_file_EQ)) {
3696 CmdArgs.push_back("-frewrite-map-file");
3697 CmdArgs.push_back(A->getValue());
3698 A->claim();
3699 }
3700 }
3701
3702 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3703 StringRef v = A->getValue();
3704 CmdArgs.push_back("-mllvm");
3705 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3706 A->claim();
3707 }
3708
3709 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3710 CmdArgs.push_back("-mregparm");
3711 CmdArgs.push_back(A->getValue());
3712 }
3713
3714 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3715 options::OPT_freg_struct_return)) {
3716 if (getToolChain().getArch() != llvm::Triple::x86) {
3717 D.Diag(diag::err_drv_unsupported_opt_for_target)
3718 << A->getSpelling() << getToolChain().getTriple().str();
3719 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3720 CmdArgs.push_back("-fpcc-struct-return");
3721 } else {
3722 assert(A->getOption().matches(options::OPT_freg_struct_return));
3723 CmdArgs.push_back("-freg-struct-return");
3724 }
3725 }
3726
3727 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3728 CmdArgs.push_back("-mrtd");
3729
3730 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3731 CmdArgs.push_back("-mdisable-fp-elim");
3732 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3733 options::OPT_fno_zero_initialized_in_bss))
3734 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3735
3736 bool OFastEnabled = isOptimizationLevelFast(Args);
3737 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3738 // enabled. This alias option is being used to simplify the hasFlag logic.
3739 OptSpecifier StrictAliasingAliasOption =
3740 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3741 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3742 // doesn't do any TBAA.
3743 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3744 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3745 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3746 CmdArgs.push_back("-relaxed-aliasing");
3747 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3748 options::OPT_fno_struct_path_tbaa))
3749 CmdArgs.push_back("-no-struct-path-tbaa");
3750 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3751 false))
3752 CmdArgs.push_back("-fstrict-enums");
3753 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3754 options::OPT_fno_strict_vtable_pointers,
3755 false))
3756 CmdArgs.push_back("-fstrict-vtable-pointers");
3757 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3758 options::OPT_fno_optimize_sibling_calls))
3759 CmdArgs.push_back("-mdisable-tail-calls");
3760
3761 // Handle segmented stacks.
3762 if (Args.hasArg(options::OPT_fsplit_stack))
3763 CmdArgs.push_back("-split-stacks");
3764
3765 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3766 // This alias option is being used to simplify the getLastArg logic.
3767 OptSpecifier FastMathAliasOption =
3768 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3769
3770 // Handle various floating point optimization flags, mapping them to the
3771 // appropriate LLVM code generation flags. The pattern for all of these is to
3772 // default off the codegen optimizations, and if any flag enables them and no
3773 // flag disables them after the flag enabling them, enable the codegen
3774 // optimization. This is complicated by several "umbrella" flags.
3775 if (Arg *A = Args.getLastArg(
3776 options::OPT_ffast_math, FastMathAliasOption,
3777 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3778 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3779 options::OPT_fno_honor_infinities))
3780 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3781 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3782 A->getOption().getID() != options::OPT_fhonor_infinities)
3783 CmdArgs.push_back("-menable-no-infs");
3784 if (Arg *A = Args.getLastArg(
3785 options::OPT_ffast_math, FastMathAliasOption,
3786 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3787 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3788 options::OPT_fno_honor_nans))
3789 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3790 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3791 A->getOption().getID() != options::OPT_fhonor_nans)
3792 CmdArgs.push_back("-menable-no-nans");
3793
3794 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3795 bool MathErrno = getToolChain().IsMathErrnoDefault();
3796 if (Arg *A =
3797 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3798 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3799 options::OPT_fno_math_errno)) {
3800 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3801 // However, turning *off* -ffast_math merely restores the toolchain default
3802 // (which may be false).
3803 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3804 A->getOption().getID() == options::OPT_ffast_math ||
3805 A->getOption().getID() == options::OPT_Ofast)
3806 MathErrno = false;
3807 else if (A->getOption().getID() == options::OPT_fmath_errno)
3808 MathErrno = true;
3809 }
3810 if (MathErrno)
3811 CmdArgs.push_back("-fmath-errno");
3812
3813 // There are several flags which require disabling very specific
3814 // optimizations. Any of these being disabled forces us to turn off the
3815 // entire set of LLVM optimizations, so collect them through all the flag
3816 // madness.
3817 bool AssociativeMath = false;
3818 if (Arg *A = Args.getLastArg(
3819 options::OPT_ffast_math, FastMathAliasOption,
3820 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3821 options::OPT_fno_unsafe_math_optimizations,
3822 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3823 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3824 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3825 A->getOption().getID() != options::OPT_fno_associative_math)
3826 AssociativeMath = true;
3827 bool ReciprocalMath = false;
3828 if (Arg *A = Args.getLastArg(
3829 options::OPT_ffast_math, FastMathAliasOption,
3830 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3831 options::OPT_fno_unsafe_math_optimizations,
3832 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3833 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3834 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3835 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3836 ReciprocalMath = true;
3837 bool SignedZeros = true;
3838 if (Arg *A = Args.getLastArg(
3839 options::OPT_ffast_math, FastMathAliasOption,
3840 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3841 options::OPT_fno_unsafe_math_optimizations,
3842 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3843 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3844 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3845 A->getOption().getID() != options::OPT_fsigned_zeros)
3846 SignedZeros = false;
3847 bool TrappingMath = true;
3848 if (Arg *A = Args.getLastArg(
3849 options::OPT_ffast_math, FastMathAliasOption,
3850 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3851 options::OPT_fno_unsafe_math_optimizations,
3852 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3853 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3854 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3855 A->getOption().getID() != options::OPT_ftrapping_math)
3856 TrappingMath = false;
3857 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3858 !TrappingMath)
3859 CmdArgs.push_back("-menable-unsafe-fp-math");
3860
3861 if (!SignedZeros)
3862 CmdArgs.push_back("-fno-signed-zeros");
3863
3864 if (ReciprocalMath)
3865 CmdArgs.push_back("-freciprocal-math");
3866
3867 // Validate and pass through -fp-contract option.
3868 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3869 options::OPT_fno_fast_math,
3870 options::OPT_ffp_contract)) {
3871 if (A->getOption().getID() == options::OPT_ffp_contract) {
3872 StringRef Val = A->getValue();
3873 if (Val == "fast" || Val == "on" || Val == "off") {
3874 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3875 } else {
3876 D.Diag(diag::err_drv_unsupported_option_argument)
3877 << A->getOption().getName() << Val;
3878 }
3879 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3880 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3881 // If fast-math is set then set the fp-contract mode to fast.
3882 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3883 }
3884 }
3885
3886 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3887
3888 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3889 // and if we find them, tell the frontend to provide the appropriate
3890 // preprocessor macros. This is distinct from enabling any optimizations as
3891 // these options induce language changes which must survive serialization
3892 // and deserialization, etc.
3893 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3894 options::OPT_fno_fast_math))
3895 if (!A->getOption().matches(options::OPT_fno_fast_math))
3896 CmdArgs.push_back("-ffast-math");
3897 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3898 options::OPT_fno_fast_math))
3899 if (A->getOption().matches(options::OPT_ffinite_math_only))
3900 CmdArgs.push_back("-ffinite-math-only");
3901
3902 // Decide whether to use verbose asm. Verbose assembly is the default on
3903 // toolchains which have the integrated assembler on by default.
3904 bool IsIntegratedAssemblerDefault =
3905 getToolChain().IsIntegratedAssemblerDefault();
3906 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3907 IsIntegratedAssemblerDefault) ||
3908 Args.hasArg(options::OPT_dA))
3909 CmdArgs.push_back("-masm-verbose");
3910
3911 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3912 IsIntegratedAssemblerDefault))
3913 CmdArgs.push_back("-no-integrated-as");
3914
3915 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3916 CmdArgs.push_back("-mdebug-pass");
3917 CmdArgs.push_back("Structure");
3918 }
3919 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3920 CmdArgs.push_back("-mdebug-pass");
3921 CmdArgs.push_back("Arguments");
3922 }
3923
3924 // Enable -mconstructor-aliases except on darwin, where we have to
3925 // work around a linker bug; see <rdar://problem/7651567>.
3926 if (!getToolChain().getTriple().isOSDarwin())
3927 CmdArgs.push_back("-mconstructor-aliases");
3928
3929 // Darwin's kernel doesn't support guard variables; just die if we
3930 // try to use them.
3931 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3932 CmdArgs.push_back("-fforbid-guard-variables");
3933
3934 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3935 false)) {
3936 CmdArgs.push_back("-mms-bitfields");
3937 }
3938
3939 // This is a coarse approximation of what llvm-gcc actually does, both
3940 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3941 // complicated ways.
3942 bool AsynchronousUnwindTables =
3943 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3944 options::OPT_fno_asynchronous_unwind_tables,
3945 (getToolChain().IsUnwindTablesDefault() ||
3946 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3947 !KernelOrKext);
3948 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3949 AsynchronousUnwindTables))
3950 CmdArgs.push_back("-munwind-tables");
3951
3952 getToolChain().addClangTargetOptions(Args, CmdArgs);
3953
3954 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3955 CmdArgs.push_back("-mlimit-float-precision");
3956 CmdArgs.push_back(A->getValue());
3957 }
3958
3959 // FIXME: Handle -mtune=.
3960 (void)Args.hasArg(options::OPT_mtune_EQ);
3961
3962 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3963 CmdArgs.push_back("-mcode-model");
3964 CmdArgs.push_back(A->getValue());
3965 }
3966
3967 // Add the target cpu
3968 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3969 if (!CPU.empty()) {
3970 CmdArgs.push_back("-target-cpu");
3971 CmdArgs.push_back(Args.MakeArgString(CPU));
3972 }
3973
3974 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3975 CmdArgs.push_back("-mfpmath");
3976 CmdArgs.push_back(A->getValue());
3977 }
3978
3979 // Add the target features
3980 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
3981
3982 // Add target specific flags.
3983 switch (getToolChain().getArch()) {
3984 default:
3985 break;
3986
3987 case llvm::Triple::arm:
3988 case llvm::Triple::armeb:
3989 case llvm::Triple::thumb:
3990 case llvm::Triple::thumbeb:
3991 // Use the effective triple, which takes into account the deployment target.
3992 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
3993 break;
3994
3995 case llvm::Triple::aarch64:
3996 case llvm::Triple::aarch64_be:
3997 AddAArch64TargetArgs(Args, CmdArgs);
3998 break;
3999
4000 case llvm::Triple::mips:
4001 case llvm::Triple::mipsel:
4002 case llvm::Triple::mips64:
4003 case llvm::Triple::mips64el:
4004 AddMIPSTargetArgs(Args, CmdArgs);
4005 break;
4006
4007 case llvm::Triple::ppc:
4008 case llvm::Triple::ppc64:
4009 case llvm::Triple::ppc64le:
4010 AddPPCTargetArgs(Args, CmdArgs);
4011 break;
4012
4013 case llvm::Triple::sparc:
4014 case llvm::Triple::sparcel:
4015 case llvm::Triple::sparcv9:
4016 AddSparcTargetArgs(Args, CmdArgs);
4017 break;
4018
4019 case llvm::Triple::x86:
4020 case llvm::Triple::x86_64:
4021 AddX86TargetArgs(Args, CmdArgs);
4022 break;
4023
4024 case llvm::Triple::hexagon:
4025 AddHexagonTargetArgs(Args, CmdArgs);
4026 break;
4027 }
4028
4029 // The 'g' groups options involve a somewhat intricate sequence of decisions
4030 // about what to pass from the driver to the frontend, but by the time they
4031 // reach cc1 they've been factored into three well-defined orthogonal choices:
4032 // * what level of debug info to generate
4033 // * what dwarf version to write
4034 // * what debugger tuning to use
4035 // This avoids having to monkey around further in cc1 other than to disable
4036 // codeview if not running in a Windows environment. Perhaps even that
4037 // decision should be made in the driver as well though.
4038 unsigned DwarfVersion = 0;
4039 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4040 // These two are potentially updated by AddClangCLArgs.
4041 enum CodeGenOptions::DebugInfoKind DebugInfoKind =
4042 CodeGenOptions::NoDebugInfo;
4043 bool EmitCodeView = false;
4044
4045 // Add clang-cl arguments.
4046 if (getToolChain().getDriver().IsCLMode())
4047 AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
4048
4049 // Pass the linker version in use.
4050 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4051 CmdArgs.push_back("-target-linker-version");
4052 CmdArgs.push_back(A->getValue());
4053 }
4054
4055 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4056 CmdArgs.push_back("-momit-leaf-frame-pointer");
4057
4058 // Explicitly error on some things we know we don't support and can't just
4059 // ignore.
4060 types::ID InputType = Input.getType();
4061 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4062 Arg *Unsupported;
4063 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4064 getToolChain().getArch() == llvm::Triple::x86) {
4065 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4066 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4067 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4068 << Unsupported->getOption().getName();
4069 }
4070 }
4071
4072 Args.AddAllArgs(CmdArgs, options::OPT_v);
4073 Args.AddLastArg(CmdArgs, options::OPT_H);
4074 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4075 CmdArgs.push_back("-header-include-file");
4076 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4077 : "-");
4078 }
4079 Args.AddLastArg(CmdArgs, options::OPT_P);
4080 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4081
4082 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4083 CmdArgs.push_back("-diagnostic-log-file");
4084 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4085 : "-");
4086 }
4087
4088 Args.ClaimAllArgs(options::OPT_g_Group);
4089 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4090 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4091 // If the last option explicitly specified a debug-info level, use it.
4092 if (A->getOption().matches(options::OPT_gN_Group)) {
4093 DebugInfoKind = DebugLevelToInfoKind(*A);
4094 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4095 // But -gsplit-dwarf is not a g_group option, hence we have to check the
4096 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4097 if (SplitDwarfArg && DebugInfoKind < CodeGenOptions::LimitedDebugInfo &&
4098 A->getIndex() > SplitDwarfArg->getIndex())
4099 SplitDwarfArg = nullptr;
4100 } else
4101 // For any other 'g' option, use Limited.
4102 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4103 }
4104
4105 // If a debugger tuning argument appeared, remember it.
4106 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4107 options::OPT_ggdbN_Group)) {
4108 if (A->getOption().matches(options::OPT_glldb))
4109 DebuggerTuning = llvm::DebuggerKind::LLDB;
4110 else if (A->getOption().matches(options::OPT_gsce))
4111 DebuggerTuning = llvm::DebuggerKind::SCE;
4112 else
4113 DebuggerTuning = llvm::DebuggerKind::GDB;
4114 }
4115
4116 // If a -gdwarf argument appeared, remember it.
4117 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4118 options::OPT_gdwarf_4))
4119 DwarfVersion = DwarfVersionNum(A->getSpelling());
4120
4121 // Forward -gcodeview.
4122 // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4123 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4124 // DwarfVersion remains at 0 if no explicit choice was made.
4125 CmdArgs.push_back("-gcodeview");
4126 } else if (DwarfVersion == 0 &&
4127 DebugInfoKind != CodeGenOptions::NoDebugInfo) {
4128 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4129 }
4130
4131 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4132 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4133
4134 // PS4 defaults to no column info
4135 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4136 /*Default=*/ !IsPS4CPU))
4137 CmdArgs.push_back("-dwarf-column-info");
4138
4139 // FIXME: Move backend command line options to the module.
4140 if (Args.hasArg(options::OPT_gmodules)) {
4141 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4142 CmdArgs.push_back("-dwarf-ext-refs");
4143 CmdArgs.push_back("-fmodule-format=obj");
4144 }
4145
4146 // -gsplit-dwarf should turn on -g and enable the backend dwarf
4147 // splitting and extraction.
4148 // FIXME: Currently only works on Linux.
4149 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4150 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4151 CmdArgs.push_back("-backend-option");
4152 CmdArgs.push_back("-split-dwarf=Enable");
4153 }
4154
4155 // After we've dealt with all combinations of things that could
4156 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4157 // figure out if we need to "upgrade" it to standalone debug info.
4158 // We parse these two '-f' options whether or not they will be used,
4159 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4160 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4161 options::OPT_fno_standalone_debug,
4162 getToolChain().GetDefaultStandaloneDebug());
4163 if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
4164 DebugInfoKind = CodeGenOptions::FullDebugInfo;
4165 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4166 DebuggerTuning);
4167
4168 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4169 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4170 CmdArgs.push_back("-backend-option");
4171 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4172 }
4173
4174 // -gdwarf-aranges turns on the emission of the aranges section in the
4175 // backend.
4176 // Always enabled on the PS4.
4177 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4178 CmdArgs.push_back("-backend-option");
4179 CmdArgs.push_back("-generate-arange-section");
4180 }
4181
4182 if (Args.hasFlag(options::OPT_fdebug_types_section,
4183 options::OPT_fno_debug_types_section, false)) {
4184 CmdArgs.push_back("-backend-option");
4185 CmdArgs.push_back("-generate-type-units");
4186 }
4187
4188 // CloudABI uses -ffunction-sections and -fdata-sections by default.
4189 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
4190
4191 if (Args.hasFlag(options::OPT_ffunction_sections,
4192 options::OPT_fno_function_sections, UseSeparateSections)) {
4193 CmdArgs.push_back("-ffunction-sections");
4194 }
4195
4196 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4197 UseSeparateSections)) {
4198 CmdArgs.push_back("-fdata-sections");
4199 }
4200
4201 if (!Args.hasFlag(options::OPT_funique_section_names,
4202 options::OPT_fno_unique_section_names, true))
4203 CmdArgs.push_back("-fno-unique-section-names");
4204
4205 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4206
4207 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4208
4209 // Add runtime flag for PS4 when PGO or Coverage are enabled.
4210 if (getToolChain().getTriple().isPS4CPU())
4211 addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4212
4213 // Pass options for controlling the default header search paths.
4214 if (Args.hasArg(options::OPT_nostdinc)) {
4215 CmdArgs.push_back("-nostdsysteminc");
4216 CmdArgs.push_back("-nobuiltininc");
4217 } else {
4218 if (Args.hasArg(options::OPT_nostdlibinc))
4219 CmdArgs.push_back("-nostdsysteminc");
4220 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4221 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4222 }
4223
4224 // Pass the path to compiler resource files.
4225 CmdArgs.push_back("-resource-dir");
4226 CmdArgs.push_back(D.ResourceDir.c_str());
4227
4228 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4229
4230 bool ARCMTEnabled = false;
4231 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4232 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4233 options::OPT_ccc_arcmt_modify,
4234 options::OPT_ccc_arcmt_migrate)) {
4235 ARCMTEnabled = true;
4236 switch (A->getOption().getID()) {
4237 default:
4238 llvm_unreachable("missed a case");
4239 case options::OPT_ccc_arcmt_check:
4240 CmdArgs.push_back("-arcmt-check");
4241 break;
4242 case options::OPT_ccc_arcmt_modify:
4243 CmdArgs.push_back("-arcmt-modify");
4244 break;
4245 case options::OPT_ccc_arcmt_migrate:
4246 CmdArgs.push_back("-arcmt-migrate");
4247 CmdArgs.push_back("-mt-migrate-directory");
4248 CmdArgs.push_back(A->getValue());
4249
4250 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4251 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4252 break;
4253 }
4254 }
4255 } else {
4256 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4257 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4258 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4259 }
4260
4261 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4262 if (ARCMTEnabled) {
4263 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4264 << "-ccc-arcmt-migrate";
4265 }
4266 CmdArgs.push_back("-mt-migrate-directory");
4267 CmdArgs.push_back(A->getValue());
4268
4269 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4270 options::OPT_objcmt_migrate_subscripting,
4271 options::OPT_objcmt_migrate_property)) {
4272 // None specified, means enable them all.
4273 CmdArgs.push_back("-objcmt-migrate-literals");
4274 CmdArgs.push_back("-objcmt-migrate-subscripting");
4275 CmdArgs.push_back("-objcmt-migrate-property");
4276 } else {
4277 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4278 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4279 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4280 }
4281 } else {
4282 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4283 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4284 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4285 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4286 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4287 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4288 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4289 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4290 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4291 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4292 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4293 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4294 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4295 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4296 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4297 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4298 }
4299
4300 // Add preprocessing options like -I, -D, etc. if we are using the
4301 // preprocessor.
4302 //
4303 // FIXME: Support -fpreprocessed
4304 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4305 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4306 AuxToolChain);
4307
4308 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4309 // that "The compiler can only warn and ignore the option if not recognized".
4310 // When building with ccache, it will pass -D options to clang even on
4311 // preprocessed inputs and configure concludes that -fPIC is not supported.
4312 Args.ClaimAllArgs(options::OPT_D);
4313
4314 // Manually translate -O4 to -O3; let clang reject others.
4315 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4316 if (A->getOption().matches(options::OPT_O4)) {
4317 CmdArgs.push_back("-O3");
4318 D.Diag(diag::warn_O4_is_O3);
4319 } else {
4320 A->render(Args, CmdArgs);
4321 }
4322 }
4323
4324 // Warn about ignored options to clang.
4325 for (const Arg *A :
4326 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4327 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4328 A->claim();
4329 }
4330
4331 claimNoWarnArgs(Args);
4332
4333 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4334 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4335 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4336 CmdArgs.push_back("-pedantic");
4337 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4338 Args.AddLastArg(CmdArgs, options::OPT_w);
4339
4340 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4341 // (-ansi is equivalent to -std=c89 or -std=c++98).
4342 //
4343 // If a std is supplied, only add -trigraphs if it follows the
4344 // option.
4345 bool ImplyVCPPCXXVer = false;
4346 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4347 if (Std->getOption().matches(options::OPT_ansi))
4348 if (types::isCXX(InputType))
4349 CmdArgs.push_back("-std=c++98");
4350 else
4351 CmdArgs.push_back("-std=c89");
4352 else
4353 Std->render(Args, CmdArgs);
4354
4355 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4356 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4357 options::OPT_ftrigraphs,
4358 options::OPT_fno_trigraphs))
4359 if (A != Std)
4360 A->render(Args, CmdArgs);
4361 } else {
4362 // Honor -std-default.
4363 //
4364 // FIXME: Clang doesn't correctly handle -std= when the input language
4365 // doesn't match. For the time being just ignore this for C++ inputs;
4366 // eventually we want to do all the standard defaulting here instead of
4367 // splitting it between the driver and clang -cc1.
4368 if (!types::isCXX(InputType))
4369 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4370 /*Joined=*/true);
4371 else if (IsWindowsMSVC)
4372 ImplyVCPPCXXVer = true;
4373
4374 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4375 options::OPT_fno_trigraphs);
4376 }
4377
4378 // GCC's behavior for -Wwrite-strings is a bit strange:
4379 // * In C, this "warning flag" changes the types of string literals from
4380 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4381 // for the discarded qualifier.
4382 // * In C++, this is just a normal warning flag.
4383 //
4384 // Implementing this warning correctly in C is hard, so we follow GCC's
4385 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4386 // a non-const char* in C, rather than using this crude hack.
4387 if (!types::isCXX(InputType)) {
4388 // FIXME: This should behave just like a warning flag, and thus should also
4389 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4390 Arg *WriteStrings =
4391 Args.getLastArg(options::OPT_Wwrite_strings,
4392 options::OPT_Wno_write_strings, options::OPT_w);
4393 if (WriteStrings &&
4394 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4395 CmdArgs.push_back("-fconst-strings");
4396 }
4397
4398 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4399 // during C++ compilation, which it is by default. GCC keeps this define even
4400 // in the presence of '-w', match this behavior bug-for-bug.
4401 if (types::isCXX(InputType) &&
4402 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4403 true)) {
4404 CmdArgs.push_back("-fdeprecated-macro");
4405 }
4406
4407 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4408 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4409 if (Asm->getOption().matches(options::OPT_fasm))
4410 CmdArgs.push_back("-fgnu-keywords");
4411 else
4412 CmdArgs.push_back("-fno-gnu-keywords");
4413 }
4414
4415 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4416 CmdArgs.push_back("-fno-dwarf-directory-asm");
4417
4418 if (ShouldDisableAutolink(Args, getToolChain()))
4419 CmdArgs.push_back("-fno-autolink");
4420
4421 // Add in -fdebug-compilation-dir if necessary.
4422 addDebugCompDirArg(Args, CmdArgs);
4423
4424 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4425 StringRef Map = A->getValue();
4426 if (Map.find('=') == StringRef::npos)
4427 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4428 else
4429 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4430 A->claim();
4431 }
4432
4433 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4434 options::OPT_ftemplate_depth_EQ)) {
4435 CmdArgs.push_back("-ftemplate-depth");
4436 CmdArgs.push_back(A->getValue());
4437 }
4438
4439 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4440 CmdArgs.push_back("-foperator-arrow-depth");
4441 CmdArgs.push_back(A->getValue());
4442 }
4443
4444 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4445 CmdArgs.push_back("-fconstexpr-depth");
4446 CmdArgs.push_back(A->getValue());
4447 }
4448
4449 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4450 CmdArgs.push_back("-fconstexpr-steps");
4451 CmdArgs.push_back(A->getValue());
4452 }
4453
4454 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4455 CmdArgs.push_back("-fbracket-depth");
4456 CmdArgs.push_back(A->getValue());
4457 }
4458
4459 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4460 options::OPT_Wlarge_by_value_copy_def)) {
4461 if (A->getNumValues()) {
4462 StringRef bytes = A->getValue();
4463 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4464 } else
4465 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4466 }
4467
4468 if (Args.hasArg(options::OPT_relocatable_pch))
4469 CmdArgs.push_back("-relocatable-pch");
4470
4471 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4472 CmdArgs.push_back("-fconstant-string-class");
4473 CmdArgs.push_back(A->getValue());
4474 }
4475
4476 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4477 CmdArgs.push_back("-ftabstop");
4478 CmdArgs.push_back(A->getValue());
4479 }
4480
4481 CmdArgs.push_back("-ferror-limit");
4482 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4483 CmdArgs.push_back(A->getValue());
4484 else
4485 CmdArgs.push_back("19");
4486
4487 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4488 CmdArgs.push_back("-fmacro-backtrace-limit");
4489 CmdArgs.push_back(A->getValue());
4490 }
4491
4492 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4493 CmdArgs.push_back("-ftemplate-backtrace-limit");
4494 CmdArgs.push_back(A->getValue());
4495 }
4496
4497 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4498 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4499 CmdArgs.push_back(A->getValue());
4500 }
4501
4502 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4503 CmdArgs.push_back("-fspell-checking-limit");
4504 CmdArgs.push_back(A->getValue());
4505 }
4506
4507 // Pass -fmessage-length=.
4508 CmdArgs.push_back("-fmessage-length");
4509 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4510 CmdArgs.push_back(A->getValue());
4511 } else {
4512 // If -fmessage-length=N was not specified, determine whether this is a
4513 // terminal and, if so, implicitly define -fmessage-length appropriately.
4514 unsigned N = llvm::sys::Process::StandardErrColumns();
4515 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4516 }
4517
4518 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4519 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4520 options::OPT_fvisibility_ms_compat)) {
4521 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4522 CmdArgs.push_back("-fvisibility");
4523 CmdArgs.push_back(A->getValue());
4524 } else {
4525 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4526 CmdArgs.push_back("-fvisibility");
4527 CmdArgs.push_back("hidden");
4528 CmdArgs.push_back("-ftype-visibility");
4529 CmdArgs.push_back("default");
4530 }
4531 }
4532
4533 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4534
4535 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4536
4537 // -fhosted is default.
4538 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4539 KernelOrKext)
4540 CmdArgs.push_back("-ffreestanding");
4541
4542 // Forward -f (flag) options which we can pass directly.
4543 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4544 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4545 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4546 // Emulated TLS is enabled by default on Android, and can be enabled manually
4547 // with -femulated-tls.
4548 bool EmulatedTLSDefault = Triple.isAndroid();
4549 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4550 EmulatedTLSDefault))
4551 CmdArgs.push_back("-femulated-tls");
4552 // AltiVec-like language extensions aren't relevant for assembling.
4553 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4554 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4555 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4556 }
4557 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4558 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4559
4560 // Forward flags for OpenMP
4561 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4562 options::OPT_fno_openmp, false))
4563 switch (getOpenMPRuntime(getToolChain(), Args)) {
4564 case OMPRT_OMP:
4565 case OMPRT_IOMP5:
4566 // Clang can generate useful OpenMP code for these two runtime libraries.
4567 CmdArgs.push_back("-fopenmp");
4568
4569 // If no option regarding the use of TLS in OpenMP codegeneration is
4570 // given, decide a default based on the target. Otherwise rely on the
4571 // options and pass the right information to the frontend.
4572 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4573 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4574 CmdArgs.push_back("-fnoopenmp-use-tls");
4575 break;
4576 default:
4577 // By default, if Clang doesn't know how to generate useful OpenMP code
4578 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4579 // down to the actual compilation.
4580 // FIXME: It would be better to have a mode which *only* omits IR
4581 // generation based on the OpenMP support so that we get consistent
4582 // semantic analysis, etc.
4583 break;
4584 }
4585
4586 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4587 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4588
4589 // Report an error for -faltivec on anything other than PowerPC.
4590 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4591 const llvm::Triple::ArchType Arch = getToolChain().getArch();
4592 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4593 Arch == llvm::Triple::ppc64le))
4594 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4595 << "ppc/ppc64/ppc64le";
4596 }
4597
4598 // -fzvector is incompatible with -faltivec.
4599 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4600 if (Args.hasArg(options::OPT_faltivec))
4601 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4602 << "-faltivec";
4603
4604 if (getToolChain().SupportsProfiling())
4605 Args.AddLastArg(CmdArgs, options::OPT_pg);
4606
4607 // -flax-vector-conversions is default.
4608 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4609 options::OPT_fno_lax_vector_conversions))
4610 CmdArgs.push_back("-fno-lax-vector-conversions");
4611
4612 if (Args.getLastArg(options::OPT_fapple_kext) ||
4613 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4614 CmdArgs.push_back("-fapple-kext");
4615
4616 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4617 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4618 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4619 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4620 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4621
4622 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4623 CmdArgs.push_back("-ftrapv-handler");
4624 CmdArgs.push_back(A->getValue());
4625 }
4626
4627 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4628
4629 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4630 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4631 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4632 if (A->getOption().matches(options::OPT_fwrapv))
4633 CmdArgs.push_back("-fwrapv");
4634 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4635 options::OPT_fno_strict_overflow)) {
4636 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4637 CmdArgs.push_back("-fwrapv");
4638 }
4639
4640 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4641 options::OPT_fno_reroll_loops))
4642 if (A->getOption().matches(options::OPT_freroll_loops))
4643 CmdArgs.push_back("-freroll-loops");
4644
4645 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4646 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4647 options::OPT_fno_unroll_loops);
4648
4649 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4650
4651 // -stack-protector=0 is default.
4652 unsigned StackProtectorLevel = 0;
4653 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4654 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4655 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4656 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4657 Args.ClaimAllArgs(options::OPT_fstack_protector);
4658 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4659 options::OPT_fstack_protector_all,
4660 options::OPT_fstack_protector_strong,
4661 options::OPT_fstack_protector)) {
4662 if (A->getOption().matches(options::OPT_fstack_protector)) {
4663 StackProtectorLevel = std::max<unsigned>(
4664 LangOptions::SSPOn,
4665 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4666 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4667 StackProtectorLevel = LangOptions::SSPStrong;
4668 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4669 StackProtectorLevel = LangOptions::SSPReq;
4670 } else {
4671 StackProtectorLevel =
4672 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4673 }
4674 if (StackProtectorLevel) {
4675 CmdArgs.push_back("-stack-protector");
4676 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4677 }
4678
4679 // --param ssp-buffer-size=
4680 for (const Arg *A : Args.filtered(options::OPT__param)) {
4681 StringRef Str(A->getValue());
4682 if (Str.startswith("ssp-buffer-size=")) {
4683 if (StackProtectorLevel) {
4684 CmdArgs.push_back("-stack-protector-buffer-size");
4685 // FIXME: Verify the argument is a valid integer.
4686 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4687 }
4688 A->claim();
4689 }
4690 }
4691
4692 // Translate -mstackrealign
4693 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4694 false))
4695 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4696
4697 if (Args.hasArg(options::OPT_mstack_alignment)) {
4698 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4699 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4700 }
4701
4702 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4703 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4704
4705 if (!Size.empty())
4706 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4707 else
4708 CmdArgs.push_back("-mstack-probe-size=0");
4709 }
4710
4711 switch (getToolChain().getArch()) {
4712 case llvm::Triple::aarch64:
4713 case llvm::Triple::aarch64_be:
4714 case llvm::Triple::arm:
4715 case llvm::Triple::armeb:
4716 case llvm::Triple::thumb:
4717 case llvm::Triple::thumbeb:
4718 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4719 break;
4720
4721 default:
4722 break;
4723 }
4724
4725 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4726 options::OPT_mno_restrict_it)) {
4727 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4728 CmdArgs.push_back("-backend-option");
4729 CmdArgs.push_back("-arm-restrict-it");
4730 } else {
4731 CmdArgs.push_back("-backend-option");
4732 CmdArgs.push_back("-arm-no-restrict-it");
4733 }
4734 } else if (Triple.isOSWindows() &&
4735 (Triple.getArch() == llvm::Triple::arm ||
4736 Triple.getArch() == llvm::Triple::thumb)) {
4737 // Windows on ARM expects restricted IT blocks
4738 CmdArgs.push_back("-backend-option");
4739 CmdArgs.push_back("-arm-restrict-it");
4740 }
4741
4742 // Forward -f options with positive and negative forms; we translate
4743 // these by hand.
4744 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4745 StringRef fname = A->getValue();
4746 if (!llvm::sys::fs::exists(fname))
4747 D.Diag(diag::err_drv_no_such_file) << fname;
4748 else
4749 A->render(Args, CmdArgs);
4750 }
4751
4752 // -fbuiltin is default unless -mkernel is used
4753 if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4754 !Args.hasArg(options::OPT_mkernel)))
4755 CmdArgs.push_back("-fno-builtin");
4756
4757 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4758 options::OPT_fno_assume_sane_operator_new))
4759 CmdArgs.push_back("-fno-assume-sane-operator-new");
4760
4761 // -fblocks=0 is default.
4762 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4763 getToolChain().IsBlocksDefault()) ||
4764 (Args.hasArg(options::OPT_fgnu_runtime) &&
4765 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4766 !Args.hasArg(options::OPT_fno_blocks))) {
4767 CmdArgs.push_back("-fblocks");
4768
4769 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4770 !getToolChain().hasBlocksRuntime())
4771 CmdArgs.push_back("-fblocks-runtime-optional");
4772 }
4773
4774 // -fmodules enables the use of precompiled modules (off by default).
4775 // Users can pass -fno-cxx-modules to turn off modules support for
4776 // C++/Objective-C++ programs.
4777 bool HaveModules = false;
4778 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4779 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4780 options::OPT_fno_cxx_modules, true);
4781 if (AllowedInCXX || !types::isCXX(InputType)) {
4782 CmdArgs.push_back("-fmodules");
4783 HaveModules = true;
4784 }
4785 }
4786
4787 // -fmodule-maps enables implicit reading of module map files. By default,
4788 // this is enabled if we are using precompiled modules.
4789 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4790 options::OPT_fno_implicit_module_maps, HaveModules)) {
4791 CmdArgs.push_back("-fimplicit-module-maps");
4792 }
4793
4794 // -fmodules-decluse checks that modules used are declared so (off by
4795 // default).
4796 if (Args.hasFlag(options::OPT_fmodules_decluse,
4797 options::OPT_fno_modules_decluse, false)) {
4798 CmdArgs.push_back("-fmodules-decluse");
4799 }
4800
4801 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4802 // all #included headers are part of modules.
4803 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4804 options::OPT_fno_modules_strict_decluse, false)) {
4805 CmdArgs.push_back("-fmodules-strict-decluse");
4806 }
4807
4808 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4809 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4810 options::OPT_fno_implicit_modules)) {
4811 CmdArgs.push_back("-fno-implicit-modules");
4812 }
4813
4814 // -fmodule-name specifies the module that is currently being built (or
4815 // used for header checking by -fmodule-maps).
4816 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4817
4818 // -fmodule-map-file can be used to specify files containing module
4819 // definitions.
4820 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4821
4822 // -fmodule-file can be used to specify files containing precompiled modules.
4823 if (HaveModules)
4824 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4825 else
4826 Args.ClaimAllArgs(options::OPT_fmodule_file);
4827
4828 // -fmodule-cache-path specifies where our implicitly-built module files
4829 // should be written.
4830 SmallString<128> Path;
4831 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4832 Path = A->getValue();
4833 if (HaveModules) {
4834 if (C.isForDiagnostics()) {
4835 // When generating crash reports, we want to emit the modules along with
4836 // the reproduction sources, so we ignore any provided module path.
4837 Path = Output.getFilename();
4838 llvm::sys::path::replace_extension(Path, ".cache");
4839 llvm::sys::path::append(Path, "modules");
4840 } else if (Path.empty()) {
4841 // No module path was provided: use the default.
4842 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4843 llvm::sys::path::append(Path, "org.llvm.clang.");
4844 appendUserToPath(Path);
4845 llvm::sys::path::append(Path, "ModuleCache");
4846 }
4847 const char Arg[] = "-fmodules-cache-path=";
4848 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4849 CmdArgs.push_back(Args.MakeArgString(Path));
4850 }
4851
4852 // When building modules and generating crashdumps, we need to dump a module
4853 // dependency VFS alongside the output.
4854 if (HaveModules && C.isForDiagnostics()) {
4855 SmallString<128> VFSDir(Output.getFilename());
4856 llvm::sys::path::replace_extension(VFSDir, ".cache");
4857 // Add the cache directory as a temp so the crash diagnostics pick it up.
4858 C.addTempFile(Args.MakeArgString(VFSDir));
4859
4860 llvm::sys::path::append(VFSDir, "vfs");
4861 CmdArgs.push_back("-module-dependency-dir");
4862 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4863 }
4864
4865 if (HaveModules)
4866 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4867
4868 // Pass through all -fmodules-ignore-macro arguments.
4869 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4870 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4871 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4872
4873 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4874
4875 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4876 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4877 D.Diag(diag::err_drv_argument_not_allowed_with)
4878 << A->getAsString(Args) << "-fbuild-session-timestamp";
4879
4880 llvm::sys::fs::file_status Status;
4881 if (llvm::sys::fs::status(A->getValue(), Status))
4882 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4883 CmdArgs.push_back(Args.MakeArgString(
4884 "-fbuild-session-timestamp=" +
4885 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4886 }
4887
4888 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4889 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4890 options::OPT_fbuild_session_file))
4891 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4892
4893 Args.AddLastArg(CmdArgs,
4894 options::OPT_fmodules_validate_once_per_build_session);
4895 }
4896
4897 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4898
4899 // -faccess-control is default.
4900 if (Args.hasFlag(options::OPT_fno_access_control,
4901 options::OPT_faccess_control, false))
4902 CmdArgs.push_back("-fno-access-control");
4903
4904 // -felide-constructors is the default.
4905 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4906 options::OPT_felide_constructors, false))
4907 CmdArgs.push_back("-fno-elide-constructors");
4908
4909 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4910
4911 if (KernelOrKext || (types::isCXX(InputType) &&
4912 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4913 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4914 CmdArgs.push_back("-fno-rtti");
4915
4916 // -fshort-enums=0 is default for all architectures except Hexagon.
4917 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4918 getToolChain().getArch() == llvm::Triple::hexagon))
4919 CmdArgs.push_back("-fshort-enums");
4920
4921 // -fsigned-char is default.
4922 if (Arg *A = Args.getLastArg(
4923 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4924 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4925 if (A->getOption().matches(options::OPT_funsigned_char) ||
4926 A->getOption().matches(options::OPT_fno_signed_char)) {
4927 CmdArgs.push_back("-fno-signed-char");
4928 }
4929 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4930 CmdArgs.push_back("-fno-signed-char");
4931 }
4932
4933 // -fuse-cxa-atexit is default.
4934 if (!Args.hasFlag(
4935 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4936 !IsWindowsCygnus && !IsWindowsGNU &&
4937 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
4938 getToolChain().getArch() != llvm::Triple::hexagon &&
4939 getToolChain().getArch() != llvm::Triple::xcore &&
4940 ((getToolChain().getTriple().getVendor() !=
4941 llvm::Triple::MipsTechnologies) ||
4942 getToolChain().getTriple().hasEnvironment())) ||
4943 KernelOrKext)
4944 CmdArgs.push_back("-fno-use-cxa-atexit");
4945
4946 // -fms-extensions=0 is default.
4947 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4948 IsWindowsMSVC))
4949 CmdArgs.push_back("-fms-extensions");
4950
4951 // -fno-use-line-directives is default.
4952 if (Args.hasFlag(options::OPT_fuse_line_directives,
4953 options::OPT_fno_use_line_directives, false))
4954 CmdArgs.push_back("-fuse-line-directives");
4955
4956 // -fms-compatibility=0 is default.
4957 if (Args.hasFlag(options::OPT_fms_compatibility,
4958 options::OPT_fno_ms_compatibility,
4959 (IsWindowsMSVC &&
4960 Args.hasFlag(options::OPT_fms_extensions,
4961 options::OPT_fno_ms_extensions, true))))
4962 CmdArgs.push_back("-fms-compatibility");
4963
4964 // -fms-compatibility-version=18.00 is default.
4965 VersionTuple MSVT = visualstudio::getMSVCVersion(
4966 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4967 if (!MSVT.empty())
4968 CmdArgs.push_back(
4969 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4970
4971 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4972 if (ImplyVCPPCXXVer) {
4973 if (IsMSVC2015Compatible)
4974 CmdArgs.push_back("-std=c++14");
4975 else
4976 CmdArgs.push_back("-std=c++11");
4977 }
4978
4979 // -fno-borland-extensions is default.
4980 if (Args.hasFlag(options::OPT_fborland_extensions,
4981 options::OPT_fno_borland_extensions, false))
4982 CmdArgs.push_back("-fborland-extensions");
4983
4984 // -fno-declspec is default, except for PS4.
4985 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4986 getToolChain().getTriple().isPS4()))
4987 CmdArgs.push_back("-fdeclspec");
4988 else if (Args.hasArg(options::OPT_fno_declspec))
4989 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4990
4991 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4992 // than 19.
4993 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4994 options::OPT_fno_threadsafe_statics,
4995 !IsWindowsMSVC || IsMSVC2015Compatible))
4996 CmdArgs.push_back("-fno-threadsafe-statics");
4997
4998 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4999 // needs it.
5000 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5001 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5002 CmdArgs.push_back("-fdelayed-template-parsing");
5003
5004 // -fgnu-keywords default varies depending on language; only pass if
5005 // specified.
5006 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5007 options::OPT_fno_gnu_keywords))
5008 A->render(Args, CmdArgs);
5009
5010 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5011 false))
5012 CmdArgs.push_back("-fgnu89-inline");
5013
5014 if (Args.hasArg(options::OPT_fno_inline))
5015 CmdArgs.push_back("-fno-inline");
5016
5017 if (Args.hasArg(options::OPT_fno_inline_functions))
5018 CmdArgs.push_back("-fno-inline-functions");
5019
5020 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5021
5022 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5023 // legacy is the default. Except for deployment taget of 10.5,
5024 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5025 // gets ignored silently.
5026 if (objcRuntime.isNonFragile()) {
5027 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5028 options::OPT_fno_objc_legacy_dispatch,
5029 objcRuntime.isLegacyDispatchDefaultForArch(
5030 getToolChain().getArch()))) {
5031 if (getToolChain().UseObjCMixedDispatch())
5032 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5033 else
5034 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5035 }
5036 }
5037
5038 // When ObjectiveC legacy runtime is in effect on MacOSX,
5039 // turn on the option to do Array/Dictionary subscripting
5040 // by default.
5041 if (getToolChain().getArch() == llvm::Triple::x86 &&
5042 getToolChain().getTriple().isMacOSX() &&
5043 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5044 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5045 objcRuntime.isNeXTFamily())
5046 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5047
5048 // -fencode-extended-block-signature=1 is default.
5049 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5050 CmdArgs.push_back("-fencode-extended-block-signature");
5051 }
5052
5053 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5054 // NOTE: This logic is duplicated in ToolChains.cpp.
5055 bool ARC = isObjCAutoRefCount(Args);
5056 if (ARC) {
5057 getToolChain().CheckObjCARC();
5058
5059 CmdArgs.push_back("-fobjc-arc");
5060
5061 // FIXME: It seems like this entire block, and several around it should be
5062 // wrapped in isObjC, but for now we just use it here as this is where it
5063 // was being used previously.
5064 if (types::isCXX(InputType) && types::isObjC(InputType)) {
5065 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5066 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5067 else
5068 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5069 }
5070
5071 // Allow the user to enable full exceptions code emission.
5072 // We define off for Objective-CC, on for Objective-C++.
5073 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5074 options::OPT_fno_objc_arc_exceptions,
5075 /*default*/ types::isCXX(InputType)))
5076 CmdArgs.push_back("-fobjc-arc-exceptions");
5077
5078 }
5079
5080 // -fobjc-infer-related-result-type is the default, except in the Objective-C
5081 // rewriter.
5082 if (rewriteKind != RK_None)
5083 CmdArgs.push_back("-fno-objc-infer-related-result-type");
5084
5085 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5086 // takes precedence.
5087 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5088 if (!GCArg)
5089 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5090 if (GCArg) {
5091 if (ARC) {
5092 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5093 } else if (getToolChain().SupportsObjCGC()) {
5094 GCArg->render(Args, CmdArgs);
5095 } else {
5096 // FIXME: We should move this to a hard error.
5097 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5098 }
5099 }
5100
5101 // Pass down -fobjc-weak or -fno-objc-weak if present.
5102 if (types::isObjC(InputType)) {
5103 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5104 options::OPT_fno_objc_weak);
5105 if (!WeakArg) {
5106 // nothing to do
5107 } else if (GCArg) {
5108 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5109 D.Diag(diag::err_objc_weak_with_gc);
5110 } else if (!objcRuntime.allowsWeak()) {
5111 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5112 D.Diag(diag::err_objc_weak_unsupported);
5113 } else {
5114 WeakArg->render(Args, CmdArgs);
5115 }
5116 }
5117
5118 if (Args.hasFlag(options::OPT_fapplication_extension,
5119 options::OPT_fno_application_extension, false))
5120 CmdArgs.push_back("-fapplication-extension");
5121
5122 // Handle GCC-style exception args.
5123 if (!C.getDriver().IsCLMode())
5124 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5125 CmdArgs);
5126
5127 if (getToolChain().UseSjLjExceptions(Args))
5128 CmdArgs.push_back("-fsjlj-exceptions");
5129
5130 // C++ "sane" operator new.
5131 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5132 options::OPT_fno_assume_sane_operator_new))
5133 CmdArgs.push_back("-fno-assume-sane-operator-new");
5134
5135 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5136 // most platforms.
5137 if (Args.hasFlag(options::OPT_fsized_deallocation,
5138 options::OPT_fno_sized_deallocation, false))
5139 CmdArgs.push_back("-fsized-deallocation");
5140
5141 // -fconstant-cfstrings is default, and may be subject to argument translation
5142 // on Darwin.
5143 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5144 options::OPT_fno_constant_cfstrings) ||
5145 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5146 options::OPT_mno_constant_cfstrings))
5147 CmdArgs.push_back("-fno-constant-cfstrings");
5148
5149 // -fshort-wchar default varies depending on platform; only
5150 // pass if specified.
5151 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5152 options::OPT_fno_short_wchar))
5153 A->render(Args, CmdArgs);
5154
5155 // -fno-pascal-strings is default, only pass non-default.
5156 if (Args.hasFlag(options::OPT_fpascal_strings,
5157 options::OPT_fno_pascal_strings, false))
5158 CmdArgs.push_back("-fpascal-strings");
5159
5160 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5161 // -fno-pack-struct doesn't apply to -fpack-struct=.
5162 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5163 std::string PackStructStr = "-fpack-struct=";
5164 PackStructStr += A->getValue();
5165 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5166 } else if (Args.hasFlag(options::OPT_fpack_struct,
5167 options::OPT_fno_pack_struct, false)) {
5168 CmdArgs.push_back("-fpack-struct=1");
5169 }
5170
5171 // Handle -fmax-type-align=N and -fno-type-align
5172 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5173 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5174 if (!SkipMaxTypeAlign) {
5175 std::string MaxTypeAlignStr = "-fmax-type-align=";
5176 MaxTypeAlignStr += A->getValue();
5177 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5178 }
5179 } else if (getToolChain().getTriple().isOSDarwin()) {
5180 if (!SkipMaxTypeAlign) {
5181 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5182 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5183 }
5184 }
5185
5186 // -fcommon is the default unless compiling kernel code or the target says so
5187 bool NoCommonDefault =
5188 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5189 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5190 !NoCommonDefault))
5191 CmdArgs.push_back("-fno-common");
5192
5193 // -fsigned-bitfields is default, and clang doesn't yet support
5194 // -funsigned-bitfields.
5195 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5196 options::OPT_funsigned_bitfields))
5197 D.Diag(diag::warn_drv_clang_unsupported)
5198 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5199
5200 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5201 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5202 D.Diag(diag::err_drv_clang_unsupported)
5203 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5204
5205 // -finput_charset=UTF-8 is default. Reject others
5206 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5207 StringRef value = inputCharset->getValue();
5208 if (value != "UTF-8")
5209 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5210 << value;
5211 }
5212
5213 // -fexec_charset=UTF-8 is default. Reject others
5214 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5215 StringRef value = execCharset->getValue();
5216 if (value != "UTF-8")
5217 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5218 << value;
5219 }
5220
5221 // -fcaret-diagnostics is default.
5222 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5223 options::OPT_fno_caret_diagnostics, true))
5224 CmdArgs.push_back("-fno-caret-diagnostics");
5225
5226 // -fdiagnostics-fixit-info is default, only pass non-default.
5227 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5228 options::OPT_fno_diagnostics_fixit_info))
5229 CmdArgs.push_back("-fno-diagnostics-fixit-info");
5230
5231 // Enable -fdiagnostics-show-option by default.
5232 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5233 options::OPT_fno_diagnostics_show_option))
5234 CmdArgs.push_back("-fdiagnostics-show-option");
5235
5236 if (const Arg *A =
5237 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5238 CmdArgs.push_back("-fdiagnostics-show-category");
5239 CmdArgs.push_back(A->getValue());
5240 }
5241
5242 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5243 CmdArgs.push_back("-fdiagnostics-format");
5244 CmdArgs.push_back(A->getValue());
5245 }
5246
5247 if (Arg *A = Args.getLastArg(
5248 options::OPT_fdiagnostics_show_note_include_stack,
5249 options::OPT_fno_diagnostics_show_note_include_stack)) {
5250 if (A->getOption().matches(
5251 options::OPT_fdiagnostics_show_note_include_stack))
5252 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5253 else
5254 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5255 }
5256
5257 // Color diagnostics are the default, unless the terminal doesn't support
5258 // them.
5259 // Support both clang's -f[no-]color-diagnostics and gcc's
5260 // -f[no-]diagnostics-colors[=never|always|auto].
5261 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
5262 for (const auto &Arg : Args) {
5263 const Option &O = Arg->getOption();
5264 if (!O.matches(options::OPT_fcolor_diagnostics) &&
5265 !O.matches(options::OPT_fdiagnostics_color) &&
5266 !O.matches(options::OPT_fno_color_diagnostics) &&
5267 !O.matches(options::OPT_fno_diagnostics_color) &&
5268 !O.matches(options::OPT_fdiagnostics_color_EQ))
5269 continue;
5270
5271 Arg->claim();
5272 if (O.matches(options::OPT_fcolor_diagnostics) ||
5273 O.matches(options::OPT_fdiagnostics_color)) {
5274 ShowColors = Colors_On;
5275 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
5276 O.matches(options::OPT_fno_diagnostics_color)) {
5277 ShowColors = Colors_Off;
5278 } else {
5279 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
5280 StringRef value(Arg->getValue());
5281 if (value == "always")
5282 ShowColors = Colors_On;
5283 else if (value == "never")
5284 ShowColors = Colors_Off;
5285 else if (value == "auto")
5286 ShowColors = Colors_Auto;
5287 else
5288 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5289 << ("-fdiagnostics-color=" + value).str();
5290 }
5291 }
5292 if (ShowColors == Colors_On ||
5293 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
5294 CmdArgs.push_back("-fcolor-diagnostics");
5295
5296 if (Args.hasArg(options::OPT_fansi_escape_codes))
5297 CmdArgs.push_back("-fansi-escape-codes");
5298
5299 if (!Args.hasFlag(options::OPT_fshow_source_location,
5300 options::OPT_fno_show_source_location))
5301 CmdArgs.push_back("-fno-show-source-location");
5302
5303 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5304 true))
5305 CmdArgs.push_back("-fno-show-column");
5306
5307 if (!Args.hasFlag(options::OPT_fspell_checking,
5308 options::OPT_fno_spell_checking))
5309 CmdArgs.push_back("-fno-spell-checking");
5310
5311 // -fno-asm-blocks is default.
5312 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5313 false))
5314 CmdArgs.push_back("-fasm-blocks");
5315
5316 // -fgnu-inline-asm is default.
5317 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5318 options::OPT_fno_gnu_inline_asm, true))
5319 CmdArgs.push_back("-fno-gnu-inline-asm");
5320
5321 // Enable vectorization per default according to the optimization level
5322 // selected. For optimization levels that want vectorization we use the alias
5323 // option to simplify the hasFlag logic.
5324 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5325 OptSpecifier VectorizeAliasOption =
5326 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5327 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5328 options::OPT_fno_vectorize, EnableVec))
5329 CmdArgs.push_back("-vectorize-loops");
5330
5331 // -fslp-vectorize is enabled based on the optimization level selected.
5332 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5333 OptSpecifier SLPVectAliasOption =
5334 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5335 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5336 options::OPT_fno_slp_vectorize, EnableSLPVec))
5337 CmdArgs.push_back("-vectorize-slp");
5338
5339 // -fno-slp-vectorize-aggressive is default.
5340 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5341 options::OPT_fno_slp_vectorize_aggressive, false))
5342 CmdArgs.push_back("-vectorize-slp-aggressive");
5343
5344 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5345 A->render(Args, CmdArgs);
5346
5347 // -fdollars-in-identifiers default varies depending on platform and
5348 // language; only pass if specified.
5349 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5350 options::OPT_fno_dollars_in_identifiers)) {
5351 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5352 CmdArgs.push_back("-fdollars-in-identifiers");
5353 else
5354 CmdArgs.push_back("-fno-dollars-in-identifiers");
5355 }
5356
5357 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5358 // practical purposes.
5359 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5360 options::OPT_fno_unit_at_a_time)) {
5361 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5362 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5363 }
5364
5365 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5366 options::OPT_fno_apple_pragma_pack, false))
5367 CmdArgs.push_back("-fapple-pragma-pack");
5368
5369 // le32-specific flags:
5370 // -fno-math-builtin: clang should not convert math builtins to intrinsics
5371 // by default.
5372 if (getToolChain().getArch() == llvm::Triple::le32) {
5373 CmdArgs.push_back("-fno-math-builtin");
5374 }
5375
5376 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5377 //
5378 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
5379 #if 0
5380 if (getToolChain().getTriple().isOSDarwin() &&
5381 (getToolChain().getArch() == llvm::Triple::arm ||
5382 getToolChain().getArch() == llvm::Triple::thumb)) {
5383 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5384 CmdArgs.push_back("-fno-builtin-strcat");
5385 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5386 CmdArgs.push_back("-fno-builtin-strcpy");
5387 }
5388 #endif
5389
5390 // Enable rewrite includes if the user's asked for it or if we're generating
5391 // diagnostics.
5392 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5393 // nice to enable this when doing a crashdump for modules as well.
5394 if (Args.hasFlag(options::OPT_frewrite_includes,
5395 options::OPT_fno_rewrite_includes, false) ||
5396 (C.isForDiagnostics() && !HaveModules))
5397 CmdArgs.push_back("-frewrite-includes");
5398
5399 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5400 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5401 options::OPT_traditional_cpp)) {
5402 if (isa<PreprocessJobAction>(JA))
5403 CmdArgs.push_back("-traditional-cpp");
5404 else
5405 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5406 }
5407
5408 Args.AddLastArg(CmdArgs, options::OPT_dM);
5409 Args.AddLastArg(CmdArgs, options::OPT_dD);
5410
5411 // Handle serialized diagnostics.
5412 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5413 CmdArgs.push_back("-serialize-diagnostic-file");
5414 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5415 }
5416
5417 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5418 CmdArgs.push_back("-fretain-comments-from-system-headers");
5419
5420 // Forward -fcomment-block-commands to -cc1.
5421 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5422 // Forward -fparse-all-comments to -cc1.
5423 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5424
5425 // Turn -fplugin=name.so into -load name.so
5426 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5427 CmdArgs.push_back("-load");
5428 CmdArgs.push_back(A->getValue());
5429 A->claim();
5430 }
5431
5432 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5433 // parser.
5434 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5435 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5436 A->claim();
5437
5438 // We translate this by hand to the -cc1 argument, since nightly test uses
5439 // it and developers have been trained to spell it with -mllvm.
5440 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5441 CmdArgs.push_back("-disable-llvm-optzns");
5442 } else
5443 A->render(Args, CmdArgs);
5444 }
5445
5446 // With -save-temps, we want to save the unoptimized bitcode output from the
5447 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5448 // by the frontend.
5449 if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
5450 CmdArgs.push_back("-disable-llvm-passes");
5451
5452 if (Output.getType() == types::TY_Dependencies) {
5453 // Handled with other dependency code.
5454 } else if (Output.isFilename()) {
5455 CmdArgs.push_back("-o");
5456 CmdArgs.push_back(Output.getFilename());
5457 } else {
5458 assert(Output.isNothing() && "Invalid output.");
5459 }
5460
5461 addDashXForInput(Args, Input, CmdArgs);
5462
5463 if (Input.isFilename())
5464 CmdArgs.push_back(Input.getFilename());
5465 else
5466 Input.getInputArg().renderAsInput(Args, CmdArgs);
5467
5468 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5469
5470 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5471
5472 // Optionally embed the -cc1 level arguments into the debug info, for build
5473 // analysis.
5474 if (getToolChain().UseDwarfDebugFlags()) {
5475 ArgStringList OriginalArgs;
5476 for (const auto &Arg : Args)
5477 Arg->render(Args, OriginalArgs);
5478
5479 SmallString<256> Flags;
5480 Flags += Exec;
5481 for (const char *OriginalArg : OriginalArgs) {
5482 SmallString<128> EscapedArg;
5483 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5484 Flags += " ";
5485 Flags += EscapedArg;
5486 }
5487 CmdArgs.push_back("-dwarf-debug-flags");
5488 CmdArgs.push_back(Args.MakeArgString(Flags));
5489 }
5490
5491 // Add the split debug info name to the command lines here so we
5492 // can propagate it to the backend.
5493 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5494 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5495 isa<BackendJobAction>(JA));
5496 const char *SplitDwarfOut;
5497 if (SplitDwarf) {
5498 CmdArgs.push_back("-split-dwarf-file");
5499 SplitDwarfOut = SplitDebugName(Args, Input);
5500 CmdArgs.push_back(SplitDwarfOut);
5501 }
5502
5503 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5504 // Include them with -fcuda-include-gpubinary.
5505 if (IsCuda && Inputs.size() > 1)
5506 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5507 CmdArgs.push_back("-fcuda-include-gpubinary");
5508 CmdArgs.push_back(I->getFilename());
5509 }
5510
5511 // Finally add the compile command to the compilation.
5512 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5513 Output.getType() == types::TY_Object &&
5514 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5515 auto CLCommand =
5516 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5517 C.addCommand(llvm::make_unique<FallbackCommand>(
5518 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5519 } else {
5520 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5521 }
5522
5523 // Handle the debug info splitting at object creation time if we're
5524 // creating an object.
5525 // TODO: Currently only works on linux with newer objcopy.
5526 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5527 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5528
5529 if (Arg *A = Args.getLastArg(options::OPT_pg))
5530 if (Args.hasArg(options::OPT_fomit_frame_pointer))
5531 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5532 << A->getAsString(Args);
5533
5534 // Claim some arguments which clang supports automatically.
5535
5536 // -fpch-preprocess is used with gcc to add a special marker in the output to
5537 // include the PCH file. Clang's PTH solution is completely transparent, so we
5538 // do not need to deal with it at all.
5539 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5540
5541 // Claim some arguments which clang doesn't support, but we don't
5542 // care to warn the user about.
5543 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5544 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5545
5546 // Disable warnings for clang -E -emit-llvm foo.c
5547 Args.ClaimAllArgs(options::OPT_emit_llvm);
5548 }
5549
5550 /// Add options related to the Objective-C runtime/ABI.
5551 ///
5552 /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,ArgStringList & cmdArgs,RewriteKind rewriteKind) const5553 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5554 ArgStringList &cmdArgs,
5555 RewriteKind rewriteKind) const {
5556 // Look for the controlling runtime option.
5557 Arg *runtimeArg =
5558 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5559 options::OPT_fobjc_runtime_EQ);
5560
5561 // Just forward -fobjc-runtime= to the frontend. This supercedes
5562 // options about fragility.
5563 if (runtimeArg &&
5564 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5565 ObjCRuntime runtime;
5566 StringRef value = runtimeArg->getValue();
5567 if (runtime.tryParse(value)) {
5568 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5569 << value;
5570 }
5571
5572 runtimeArg->render(args, cmdArgs);
5573 return runtime;
5574 }
5575
5576 // Otherwise, we'll need the ABI "version". Version numbers are
5577 // slightly confusing for historical reasons:
5578 // 1 - Traditional "fragile" ABI
5579 // 2 - Non-fragile ABI, version 1
5580 // 3 - Non-fragile ABI, version 2
5581 unsigned objcABIVersion = 1;
5582 // If -fobjc-abi-version= is present, use that to set the version.
5583 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5584 StringRef value = abiArg->getValue();
5585 if (value == "1")
5586 objcABIVersion = 1;
5587 else if (value == "2")
5588 objcABIVersion = 2;
5589 else if (value == "3")
5590 objcABIVersion = 3;
5591 else
5592 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5593 } else {
5594 // Otherwise, determine if we are using the non-fragile ABI.
5595 bool nonFragileABIIsDefault =
5596 (rewriteKind == RK_NonFragile ||
5597 (rewriteKind == RK_None &&
5598 getToolChain().IsObjCNonFragileABIDefault()));
5599 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5600 options::OPT_fno_objc_nonfragile_abi,
5601 nonFragileABIIsDefault)) {
5602 // Determine the non-fragile ABI version to use.
5603 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5604 unsigned nonFragileABIVersion = 1;
5605 #else
5606 unsigned nonFragileABIVersion = 2;
5607 #endif
5608
5609 if (Arg *abiArg =
5610 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5611 StringRef value = abiArg->getValue();
5612 if (value == "1")
5613 nonFragileABIVersion = 1;
5614 else if (value == "2")
5615 nonFragileABIVersion = 2;
5616 else
5617 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5618 << value;
5619 }
5620
5621 objcABIVersion = 1 + nonFragileABIVersion;
5622 } else {
5623 objcABIVersion = 1;
5624 }
5625 }
5626
5627 // We don't actually care about the ABI version other than whether
5628 // it's non-fragile.
5629 bool isNonFragile = objcABIVersion != 1;
5630
5631 // If we have no runtime argument, ask the toolchain for its default runtime.
5632 // However, the rewriter only really supports the Mac runtime, so assume that.
5633 ObjCRuntime runtime;
5634 if (!runtimeArg) {
5635 switch (rewriteKind) {
5636 case RK_None:
5637 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5638 break;
5639 case RK_Fragile:
5640 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5641 break;
5642 case RK_NonFragile:
5643 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5644 break;
5645 }
5646
5647 // -fnext-runtime
5648 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5649 // On Darwin, make this use the default behavior for the toolchain.
5650 if (getToolChain().getTriple().isOSDarwin()) {
5651 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5652
5653 // Otherwise, build for a generic macosx port.
5654 } else {
5655 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5656 }
5657
5658 // -fgnu-runtime
5659 } else {
5660 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5661 // Legacy behaviour is to target the gnustep runtime if we are i
5662 // non-fragile mode or the GCC runtime in fragile mode.
5663 if (isNonFragile)
5664 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5665 else
5666 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5667 }
5668
5669 cmdArgs.push_back(
5670 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5671 return runtime;
5672 }
5673
maybeConsumeDash(const std::string & EH,size_t & I)5674 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5675 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5676 I += HaveDash;
5677 return !HaveDash;
5678 }
5679
5680 namespace {
5681 struct EHFlags {
EHFlags__anon322759a80311::EHFlags5682 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5683 bool Synch;
5684 bool Asynch;
5685 bool NoExceptC;
5686 };
5687 } // end anonymous namespace
5688
5689 /// /EH controls whether to run destructor cleanups when exceptions are
5690 /// thrown. There are three modifiers:
5691 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5692 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5693 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5694 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5695 /// modifier is an optimization, so we ignore it for now.
5696 /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args)5697 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5698 EHFlags EH;
5699
5700 std::vector<std::string> EHArgs =
5701 Args.getAllArgValues(options::OPT__SLASH_EH);
5702 for (auto EHVal : EHArgs) {
5703 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5704 switch (EHVal[I]) {
5705 case 'a':
5706 EH.Asynch = maybeConsumeDash(EHVal, I);
5707 continue;
5708 case 'c':
5709 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5710 continue;
5711 case 's':
5712 EH.Synch = maybeConsumeDash(EHVal, I);
5713 continue;
5714 default:
5715 break;
5716 }
5717 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5718 break;
5719 }
5720 }
5721
5722 return EH;
5723 }
5724
AddClangCLArgs(const ArgList & Args,ArgStringList & CmdArgs,enum CodeGenOptions::DebugInfoKind * DebugInfoKind,bool * EmitCodeView) const5725 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
5726 enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
5727 bool *EmitCodeView) const {
5728 unsigned RTOptionID = options::OPT__SLASH_MT;
5729
5730 if (Args.hasArg(options::OPT__SLASH_LDd))
5731 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5732 // but defining _DEBUG is sticky.
5733 RTOptionID = options::OPT__SLASH_MTd;
5734
5735 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5736 RTOptionID = A->getOption().getID();
5737
5738 StringRef FlagForCRT;
5739 switch (RTOptionID) {
5740 case options::OPT__SLASH_MD:
5741 if (Args.hasArg(options::OPT__SLASH_LDd))
5742 CmdArgs.push_back("-D_DEBUG");
5743 CmdArgs.push_back("-D_MT");
5744 CmdArgs.push_back("-D_DLL");
5745 FlagForCRT = "--dependent-lib=msvcrt";
5746 break;
5747 case options::OPT__SLASH_MDd:
5748 CmdArgs.push_back("-D_DEBUG");
5749 CmdArgs.push_back("-D_MT");
5750 CmdArgs.push_back("-D_DLL");
5751 FlagForCRT = "--dependent-lib=msvcrtd";
5752 break;
5753 case options::OPT__SLASH_MT:
5754 if (Args.hasArg(options::OPT__SLASH_LDd))
5755 CmdArgs.push_back("-D_DEBUG");
5756 CmdArgs.push_back("-D_MT");
5757 FlagForCRT = "--dependent-lib=libcmt";
5758 break;
5759 case options::OPT__SLASH_MTd:
5760 CmdArgs.push_back("-D_DEBUG");
5761 CmdArgs.push_back("-D_MT");
5762 FlagForCRT = "--dependent-lib=libcmtd";
5763 break;
5764 default:
5765 llvm_unreachable("Unexpected option ID.");
5766 }
5767
5768 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5769 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5770 } else {
5771 CmdArgs.push_back(FlagForCRT.data());
5772
5773 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5774 // users want. The /Za flag to cl.exe turns this off, but it's not
5775 // implemented in clang.
5776 CmdArgs.push_back("--dependent-lib=oldnames");
5777 }
5778
5779 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5780 // would produce interleaved output, so ignore /showIncludes in such cases.
5781 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5782 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5783 A->render(Args, CmdArgs);
5784
5785 // This controls whether or not we emit RTTI data for polymorphic types.
5786 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5787 /*default=*/false))
5788 CmdArgs.push_back("-fno-rtti-data");
5789
5790 // Emit CodeView if -Z7 is present.
5791 *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
5792 bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
5793 // If we are emitting CV but not DWARF, don't build information that LLVM
5794 // can't yet process.
5795 if (*EmitCodeView && !EmitDwarf)
5796 *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
5797 if (*EmitCodeView)
5798 CmdArgs.push_back("-gcodeview");
5799
5800 const Driver &D = getToolChain().getDriver();
5801 EHFlags EH = parseClangCLEHFlags(D, Args);
5802 // FIXME: Do something with NoExceptC.
5803 if (EH.Synch || EH.Asynch) {
5804 CmdArgs.push_back("-fcxx-exceptions");
5805 CmdArgs.push_back("-fexceptions");
5806 }
5807
5808 // /EP should expand to -E -P.
5809 if (Args.hasArg(options::OPT__SLASH_EP)) {
5810 CmdArgs.push_back("-E");
5811 CmdArgs.push_back("-P");
5812 }
5813
5814 unsigned VolatileOptionID;
5815 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5816 getToolChain().getArch() == llvm::Triple::x86)
5817 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5818 else
5819 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5820
5821 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5822 VolatileOptionID = A->getOption().getID();
5823
5824 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5825 CmdArgs.push_back("-fms-volatile");
5826
5827 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5828 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5829 if (MostGeneralArg && BestCaseArg)
5830 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5831 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5832
5833 if (MostGeneralArg) {
5834 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5835 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5836 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5837
5838 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5839 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5840 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5841 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5842 << FirstConflict->getAsString(Args)
5843 << SecondConflict->getAsString(Args);
5844
5845 if (SingleArg)
5846 CmdArgs.push_back("-fms-memptr-rep=single");
5847 else if (MultipleArg)
5848 CmdArgs.push_back("-fms-memptr-rep=multiple");
5849 else
5850 CmdArgs.push_back("-fms-memptr-rep=virtual");
5851 }
5852
5853 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5854 A->render(Args, CmdArgs);
5855
5856 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5857 CmdArgs.push_back("-fdiagnostics-format");
5858 if (Args.hasArg(options::OPT__SLASH_fallback))
5859 CmdArgs.push_back("msvc-fallback");
5860 else
5861 CmdArgs.push_back("msvc");
5862 }
5863 }
5864
getCLFallback() const5865 visualstudio::Compiler *Clang::getCLFallback() const {
5866 if (!CLFallback)
5867 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5868 return CLFallback.get();
5869 }
5870
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const5871 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5872 ArgStringList &CmdArgs) const {
5873 StringRef CPUName;
5874 StringRef ABIName;
5875 const llvm::Triple &Triple = getToolChain().getTriple();
5876 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5877
5878 CmdArgs.push_back("-target-abi");
5879 CmdArgs.push_back(ABIName.data());
5880 }
5881
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const5882 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5883 const InputInfo &Output, const InputInfoList &Inputs,
5884 const ArgList &Args,
5885 const char *LinkingOutput) const {
5886 ArgStringList CmdArgs;
5887
5888 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5889 const InputInfo &Input = Inputs[0];
5890
5891 std::string TripleStr =
5892 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5893 const llvm::Triple Triple(TripleStr);
5894
5895 // Don't warn about "clang -w -c foo.s"
5896 Args.ClaimAllArgs(options::OPT_w);
5897 // and "clang -emit-llvm -c foo.s"
5898 Args.ClaimAllArgs(options::OPT_emit_llvm);
5899
5900 claimNoWarnArgs(Args);
5901
5902 // Invoke ourselves in -cc1as mode.
5903 //
5904 // FIXME: Implement custom jobs for internal actions.
5905 CmdArgs.push_back("-cc1as");
5906
5907 // Add the "effective" target triple.
5908 CmdArgs.push_back("-triple");
5909 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5910
5911 // Set the output mode, we currently only expect to be used as a real
5912 // assembler.
5913 CmdArgs.push_back("-filetype");
5914 CmdArgs.push_back("obj");
5915
5916 // Set the main file name, so that debug info works even with
5917 // -save-temps or preprocessed assembly.
5918 CmdArgs.push_back("-main-file-name");
5919 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5920
5921 // Add the target cpu
5922 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5923 if (!CPU.empty()) {
5924 CmdArgs.push_back("-target-cpu");
5925 CmdArgs.push_back(Args.MakeArgString(CPU));
5926 }
5927
5928 // Add the target features
5929 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5930
5931 // Ignore explicit -force_cpusubtype_ALL option.
5932 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5933
5934 // Pass along any -I options so we get proper .include search paths.
5935 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5936
5937 // Determine the original source input.
5938 const Action *SourceAction = &JA;
5939 while (SourceAction->getKind() != Action::InputClass) {
5940 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5941 SourceAction = SourceAction->getInputs()[0];
5942 }
5943
5944 // Forward -g and handle debug info related flags, assuming we are dealing
5945 // with an actual assembly file.
5946 if (SourceAction->getType() == types::TY_Asm ||
5947 SourceAction->getType() == types::TY_PP_Asm) {
5948 bool WantDebug = false;
5949 unsigned DwarfVersion = 0;
5950 Args.ClaimAllArgs(options::OPT_g_Group);
5951 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5952 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5953 !A->getOption().matches(options::OPT_ggdb0);
5954 if (WantDebug)
5955 DwarfVersion = DwarfVersionNum(A->getSpelling());
5956 }
5957 if (DwarfVersion == 0)
5958 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5959 RenderDebugEnablingArgs(Args, CmdArgs,
5960 (WantDebug ? CodeGenOptions::LimitedDebugInfo
5961 : CodeGenOptions::NoDebugInfo),
5962 DwarfVersion, llvm::DebuggerKind::Default);
5963
5964 // Add the -fdebug-compilation-dir flag if needed.
5965 addDebugCompDirArg(Args, CmdArgs);
5966
5967 // Set the AT_producer to the clang version when using the integrated
5968 // assembler on assembly source files.
5969 CmdArgs.push_back("-dwarf-debug-producer");
5970 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5971
5972 // And pass along -I options
5973 Args.AddAllArgs(CmdArgs, options::OPT_I);
5974 }
5975
5976 // Handle -fPIC et al -- the relocation-model affects the assembler
5977 // for some targets.
5978 llvm::Reloc::Model RelocationModel;
5979 unsigned PICLevel;
5980 bool IsPIE;
5981 std::tie(RelocationModel, PICLevel, IsPIE) =
5982 ParsePICArgs(getToolChain(), Triple, Args);
5983
5984 const char *RMName = RelocationModelName(RelocationModel);
5985 if (RMName) {
5986 CmdArgs.push_back("-mrelocation-model");
5987 CmdArgs.push_back(RMName);
5988 }
5989
5990 // Optionally embed the -cc1as level arguments into the debug info, for build
5991 // analysis.
5992 if (getToolChain().UseDwarfDebugFlags()) {
5993 ArgStringList OriginalArgs;
5994 for (const auto &Arg : Args)
5995 Arg->render(Args, OriginalArgs);
5996
5997 SmallString<256> Flags;
5998 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5999 Flags += Exec;
6000 for (const char *OriginalArg : OriginalArgs) {
6001 SmallString<128> EscapedArg;
6002 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6003 Flags += " ";
6004 Flags += EscapedArg;
6005 }
6006 CmdArgs.push_back("-dwarf-debug-flags");
6007 CmdArgs.push_back(Args.MakeArgString(Flags));
6008 }
6009
6010 // FIXME: Add -static support, once we have it.
6011
6012 // Add target specific flags.
6013 switch (getToolChain().getArch()) {
6014 default:
6015 break;
6016
6017 case llvm::Triple::mips:
6018 case llvm::Triple::mipsel:
6019 case llvm::Triple::mips64:
6020 case llvm::Triple::mips64el:
6021 AddMIPSTargetArgs(Args, CmdArgs);
6022 break;
6023 }
6024
6025 // Consume all the warning flags. Usually this would be handled more
6026 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6027 // doesn't handle that so rather than warning about unused flags that are
6028 // actually used, we'll lie by omission instead.
6029 // FIXME: Stop lying and consume only the appropriate driver flags
6030 for (const Arg *A : Args.filtered(options::OPT_W_Group))
6031 A->claim();
6032
6033 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6034 getToolChain().getDriver());
6035
6036 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6037
6038 assert(Output.isFilename() && "Unexpected lipo output.");
6039 CmdArgs.push_back("-o");
6040 CmdArgs.push_back(Output.getFilename());
6041
6042 assert(Input.isFilename() && "Invalid input.");
6043 CmdArgs.push_back(Input.getFilename());
6044
6045 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6046 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6047
6048 // Handle the debug info splitting at object creation time if we're
6049 // creating an object.
6050 // TODO: Currently only works on linux with newer objcopy.
6051 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6052 getToolChain().getTriple().isOSLinux())
6053 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6054 SplitDebugName(Args, Input));
6055 }
6056
anchor()6057 void GnuTool::anchor() {}
6058
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6059 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6060 const InputInfo &Output,
6061 const InputInfoList &Inputs, const ArgList &Args,
6062 const char *LinkingOutput) const {
6063 const Driver &D = getToolChain().getDriver();
6064 ArgStringList CmdArgs;
6065
6066 for (const auto &A : Args) {
6067 if (forwardToGCC(A->getOption())) {
6068 // Don't forward any -g arguments to assembly steps.
6069 if (isa<AssembleJobAction>(JA) &&
6070 A->getOption().matches(options::OPT_g_Group))
6071 continue;
6072
6073 // Don't forward any -W arguments to assembly and link steps.
6074 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6075 A->getOption().matches(options::OPT_W_Group))
6076 continue;
6077
6078 // It is unfortunate that we have to claim here, as this means
6079 // we will basically never report anything interesting for
6080 // platforms using a generic gcc, even if we are just using gcc
6081 // to get to the assembler.
6082 A->claim();
6083 A->render(Args, CmdArgs);
6084 }
6085 }
6086
6087 RenderExtraToolArgs(JA, CmdArgs);
6088
6089 // If using a driver driver, force the arch.
6090 if (getToolChain().getTriple().isOSDarwin()) {
6091 CmdArgs.push_back("-arch");
6092 CmdArgs.push_back(
6093 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6094 }
6095
6096 // Try to force gcc to match the tool chain we want, if we recognize
6097 // the arch.
6098 //
6099 // FIXME: The triple class should directly provide the information we want
6100 // here.
6101 switch (getToolChain().getArch()) {
6102 default:
6103 break;
6104 case llvm::Triple::x86:
6105 case llvm::Triple::ppc:
6106 CmdArgs.push_back("-m32");
6107 break;
6108 case llvm::Triple::x86_64:
6109 case llvm::Triple::ppc64:
6110 case llvm::Triple::ppc64le:
6111 CmdArgs.push_back("-m64");
6112 break;
6113 case llvm::Triple::sparcel:
6114 CmdArgs.push_back("-EL");
6115 break;
6116 }
6117
6118 if (Output.isFilename()) {
6119 CmdArgs.push_back("-o");
6120 CmdArgs.push_back(Output.getFilename());
6121 } else {
6122 assert(Output.isNothing() && "Unexpected output");
6123 CmdArgs.push_back("-fsyntax-only");
6124 }
6125
6126 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6127
6128 // Only pass -x if gcc will understand it; otherwise hope gcc
6129 // understands the suffix correctly. The main use case this would go
6130 // wrong in is for linker inputs if they happened to have an odd
6131 // suffix; really the only way to get this to happen is a command
6132 // like '-x foobar a.c' which will treat a.c like a linker input.
6133 //
6134 // FIXME: For the linker case specifically, can we safely convert
6135 // inputs into '-Wl,' options?
6136 for (const auto &II : Inputs) {
6137 // Don't try to pass LLVM or AST inputs to a generic gcc.
6138 if (types::isLLVMIR(II.getType()))
6139 D.Diag(diag::err_drv_no_linker_llvm_support)
6140 << getToolChain().getTripleString();
6141 else if (II.getType() == types::TY_AST)
6142 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6143 else if (II.getType() == types::TY_ModuleFile)
6144 D.Diag(diag::err_drv_no_module_support)
6145 << getToolChain().getTripleString();
6146
6147 if (types::canTypeBeUserSpecified(II.getType())) {
6148 CmdArgs.push_back("-x");
6149 CmdArgs.push_back(types::getTypeName(II.getType()));
6150 }
6151
6152 if (II.isFilename())
6153 CmdArgs.push_back(II.getFilename());
6154 else {
6155 const Arg &A = II.getInputArg();
6156
6157 // Reverse translate some rewritten options.
6158 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6159 CmdArgs.push_back("-lstdc++");
6160 continue;
6161 }
6162
6163 // Don't render as input, we need gcc to do the translations.
6164 A.render(Args, CmdArgs);
6165 }
6166 }
6167
6168 const std::string customGCCName = D.getCCCGenericGCCName();
6169 const char *GCCName;
6170 if (!customGCCName.empty())
6171 GCCName = customGCCName.c_str();
6172 else if (D.CCCIsCXX()) {
6173 GCCName = "g++";
6174 } else
6175 GCCName = "gcc";
6176
6177 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6178 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6179 }
6180
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6181 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6182 ArgStringList &CmdArgs) const {
6183 CmdArgs.push_back("-E");
6184 }
6185
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6186 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6187 ArgStringList &CmdArgs) const {
6188 const Driver &D = getToolChain().getDriver();
6189
6190 switch (JA.getType()) {
6191 // If -flto, etc. are present then make sure not to force assembly output.
6192 case types::TY_LLVM_IR:
6193 case types::TY_LTO_IR:
6194 case types::TY_LLVM_BC:
6195 case types::TY_LTO_BC:
6196 CmdArgs.push_back("-c");
6197 break;
6198 case types::TY_PP_Asm:
6199 CmdArgs.push_back("-S");
6200 break;
6201 case types::TY_Nothing:
6202 CmdArgs.push_back("-fsyntax-only");
6203 break;
6204 default:
6205 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6206 }
6207 }
6208
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6209 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6210 ArgStringList &CmdArgs) const {
6211 // The types are (hopefully) good enough.
6212 }
6213
6214 // Hexagon tools start.
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6215 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6216 ArgStringList &CmdArgs) const {
6217 }
6218
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6219 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6220 const InputInfo &Output,
6221 const InputInfoList &Inputs,
6222 const ArgList &Args,
6223 const char *LinkingOutput) const {
6224 claimNoWarnArgs(Args);
6225
6226 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6227 const Driver &D = HTC.getDriver();
6228 ArgStringList CmdArgs;
6229
6230 std::string MArchString = "-march=hexagon";
6231 CmdArgs.push_back(Args.MakeArgString(MArchString));
6232
6233 RenderExtraToolArgs(JA, CmdArgs);
6234
6235 std::string AsName = "hexagon-llvm-mc";
6236 std::string MCpuString = "-mcpu=hexagon" +
6237 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6238 CmdArgs.push_back("-filetype=obj");
6239 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6240
6241 if (Output.isFilename()) {
6242 CmdArgs.push_back("-o");
6243 CmdArgs.push_back(Output.getFilename());
6244 } else {
6245 assert(Output.isNothing() && "Unexpected output");
6246 CmdArgs.push_back("-fsyntax-only");
6247 }
6248
6249 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6250 std::string N = llvm::utostr(G.getValue());
6251 CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6252 }
6253
6254 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6255
6256 // Only pass -x if gcc will understand it; otherwise hope gcc
6257 // understands the suffix correctly. The main use case this would go
6258 // wrong in is for linker inputs if they happened to have an odd
6259 // suffix; really the only way to get this to happen is a command
6260 // like '-x foobar a.c' which will treat a.c like a linker input.
6261 //
6262 // FIXME: For the linker case specifically, can we safely convert
6263 // inputs into '-Wl,' options?
6264 for (const auto &II : Inputs) {
6265 // Don't try to pass LLVM or AST inputs to a generic gcc.
6266 if (types::isLLVMIR(II.getType()))
6267 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6268 << HTC.getTripleString();
6269 else if (II.getType() == types::TY_AST)
6270 D.Diag(clang::diag::err_drv_no_ast_support)
6271 << HTC.getTripleString();
6272 else if (II.getType() == types::TY_ModuleFile)
6273 D.Diag(diag::err_drv_no_module_support)
6274 << HTC.getTripleString();
6275
6276 if (II.isFilename())
6277 CmdArgs.push_back(II.getFilename());
6278 else
6279 // Don't render as input, we need gcc to do the translations.
6280 // FIXME: What is this?
6281 II.getInputArg().render(Args, CmdArgs);
6282 }
6283
6284 auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6285 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6286 }
6287
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6288 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6289 ArgStringList &CmdArgs) const {
6290 }
6291
6292 static void
constructHexagonLinkArgs(Compilation & C,const JobAction & JA,const toolchains::HexagonToolChain & HTC,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const char * LinkingOutput)6293 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6294 const toolchains::HexagonToolChain &HTC,
6295 const InputInfo &Output, const InputInfoList &Inputs,
6296 const ArgList &Args, ArgStringList &CmdArgs,
6297 const char *LinkingOutput) {
6298
6299 const Driver &D = HTC.getDriver();
6300
6301 //----------------------------------------------------------------------------
6302 //
6303 //----------------------------------------------------------------------------
6304 bool IsStatic = Args.hasArg(options::OPT_static);
6305 bool IsShared = Args.hasArg(options::OPT_shared);
6306 bool IsPIE = Args.hasArg(options::OPT_pie);
6307 bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6308 bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6309 bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6310 bool UseG0 = false;
6311 bool UseShared = IsShared && !IsStatic;
6312
6313 //----------------------------------------------------------------------------
6314 // Silence warnings for various options
6315 //----------------------------------------------------------------------------
6316 Args.ClaimAllArgs(options::OPT_g_Group);
6317 Args.ClaimAllArgs(options::OPT_emit_llvm);
6318 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6319 // handled somewhere else.
6320 Args.ClaimAllArgs(options::OPT_static_libgcc);
6321
6322 //----------------------------------------------------------------------------
6323 //
6324 //----------------------------------------------------------------------------
6325 if (Args.hasArg(options::OPT_s))
6326 CmdArgs.push_back("-s");
6327
6328 if (Args.hasArg(options::OPT_r))
6329 CmdArgs.push_back("-r");
6330
6331 for (const auto &Opt : HTC.ExtraOpts)
6332 CmdArgs.push_back(Opt.c_str());
6333
6334 CmdArgs.push_back("-march=hexagon");
6335 std::string CpuVer =
6336 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6337 std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6338 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6339
6340 if (IsShared) {
6341 CmdArgs.push_back("-shared");
6342 // The following should be the default, but doing as hexagon-gcc does.
6343 CmdArgs.push_back("-call_shared");
6344 }
6345
6346 if (IsStatic)
6347 CmdArgs.push_back("-static");
6348
6349 if (IsPIE && !IsShared)
6350 CmdArgs.push_back("-pie");
6351
6352 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6353 std::string N = llvm::utostr(G.getValue());
6354 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6355 UseG0 = G.getValue() == 0;
6356 }
6357
6358 //----------------------------------------------------------------------------
6359 //
6360 //----------------------------------------------------------------------------
6361 CmdArgs.push_back("-o");
6362 CmdArgs.push_back(Output.getFilename());
6363
6364 //----------------------------------------------------------------------------
6365 // moslib
6366 //----------------------------------------------------------------------------
6367 std::vector<std::string> OsLibs;
6368 bool HasStandalone = false;
6369
6370 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6371 A->claim();
6372 OsLibs.emplace_back(A->getValue());
6373 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6374 }
6375 if (OsLibs.empty()) {
6376 OsLibs.push_back("standalone");
6377 HasStandalone = true;
6378 }
6379
6380 //----------------------------------------------------------------------------
6381 // Start Files
6382 //----------------------------------------------------------------------------
6383 const std::string MCpuSuffix = "/" + CpuVer;
6384 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6385 const std::string RootDir =
6386 HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6387 const std::string StartSubDir =
6388 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6389
6390 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6391 const char *Name) -> std::string {
6392 std::string RelName = SubDir + Name;
6393 std::string P = HTC.GetFilePath(RelName.c_str());
6394 if (llvm::sys::fs::exists(P))
6395 return P;
6396 return RootDir + RelName;
6397 };
6398
6399 if (IncStdLib && IncStartFiles) {
6400 if (!IsShared) {
6401 if (HasStandalone) {
6402 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6403 CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6404 }
6405 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6406 CmdArgs.push_back(Args.MakeArgString(Crt0));
6407 }
6408 std::string Init = UseShared
6409 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6410 : Find(RootDir, StartSubDir, "/init.o");
6411 CmdArgs.push_back(Args.MakeArgString(Init));
6412 }
6413
6414 //----------------------------------------------------------------------------
6415 // Library Search Paths
6416 //----------------------------------------------------------------------------
6417 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6418 for (const auto &LibPath : LibPaths)
6419 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6420
6421 //----------------------------------------------------------------------------
6422 //
6423 //----------------------------------------------------------------------------
6424 Args.AddAllArgs(CmdArgs,
6425 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6426 options::OPT_t, options::OPT_u_Group});
6427
6428 AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6429
6430 //----------------------------------------------------------------------------
6431 // Libraries
6432 //----------------------------------------------------------------------------
6433 if (IncStdLib && IncDefLibs) {
6434 if (D.CCCIsCXX()) {
6435 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6436 CmdArgs.push_back("-lm");
6437 }
6438
6439 CmdArgs.push_back("--start-group");
6440
6441 if (!IsShared) {
6442 for (const std::string &Lib : OsLibs)
6443 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6444 CmdArgs.push_back("-lc");
6445 }
6446 CmdArgs.push_back("-lgcc");
6447
6448 CmdArgs.push_back("--end-group");
6449 }
6450
6451 //----------------------------------------------------------------------------
6452 // End files
6453 //----------------------------------------------------------------------------
6454 if (IncStdLib && IncStartFiles) {
6455 std::string Fini = UseShared
6456 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
6457 : Find(RootDir, StartSubDir, "/fini.o");
6458 CmdArgs.push_back(Args.MakeArgString(Fini));
6459 }
6460 }
6461
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6462 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6463 const InputInfo &Output,
6464 const InputInfoList &Inputs,
6465 const ArgList &Args,
6466 const char *LinkingOutput) const {
6467 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6468
6469 ArgStringList CmdArgs;
6470 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
6471 LinkingOutput);
6472
6473 std::string Linker = HTC.GetProgramPath("hexagon-link");
6474 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6475 CmdArgs, Inputs));
6476 }
6477 // Hexagon tools end.
6478
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6479 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6480 const InputInfo &Output,
6481 const InputInfoList &Inputs,
6482 const ArgList &Args,
6483 const char *LinkingOutput) const {
6484
6485 std::string Linker = getToolChain().GetProgramPath(getShortName());
6486 ArgStringList CmdArgs;
6487 CmdArgs.push_back("-flavor");
6488 CmdArgs.push_back("old-gnu");
6489 CmdArgs.push_back("-target");
6490 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
6491 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6492 CmdArgs.push_back("-o");
6493 CmdArgs.push_back(Output.getFilename());
6494 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6495 CmdArgs, Inputs));
6496 }
6497 // AMDGPU tools end.
6498
Linker(const ToolChain & TC)6499 wasm::Linker::Linker(const ToolChain &TC)
6500 : GnuTool("wasm::Linker", "lld", TC) {}
6501
isLinkJob() const6502 bool wasm::Linker::isLinkJob() const {
6503 return true;
6504 }
6505
hasIntegratedCPP() const6506 bool wasm::Linker::hasIntegratedCPP() const {
6507 return false;
6508 }
6509
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6510 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6511 const InputInfo &Output,
6512 const InputInfoList &Inputs,
6513 const ArgList &Args,
6514 const char *LinkingOutput) const {
6515 const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
6516 ArgStringList CmdArgs;
6517 CmdArgs.push_back("-flavor");
6518 CmdArgs.push_back("ld");
6519 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6520 CmdArgs.push_back("-o");
6521 CmdArgs.push_back(Output.getFilename());
6522 C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
6523 }
6524
getARMArch(StringRef Arch,const llvm::Triple & Triple)6525 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
6526 std::string MArch;
6527 if (!Arch.empty())
6528 MArch = Arch;
6529 else
6530 MArch = Triple.getArchName();
6531 MArch = StringRef(MArch).split("+").first.lower();
6532
6533 // Handle -march=native.
6534 if (MArch == "native") {
6535 std::string CPU = llvm::sys::getHostCPUName();
6536 if (CPU != "generic") {
6537 // Translate the native cpu into the architecture suffix for that CPU.
6538 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
6539 // If there is no valid architecture suffix for this CPU we don't know how
6540 // to handle it, so return no architecture.
6541 if (Suffix.empty())
6542 MArch = "";
6543 else
6544 MArch = std::string("arm") + Suffix.str();
6545 }
6546 }
6547
6548 return MArch;
6549 }
6550
6551 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
getARMCPUForMArch(StringRef Arch,const llvm::Triple & Triple)6552 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
6553 std::string MArch = getARMArch(Arch, Triple);
6554 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
6555 // here means an -march=native that we can't handle, so instead return no CPU.
6556 if (MArch.empty())
6557 return StringRef();
6558
6559 // We need to return an empty string here on invalid MArch values as the
6560 // various places that call this function can't cope with a null result.
6561 return Triple.getARMCPUForArch(MArch);
6562 }
6563
6564 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
getARMTargetCPU(StringRef CPU,StringRef Arch,const llvm::Triple & Triple)6565 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
6566 const llvm::Triple &Triple) {
6567 // FIXME: Warn on inconsistent use of -mcpu and -march.
6568 // If we have -mcpu=, use that.
6569 if (!CPU.empty()) {
6570 std::string MCPU = StringRef(CPU).split("+").first.lower();
6571 // Handle -mcpu=native.
6572 if (MCPU == "native")
6573 return llvm::sys::getHostCPUName();
6574 else
6575 return MCPU;
6576 }
6577
6578 return getARMCPUForMArch(Arch, Triple);
6579 }
6580
6581 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
6582 /// CPU (or Arch, if CPU is generic).
6583 // FIXME: This is redundant with -mcpu, why does LLVM use this.
getLLVMArchSuffixForARM(StringRef CPU,StringRef Arch,const llvm::Triple & Triple)6584 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
6585 const llvm::Triple &Triple) {
6586 unsigned ArchKind;
6587 if (CPU == "generic") {
6588 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
6589 ArchKind = llvm::ARM::parseArch(ARMArch);
6590 if (ArchKind == llvm::ARM::AK_INVALID)
6591 // In case of generic Arch, i.e. "arm",
6592 // extract arch from default cpu of the Triple
6593 ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
6594 } else {
6595 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
6596 // armv7k triple if it's actually been specified via "-arch armv7k".
6597 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
6598 ? (unsigned)llvm::ARM::AK_ARMV7K
6599 : llvm::ARM::parseCPUArch(CPU);
6600 }
6601 if (ArchKind == llvm::ARM::AK_INVALID)
6602 return "";
6603 return llvm::ARM::getSubArch(ArchKind);
6604 }
6605
appendEBLinkFlags(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple)6606 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
6607 const llvm::Triple &Triple) {
6608 if (Args.hasArg(options::OPT_r))
6609 return;
6610
6611 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
6612 // to generate BE-8 executables.
6613 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
6614 CmdArgs.push_back("--be8");
6615 }
6616
getSupportedNanEncoding(StringRef & CPU)6617 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
6618 // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
6619 // was first introduced in Release 3. However, other compilers have
6620 // traditionally allowed it for Release 2 so we should do the same.
6621 return (NanEncoding)llvm::StringSwitch<int>(CPU)
6622 .Case("mips1", NanLegacy)
6623 .Case("mips2", NanLegacy)
6624 .Case("mips3", NanLegacy)
6625 .Case("mips4", NanLegacy)
6626 .Case("mips5", NanLegacy)
6627 .Case("mips32", NanLegacy)
6628 .Case("mips32r2", NanLegacy | Nan2008)
6629 .Case("mips32r3", NanLegacy | Nan2008)
6630 .Case("mips32r5", NanLegacy | Nan2008)
6631 .Case("mips32r6", Nan2008)
6632 .Case("mips64", NanLegacy)
6633 .Case("mips64r2", NanLegacy | Nan2008)
6634 .Case("mips64r3", NanLegacy | Nan2008)
6635 .Case("mips64r5", NanLegacy | Nan2008)
6636 .Case("mips64r6", Nan2008)
6637 .Default(NanLegacy);
6638 }
6639
hasMipsAbiArg(const ArgList & Args,const char * Value)6640 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6641 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6642 return A && (A->getValue() == StringRef(Value));
6643 }
6644
isUCLibc(const ArgList & Args)6645 bool mips::isUCLibc(const ArgList &Args) {
6646 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6647 return A && A->getOption().matches(options::OPT_muclibc);
6648 }
6649
isNaN2008(const ArgList & Args,const llvm::Triple & Triple)6650 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6651 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6652 return llvm::StringSwitch<bool>(NaNArg->getValue())
6653 .Case("2008", true)
6654 .Case("legacy", false)
6655 .Default(false);
6656
6657 // NaN2008 is the default for MIPS32r6/MIPS64r6.
6658 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6659 .Cases("mips32r6", "mips64r6", true)
6660 .Default(false);
6661
6662 return false;
6663 }
6664
isFPXXDefault(const llvm::Triple & Triple,StringRef CPUName,StringRef ABIName,mips::FloatABI FloatABI)6665 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6666 StringRef ABIName, mips::FloatABI FloatABI) {
6667 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6668 Triple.getVendor() != llvm::Triple::MipsTechnologies)
6669 return false;
6670
6671 if (ABIName != "32")
6672 return false;
6673
6674 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6675 // present.
6676 if (FloatABI == mips::FloatABI::Soft)
6677 return false;
6678
6679 return llvm::StringSwitch<bool>(CPUName)
6680 .Cases("mips2", "mips3", "mips4", "mips5", true)
6681 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6682 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6683 .Default(false);
6684 }
6685
shouldUseFPXX(const ArgList & Args,const llvm::Triple & Triple,StringRef CPUName,StringRef ABIName,mips::FloatABI FloatABI)6686 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6687 StringRef CPUName, StringRef ABIName,
6688 mips::FloatABI FloatABI) {
6689 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6690
6691 // FPXX shouldn't be used if -msingle-float is present.
6692 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6693 options::OPT_mdouble_float))
6694 if (A->getOption().matches(options::OPT_msingle_float))
6695 UseFPXX = false;
6696
6697 return UseFPXX;
6698 }
6699
getArchTypeForMachOArchName(StringRef Str)6700 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6701 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6702 // archs which Darwin doesn't use.
6703
6704 // The matching this routine does is fairly pointless, since it is neither the
6705 // complete architecture list, nor a reasonable subset. The problem is that
6706 // historically the driver driver accepts this and also ties its -march=
6707 // handling to the architecture name, so we need to be careful before removing
6708 // support for it.
6709
6710 // This code must be kept in sync with Clang's Darwin specific argument
6711 // translation.
6712
6713 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6714 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6715 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6716 .Case("ppc64", llvm::Triple::ppc64)
6717 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6718 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6719 llvm::Triple::x86)
6720 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6721 // This is derived from the driver driver.
6722 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6723 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6724 .Cases("armv7s", "xscale", llvm::Triple::arm)
6725 .Case("arm64", llvm::Triple::aarch64)
6726 .Case("r600", llvm::Triple::r600)
6727 .Case("amdgcn", llvm::Triple::amdgcn)
6728 .Case("nvptx", llvm::Triple::nvptx)
6729 .Case("nvptx64", llvm::Triple::nvptx64)
6730 .Case("amdil", llvm::Triple::amdil)
6731 .Case("spir", llvm::Triple::spir)
6732 .Default(llvm::Triple::UnknownArch);
6733 }
6734
setTripleTypeForMachOArchName(llvm::Triple & T,StringRef Str)6735 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6736 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6737 T.setArch(Arch);
6738
6739 if (Str == "x86_64h")
6740 T.setArchName(Str);
6741 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6742 T.setOS(llvm::Triple::UnknownOS);
6743 T.setObjectFormat(llvm::Triple::MachO);
6744 }
6745 }
6746
getBaseInputName(const ArgList & Args,const InputInfo & Input)6747 const char *Clang::getBaseInputName(const ArgList &Args,
6748 const InputInfo &Input) {
6749 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6750 }
6751
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)6752 const char *Clang::getBaseInputStem(const ArgList &Args,
6753 const InputInfoList &Inputs) {
6754 const char *Str = getBaseInputName(Args, Inputs[0]);
6755
6756 if (const char *End = strrchr(Str, '.'))
6757 return Args.MakeArgString(std::string(Str, End));
6758
6759 return Str;
6760 }
6761
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)6762 const char *Clang::getDependencyFileName(const ArgList &Args,
6763 const InputInfoList &Inputs) {
6764 // FIXME: Think about this more.
6765 std::string Res;
6766
6767 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6768 std::string Str(OutputOpt->getValue());
6769 Res = Str.substr(0, Str.rfind('.'));
6770 } else {
6771 Res = getBaseInputStem(Args, Inputs);
6772 }
6773 return Args.MakeArgString(Res + ".d");
6774 }
6775
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6776 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6777 const InputInfo &Output,
6778 const InputInfoList &Inputs,
6779 const ArgList &Args,
6780 const char *LinkingOutput) const {
6781 const ToolChain &ToolChain = getToolChain();
6782 const Driver &D = ToolChain.getDriver();
6783 ArgStringList CmdArgs;
6784
6785 // Silence warning for "clang -g foo.o -o foo"
6786 Args.ClaimAllArgs(options::OPT_g_Group);
6787 // and "clang -emit-llvm foo.o -o foo"
6788 Args.ClaimAllArgs(options::OPT_emit_llvm);
6789 // and for "clang -w foo.o -o foo". Other warning options are already
6790 // handled somewhere else.
6791 Args.ClaimAllArgs(options::OPT_w);
6792
6793 if (!D.SysRoot.empty())
6794 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6795
6796 // CloudABI only supports static linkage.
6797 CmdArgs.push_back("-Bstatic");
6798 CmdArgs.push_back("--eh-frame-hdr");
6799 CmdArgs.push_back("--gc-sections");
6800
6801 if (Output.isFilename()) {
6802 CmdArgs.push_back("-o");
6803 CmdArgs.push_back(Output.getFilename());
6804 } else {
6805 assert(Output.isNothing() && "Invalid output.");
6806 }
6807
6808 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
6809 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6810 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6811 }
6812
6813 Args.AddAllArgs(CmdArgs, options::OPT_L);
6814 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
6815 Args.AddAllArgs(CmdArgs,
6816 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6817 options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
6818
6819 if (D.isUsingLTO())
6820 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
6821
6822 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6823
6824 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6825 if (D.CCCIsCXX())
6826 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6827 CmdArgs.push_back("-lc");
6828 CmdArgs.push_back("-lcompiler_rt");
6829 }
6830
6831 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
6832 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6833
6834 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6835 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6836 }
6837
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6838 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6839 const InputInfo &Output,
6840 const InputInfoList &Inputs,
6841 const ArgList &Args,
6842 const char *LinkingOutput) const {
6843 ArgStringList CmdArgs;
6844
6845 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6846 const InputInfo &Input = Inputs[0];
6847
6848 // Determine the original source input.
6849 const Action *SourceAction = &JA;
6850 while (SourceAction->getKind() != Action::InputClass) {
6851 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6852 SourceAction = SourceAction->getInputs()[0];
6853 }
6854
6855 // If -fno-integrated-as is used add -Q to the darwin assember driver to make
6856 // sure it runs its system assembler not clang's integrated assembler.
6857 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6858 // FIXME: at run-time detect assembler capabilities or rely on version
6859 // information forwarded by -target-assembler-version.
6860 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6861 const llvm::Triple &T(getToolChain().getTriple());
6862 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6863 CmdArgs.push_back("-Q");
6864 }
6865
6866 // Forward -g, assuming we are dealing with an actual assembly file.
6867 if (SourceAction->getType() == types::TY_Asm ||
6868 SourceAction->getType() == types::TY_PP_Asm) {
6869 if (Args.hasArg(options::OPT_gstabs))
6870 CmdArgs.push_back("--gstabs");
6871 else if (Args.hasArg(options::OPT_g_Group))
6872 CmdArgs.push_back("-g");
6873 }
6874
6875 // Derived from asm spec.
6876 AddMachOArch(Args, CmdArgs);
6877
6878 // Use -force_cpusubtype_ALL on x86 by default.
6879 if (getToolChain().getArch() == llvm::Triple::x86 ||
6880 getToolChain().getArch() == llvm::Triple::x86_64 ||
6881 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6882 CmdArgs.push_back("-force_cpusubtype_ALL");
6883
6884 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6885 (((Args.hasArg(options::OPT_mkernel) ||
6886 Args.hasArg(options::OPT_fapple_kext)) &&
6887 getMachOToolChain().isKernelStatic()) ||
6888 Args.hasArg(options::OPT_static)))
6889 CmdArgs.push_back("-static");
6890
6891 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6892
6893 assert(Output.isFilename() && "Unexpected lipo output.");
6894 CmdArgs.push_back("-o");
6895 CmdArgs.push_back(Output.getFilename());
6896
6897 assert(Input.isFilename() && "Invalid input.");
6898 CmdArgs.push_back(Input.getFilename());
6899
6900 // asm_final spec is empty.
6901
6902 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6903 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6904 }
6905
anchor()6906 void darwin::MachOTool::anchor() {}
6907
AddMachOArch(const ArgList & Args,ArgStringList & CmdArgs) const6908 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6909 ArgStringList &CmdArgs) const {
6910 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6911
6912 // Derived from darwin_arch spec.
6913 CmdArgs.push_back("-arch");
6914 CmdArgs.push_back(Args.MakeArgString(ArchName));
6915
6916 // FIXME: Is this needed anymore?
6917 if (ArchName == "arm")
6918 CmdArgs.push_back("-force_cpusubtype_ALL");
6919 }
6920
NeedsTempPath(const InputInfoList & Inputs) const6921 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6922 // We only need to generate a temp path for LTO if we aren't compiling object
6923 // files. When compiling source files, we run 'dsymutil' after linking. We
6924 // don't run 'dsymutil' when compiling object files.
6925 for (const auto &Input : Inputs)
6926 if (Input.getType() != types::TY_Object)
6927 return true;
6928
6929 return false;
6930 }
6931
AddLinkArgs(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const InputInfoList & Inputs) const6932 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6933 ArgStringList &CmdArgs,
6934 const InputInfoList &Inputs) const {
6935 const Driver &D = getToolChain().getDriver();
6936 const toolchains::MachO &MachOTC = getMachOToolChain();
6937
6938 unsigned Version[3] = {0, 0, 0};
6939 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6940 bool HadExtra;
6941 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6942 Version[2], HadExtra) ||
6943 HadExtra)
6944 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6945 }
6946
6947 // Newer linkers support -demangle. Pass it if supported and not disabled by
6948 // the user.
6949 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6950 CmdArgs.push_back("-demangle");
6951
6952 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6953 CmdArgs.push_back("-export_dynamic");
6954
6955 // If we are using App Extension restrictions, pass a flag to the linker
6956 // telling it that the compiled code has been audited.
6957 if (Args.hasFlag(options::OPT_fapplication_extension,
6958 options::OPT_fno_application_extension, false))
6959 CmdArgs.push_back("-application_extension");
6960
6961 if (D.isUsingLTO()) {
6962 // If we are using LTO, then automatically create a temporary file path for
6963 // the linker to use, so that it's lifetime will extend past a possible
6964 // dsymutil step.
6965 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
6966 const char *TmpPath = C.getArgs().MakeArgString(
6967 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6968 C.addTempFile(TmpPath);
6969 CmdArgs.push_back("-object_path_lto");
6970 CmdArgs.push_back(TmpPath);
6971 }
6972
6973 // Use -lto_library option to specify the libLTO.dylib path. Try to find
6974 // it in clang installed libraries. If not found, the option is not used
6975 // and 'ld' will use its default mechanism to search for libLTO.dylib.
6976 if (Version[0] >= 133) {
6977 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
6978 StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
6979 SmallString<128> LibLTOPath(P);
6980 llvm::sys::path::append(LibLTOPath, "lib");
6981 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
6982 if (llvm::sys::fs::exists(LibLTOPath)) {
6983 CmdArgs.push_back("-lto_library");
6984 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
6985 } else {
6986 D.Diag(diag::warn_drv_lto_libpath);
6987 }
6988 }
6989 }
6990
6991 // Derived from the "link" spec.
6992 Args.AddAllArgs(CmdArgs, options::OPT_static);
6993 if (!Args.hasArg(options::OPT_static))
6994 CmdArgs.push_back("-dynamic");
6995 if (Args.hasArg(options::OPT_fgnu_runtime)) {
6996 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6997 // here. How do we wish to handle such things?
6998 }
6999
7000 if (!Args.hasArg(options::OPT_dynamiclib)) {
7001 AddMachOArch(Args, CmdArgs);
7002 // FIXME: Why do this only on this path?
7003 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7004
7005 Args.AddLastArg(CmdArgs, options::OPT_bundle);
7006 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7007 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7008
7009 Arg *A;
7010 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7011 (A = Args.getLastArg(options::OPT_current__version)) ||
7012 (A = Args.getLastArg(options::OPT_install__name)))
7013 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7014 << "-dynamiclib";
7015
7016 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7017 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7018 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7019 } else {
7020 CmdArgs.push_back("-dylib");
7021
7022 Arg *A;
7023 if ((A = Args.getLastArg(options::OPT_bundle)) ||
7024 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7025 (A = Args.getLastArg(options::OPT_client__name)) ||
7026 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7027 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7028 (A = Args.getLastArg(options::OPT_private__bundle)))
7029 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7030 << "-dynamiclib";
7031
7032 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7033 "-dylib_compatibility_version");
7034 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7035 "-dylib_current_version");
7036
7037 AddMachOArch(Args, CmdArgs);
7038
7039 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7040 "-dylib_install_name");
7041 }
7042
7043 Args.AddLastArg(CmdArgs, options::OPT_all__load);
7044 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7045 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7046 if (MachOTC.isTargetIOSBased())
7047 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7048 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7049 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7050 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7051 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7052 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7053 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7054 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7055 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7056 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7057 Args.AddAllArgs(CmdArgs, options::OPT_init);
7058
7059 // Add the deployment target.
7060 MachOTC.addMinVersionArgs(Args, CmdArgs);
7061
7062 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7063 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7064 Args.AddLastArg(CmdArgs, options::OPT_single__module);
7065 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7066 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7067
7068 if (const Arg *A =
7069 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7070 options::OPT_fno_pie, options::OPT_fno_PIE)) {
7071 if (A->getOption().matches(options::OPT_fpie) ||
7072 A->getOption().matches(options::OPT_fPIE))
7073 CmdArgs.push_back("-pie");
7074 else
7075 CmdArgs.push_back("-no_pie");
7076 }
7077
7078 Args.AddLastArg(CmdArgs, options::OPT_prebind);
7079 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7080 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7081 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7082 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7083 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7084 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7085 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7086 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7087 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7088 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7089 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7090 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7091 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7092 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7093 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7094
7095 // Give --sysroot= preference, over the Apple specific behavior to also use
7096 // --isysroot as the syslibroot.
7097 StringRef sysroot = C.getSysRoot();
7098 if (sysroot != "") {
7099 CmdArgs.push_back("-syslibroot");
7100 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7101 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7102 CmdArgs.push_back("-syslibroot");
7103 CmdArgs.push_back(A->getValue());
7104 }
7105
7106 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7107 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7108 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7109 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7110 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7111 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7112 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7113 Args.AddAllArgs(CmdArgs, options::OPT_y);
7114 Args.AddLastArg(CmdArgs, options::OPT_w);
7115 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7116 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7117 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7118 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7119 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7120 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7121 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7122 Args.AddLastArg(CmdArgs, options::OPT_whyload);
7123 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7124 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7125 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7126 Args.AddLastArg(CmdArgs, options::OPT_Mach);
7127 }
7128
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7129 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7130 const InputInfo &Output,
7131 const InputInfoList &Inputs,
7132 const ArgList &Args,
7133 const char *LinkingOutput) const {
7134 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7135
7136 // If the number of arguments surpasses the system limits, we will encode the
7137 // input files in a separate file, shortening the command line. To this end,
7138 // build a list of input file names that can be passed via a file with the
7139 // -filelist linker option.
7140 llvm::opt::ArgStringList InputFileList;
7141
7142 // The logic here is derived from gcc's behavior; most of which
7143 // comes from specs (starting with link_command). Consult gcc for
7144 // more information.
7145 ArgStringList CmdArgs;
7146
7147 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7148 if (Args.hasArg(options::OPT_ccc_arcmt_check,
7149 options::OPT_ccc_arcmt_migrate)) {
7150 for (const auto &Arg : Args)
7151 Arg->claim();
7152 const char *Exec =
7153 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7154 CmdArgs.push_back(Output.getFilename());
7155 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7156 return;
7157 }
7158
7159 // I'm not sure why this particular decomposition exists in gcc, but
7160 // we follow suite for ease of comparison.
7161 AddLinkArgs(C, Args, CmdArgs, Inputs);
7162
7163 // It seems that the 'e' option is completely ignored for dynamic executables
7164 // (the default), and with static executables, the last one wins, as expected.
7165 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7166 options::OPT_Z_Flag, options::OPT_u_Group,
7167 options::OPT_e, options::OPT_r});
7168
7169 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7170 // members of static archive libraries which implement Objective-C classes or
7171 // categories.
7172 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7173 CmdArgs.push_back("-ObjC");
7174
7175 CmdArgs.push_back("-o");
7176 CmdArgs.push_back(Output.getFilename());
7177
7178 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7179 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7180
7181 // SafeStack requires its own runtime libraries
7182 // These libraries should be linked first, to make sure the
7183 // __safestack_init constructor executes before everything else
7184 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7185 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7186 "libclang_rt.safestack_osx.a",
7187 /*AlwaysLink=*/true);
7188 }
7189
7190 Args.AddAllArgs(CmdArgs, options::OPT_L);
7191
7192 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7193 // Build the input file for -filelist (list of linker input files) in case we
7194 // need it later
7195 for (const auto &II : Inputs) {
7196 if (!II.isFilename()) {
7197 // This is a linker input argument.
7198 // We cannot mix input arguments and file names in a -filelist input, thus
7199 // we prematurely stop our list (remaining files shall be passed as
7200 // arguments).
7201 if (InputFileList.size() > 0)
7202 break;
7203
7204 continue;
7205 }
7206
7207 InputFileList.push_back(II.getFilename());
7208 }
7209
7210 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7211 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7212
7213 if (isObjCRuntimeLinked(Args) &&
7214 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7215 // We use arclite library for both ARC and subscripting support.
7216 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7217
7218 CmdArgs.push_back("-framework");
7219 CmdArgs.push_back("Foundation");
7220 // Link libobj.
7221 CmdArgs.push_back("-lobjc");
7222 }
7223
7224 if (LinkingOutput) {
7225 CmdArgs.push_back("-arch_multiple");
7226 CmdArgs.push_back("-final_output");
7227 CmdArgs.push_back(LinkingOutput);
7228 }
7229
7230 if (Args.hasArg(options::OPT_fnested_functions))
7231 CmdArgs.push_back("-allow_stack_execute");
7232
7233 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7234
7235 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7236 if (getToolChain().getDriver().CCCIsCXX())
7237 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7238
7239 // link_ssp spec is empty.
7240
7241 // Let the tool chain choose which runtime library to link.
7242 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7243 }
7244
7245 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7246 // endfile_spec is empty.
7247 }
7248
7249 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7250 Args.AddAllArgs(CmdArgs, options::OPT_F);
7251
7252 // -iframework should be forwarded as -F.
7253 for (const Arg *A : Args.filtered(options::OPT_iframework))
7254 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7255
7256 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7257 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7258 if (A->getValue() == StringRef("Accelerate")) {
7259 CmdArgs.push_back("-framework");
7260 CmdArgs.push_back("Accelerate");
7261 }
7262 }
7263 }
7264
7265 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7266 std::unique_ptr<Command> Cmd =
7267 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7268 Cmd->setInputFileList(std::move(InputFileList));
7269 C.addCommand(std::move(Cmd));
7270 }
7271
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7272 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7273 const InputInfo &Output,
7274 const InputInfoList &Inputs,
7275 const ArgList &Args,
7276 const char *LinkingOutput) const {
7277 ArgStringList CmdArgs;
7278
7279 CmdArgs.push_back("-create");
7280 assert(Output.isFilename() && "Unexpected lipo output.");
7281
7282 CmdArgs.push_back("-output");
7283 CmdArgs.push_back(Output.getFilename());
7284
7285 for (const auto &II : Inputs) {
7286 assert(II.isFilename() && "Unexpected lipo input.");
7287 CmdArgs.push_back(II.getFilename());
7288 }
7289
7290 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7291 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7292 }
7293
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7294 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7295 const InputInfo &Output,
7296 const InputInfoList &Inputs,
7297 const ArgList &Args,
7298 const char *LinkingOutput) const {
7299 ArgStringList CmdArgs;
7300
7301 CmdArgs.push_back("-o");
7302 CmdArgs.push_back(Output.getFilename());
7303
7304 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7305 const InputInfo &Input = Inputs[0];
7306 assert(Input.isFilename() && "Unexpected dsymutil input.");
7307 CmdArgs.push_back(Input.getFilename());
7308
7309 const char *Exec =
7310 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7311 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7312 }
7313
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7314 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7315 const InputInfo &Output,
7316 const InputInfoList &Inputs,
7317 const ArgList &Args,
7318 const char *LinkingOutput) const {
7319 ArgStringList CmdArgs;
7320 CmdArgs.push_back("--verify");
7321 CmdArgs.push_back("--debug-info");
7322 CmdArgs.push_back("--eh-frame");
7323 CmdArgs.push_back("--quiet");
7324
7325 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7326 const InputInfo &Input = Inputs[0];
7327 assert(Input.isFilename() && "Unexpected verify input");
7328
7329 // Grabbing the output of the earlier dsymutil run.
7330 CmdArgs.push_back(Input.getFilename());
7331
7332 const char *Exec =
7333 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7334 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7335 }
7336
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7337 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7338 const InputInfo &Output,
7339 const InputInfoList &Inputs,
7340 const ArgList &Args,
7341 const char *LinkingOutput) const {
7342 claimNoWarnArgs(Args);
7343 ArgStringList CmdArgs;
7344
7345 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7346
7347 CmdArgs.push_back("-o");
7348 CmdArgs.push_back(Output.getFilename());
7349
7350 for (const auto &II : Inputs)
7351 CmdArgs.push_back(II.getFilename());
7352
7353 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7354 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7355 }
7356
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7357 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7358 const InputInfo &Output,
7359 const InputInfoList &Inputs,
7360 const ArgList &Args,
7361 const char *LinkingOutput) const {
7362 ArgStringList CmdArgs;
7363
7364 // Demangle C++ names in errors
7365 CmdArgs.push_back("-C");
7366
7367 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7368 CmdArgs.push_back("-e");
7369 CmdArgs.push_back("_start");
7370 }
7371
7372 if (Args.hasArg(options::OPT_static)) {
7373 CmdArgs.push_back("-Bstatic");
7374 CmdArgs.push_back("-dn");
7375 } else {
7376 CmdArgs.push_back("-Bdynamic");
7377 if (Args.hasArg(options::OPT_shared)) {
7378 CmdArgs.push_back("-shared");
7379 } else {
7380 CmdArgs.push_back("--dynamic-linker");
7381 CmdArgs.push_back(
7382 Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
7383 }
7384 }
7385
7386 if (Output.isFilename()) {
7387 CmdArgs.push_back("-o");
7388 CmdArgs.push_back(Output.getFilename());
7389 } else {
7390 assert(Output.isNothing() && "Invalid output.");
7391 }
7392
7393 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7394 if (!Args.hasArg(options::OPT_shared))
7395 CmdArgs.push_back(
7396 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7397
7398 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7399 CmdArgs.push_back(
7400 Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
7401 CmdArgs.push_back(
7402 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7403 }
7404
7405 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
7406
7407 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7408 options::OPT_e, options::OPT_r});
7409
7410 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7411
7412 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7413 if (getToolChain().getDriver().CCCIsCXX())
7414 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7415 CmdArgs.push_back("-lgcc_s");
7416 CmdArgs.push_back("-lc");
7417 if (!Args.hasArg(options::OPT_shared)) {
7418 CmdArgs.push_back("-lgcc");
7419 CmdArgs.push_back("-lm");
7420 }
7421 }
7422
7423 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7424 CmdArgs.push_back(
7425 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7426 }
7427 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7428
7429 getToolChain().addProfileRTLibs(Args, CmdArgs);
7430
7431 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7432 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7433 }
7434
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7435 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7436 const InputInfo &Output,
7437 const InputInfoList &Inputs,
7438 const ArgList &Args,
7439 const char *LinkingOutput) const {
7440 claimNoWarnArgs(Args);
7441 ArgStringList CmdArgs;
7442
7443 switch (getToolChain().getArch()) {
7444 case llvm::Triple::x86:
7445 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
7446 // instruct as in the base system to assemble 32-bit code.
7447 CmdArgs.push_back("--32");
7448 break;
7449
7450 case llvm::Triple::ppc:
7451 CmdArgs.push_back("-mppc");
7452 CmdArgs.push_back("-many");
7453 break;
7454
7455 case llvm::Triple::sparc:
7456 case llvm::Triple::sparcel: {
7457 CmdArgs.push_back("-32");
7458 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7459 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7460 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7461 break;
7462 }
7463
7464 case llvm::Triple::sparcv9: {
7465 CmdArgs.push_back("-64");
7466 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7467 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7468 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7469 break;
7470 }
7471
7472 case llvm::Triple::mips64:
7473 case llvm::Triple::mips64el: {
7474 StringRef CPUName;
7475 StringRef ABIName;
7476 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7477
7478 CmdArgs.push_back("-mabi");
7479 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7480
7481 if (getToolChain().getArch() == llvm::Triple::mips64)
7482 CmdArgs.push_back("-EB");
7483 else
7484 CmdArgs.push_back("-EL");
7485
7486 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7487 break;
7488 }
7489
7490 default:
7491 break;
7492 }
7493
7494 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7495
7496 CmdArgs.push_back("-o");
7497 CmdArgs.push_back(Output.getFilename());
7498
7499 for (const auto &II : Inputs)
7500 CmdArgs.push_back(II.getFilename());
7501
7502 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7503 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7504 }
7505
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7506 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7507 const InputInfo &Output,
7508 const InputInfoList &Inputs,
7509 const ArgList &Args,
7510 const char *LinkingOutput) const {
7511 const Driver &D = getToolChain().getDriver();
7512 ArgStringList CmdArgs;
7513
7514 // Silence warning for "clang -g foo.o -o foo"
7515 Args.ClaimAllArgs(options::OPT_g_Group);
7516 // and "clang -emit-llvm foo.o -o foo"
7517 Args.ClaimAllArgs(options::OPT_emit_llvm);
7518 // and for "clang -w foo.o -o foo". Other warning options are already
7519 // handled somewhere else.
7520 Args.ClaimAllArgs(options::OPT_w);
7521
7522 if (getToolChain().getArch() == llvm::Triple::mips64)
7523 CmdArgs.push_back("-EB");
7524 else if (getToolChain().getArch() == llvm::Triple::mips64el)
7525 CmdArgs.push_back("-EL");
7526
7527 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7528 CmdArgs.push_back("-e");
7529 CmdArgs.push_back("__start");
7530 }
7531
7532 if (Args.hasArg(options::OPT_static)) {
7533 CmdArgs.push_back("-Bstatic");
7534 } else {
7535 if (Args.hasArg(options::OPT_rdynamic))
7536 CmdArgs.push_back("-export-dynamic");
7537 CmdArgs.push_back("--eh-frame-hdr");
7538 CmdArgs.push_back("-Bdynamic");
7539 if (Args.hasArg(options::OPT_shared)) {
7540 CmdArgs.push_back("-shared");
7541 } else {
7542 CmdArgs.push_back("-dynamic-linker");
7543 CmdArgs.push_back("/usr/libexec/ld.so");
7544 }
7545 }
7546
7547 if (Args.hasArg(options::OPT_nopie))
7548 CmdArgs.push_back("-nopie");
7549
7550 if (Output.isFilename()) {
7551 CmdArgs.push_back("-o");
7552 CmdArgs.push_back(Output.getFilename());
7553 } else {
7554 assert(Output.isNothing() && "Invalid output.");
7555 }
7556
7557 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7558 if (!Args.hasArg(options::OPT_shared)) {
7559 if (Args.hasArg(options::OPT_pg))
7560 CmdArgs.push_back(
7561 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7562 else
7563 CmdArgs.push_back(
7564 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7565 CmdArgs.push_back(
7566 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7567 } else {
7568 CmdArgs.push_back(
7569 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7570 }
7571 }
7572
7573 std::string Triple = getToolChain().getTripleString();
7574 if (Triple.substr(0, 6) == "x86_64")
7575 Triple.replace(0, 6, "amd64");
7576 CmdArgs.push_back(
7577 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
7578
7579 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7580 options::OPT_e, options::OPT_s, options::OPT_t,
7581 options::OPT_Z_Flag, options::OPT_r});
7582
7583 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7584
7585 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7586 if (D.CCCIsCXX()) {
7587 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7588 if (Args.hasArg(options::OPT_pg))
7589 CmdArgs.push_back("-lm_p");
7590 else
7591 CmdArgs.push_back("-lm");
7592 }
7593
7594 // FIXME: For some reason GCC passes -lgcc before adding
7595 // the default system libraries. Just mimic this for now.
7596 CmdArgs.push_back("-lgcc");
7597
7598 if (Args.hasArg(options::OPT_pthread)) {
7599 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7600 CmdArgs.push_back("-lpthread_p");
7601 else
7602 CmdArgs.push_back("-lpthread");
7603 }
7604
7605 if (!Args.hasArg(options::OPT_shared)) {
7606 if (Args.hasArg(options::OPT_pg))
7607 CmdArgs.push_back("-lc_p");
7608 else
7609 CmdArgs.push_back("-lc");
7610 }
7611
7612 CmdArgs.push_back("-lgcc");
7613 }
7614
7615 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7616 if (!Args.hasArg(options::OPT_shared))
7617 CmdArgs.push_back(
7618 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7619 else
7620 CmdArgs.push_back(
7621 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7622 }
7623
7624 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7625 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7626 }
7627
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7628 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7629 const InputInfo &Output,
7630 const InputInfoList &Inputs,
7631 const ArgList &Args,
7632 const char *LinkingOutput) const {
7633 claimNoWarnArgs(Args);
7634 ArgStringList CmdArgs;
7635
7636 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7637
7638 CmdArgs.push_back("-o");
7639 CmdArgs.push_back(Output.getFilename());
7640
7641 for (const auto &II : Inputs)
7642 CmdArgs.push_back(II.getFilename());
7643
7644 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7645 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7646 }
7647
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7648 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7649 const InputInfo &Output,
7650 const InputInfoList &Inputs,
7651 const ArgList &Args,
7652 const char *LinkingOutput) const {
7653 const Driver &D = getToolChain().getDriver();
7654 ArgStringList CmdArgs;
7655
7656 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7657 CmdArgs.push_back("-e");
7658 CmdArgs.push_back("__start");
7659 }
7660
7661 if (Args.hasArg(options::OPT_static)) {
7662 CmdArgs.push_back("-Bstatic");
7663 } else {
7664 if (Args.hasArg(options::OPT_rdynamic))
7665 CmdArgs.push_back("-export-dynamic");
7666 CmdArgs.push_back("--eh-frame-hdr");
7667 CmdArgs.push_back("-Bdynamic");
7668 if (Args.hasArg(options::OPT_shared)) {
7669 CmdArgs.push_back("-shared");
7670 } else {
7671 CmdArgs.push_back("-dynamic-linker");
7672 CmdArgs.push_back("/usr/libexec/ld.so");
7673 }
7674 }
7675
7676 if (Output.isFilename()) {
7677 CmdArgs.push_back("-o");
7678 CmdArgs.push_back(Output.getFilename());
7679 } else {
7680 assert(Output.isNothing() && "Invalid output.");
7681 }
7682
7683 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7684 if (!Args.hasArg(options::OPT_shared)) {
7685 if (Args.hasArg(options::OPT_pg))
7686 CmdArgs.push_back(
7687 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7688 else
7689 CmdArgs.push_back(
7690 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7691 CmdArgs.push_back(
7692 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7693 } else {
7694 CmdArgs.push_back(
7695 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7696 }
7697 }
7698
7699 Args.AddAllArgs(CmdArgs,
7700 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
7701
7702 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7703
7704 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7705 if (D.CCCIsCXX()) {
7706 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7707 if (Args.hasArg(options::OPT_pg))
7708 CmdArgs.push_back("-lm_p");
7709 else
7710 CmdArgs.push_back("-lm");
7711 }
7712
7713 if (Args.hasArg(options::OPT_pthread)) {
7714 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7715 CmdArgs.push_back("-lpthread_p");
7716 else
7717 CmdArgs.push_back("-lpthread");
7718 }
7719
7720 if (!Args.hasArg(options::OPT_shared)) {
7721 if (Args.hasArg(options::OPT_pg))
7722 CmdArgs.push_back("-lc_p");
7723 else
7724 CmdArgs.push_back("-lc");
7725 }
7726
7727 StringRef MyArch;
7728 switch (getToolChain().getArch()) {
7729 case llvm::Triple::arm:
7730 MyArch = "arm";
7731 break;
7732 case llvm::Triple::x86:
7733 MyArch = "i386";
7734 break;
7735 case llvm::Triple::x86_64:
7736 MyArch = "amd64";
7737 break;
7738 default:
7739 llvm_unreachable("Unsupported architecture");
7740 }
7741 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7742 }
7743
7744 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7745 if (!Args.hasArg(options::OPT_shared))
7746 CmdArgs.push_back(
7747 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7748 else
7749 CmdArgs.push_back(
7750 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7751 }
7752
7753 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7754 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7755 }
7756
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7757 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7758 const InputInfo &Output,
7759 const InputInfoList &Inputs,
7760 const ArgList &Args,
7761 const char *LinkingOutput) const {
7762 claimNoWarnArgs(Args);
7763 ArgStringList CmdArgs;
7764
7765 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7766 // instruct as in the base system to assemble 32-bit code.
7767 switch (getToolChain().getArch()) {
7768 default:
7769 break;
7770 case llvm::Triple::x86:
7771 CmdArgs.push_back("--32");
7772 break;
7773 case llvm::Triple::ppc:
7774 CmdArgs.push_back("-a32");
7775 break;
7776 case llvm::Triple::mips:
7777 case llvm::Triple::mipsel:
7778 case llvm::Triple::mips64:
7779 case llvm::Triple::mips64el: {
7780 StringRef CPUName;
7781 StringRef ABIName;
7782 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7783
7784 CmdArgs.push_back("-march");
7785 CmdArgs.push_back(CPUName.data());
7786
7787 CmdArgs.push_back("-mabi");
7788 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7789
7790 if (getToolChain().getArch() == llvm::Triple::mips ||
7791 getToolChain().getArch() == llvm::Triple::mips64)
7792 CmdArgs.push_back("-EB");
7793 else
7794 CmdArgs.push_back("-EL");
7795
7796 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7797 break;
7798 }
7799 case llvm::Triple::arm:
7800 case llvm::Triple::armeb:
7801 case llvm::Triple::thumb:
7802 case llvm::Triple::thumbeb: {
7803 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
7804
7805 if (ABI == arm::FloatABI::Hard)
7806 CmdArgs.push_back("-mfpu=vfp");
7807 else
7808 CmdArgs.push_back("-mfpu=softvfp");
7809
7810 switch (getToolChain().getTriple().getEnvironment()) {
7811 case llvm::Triple::GNUEABIHF:
7812 case llvm::Triple::GNUEABI:
7813 case llvm::Triple::EABI:
7814 CmdArgs.push_back("-meabi=5");
7815 break;
7816
7817 default:
7818 CmdArgs.push_back("-matpcs");
7819 }
7820 break;
7821 }
7822 case llvm::Triple::sparc:
7823 case llvm::Triple::sparcel:
7824 case llvm::Triple::sparcv9: {
7825 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7826 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7827 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7828 break;
7829 }
7830 }
7831
7832 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7833
7834 CmdArgs.push_back("-o");
7835 CmdArgs.push_back(Output.getFilename());
7836
7837 for (const auto &II : Inputs)
7838 CmdArgs.push_back(II.getFilename());
7839
7840 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7841 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7842 }
7843
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7844 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7845 const InputInfo &Output,
7846 const InputInfoList &Inputs,
7847 const ArgList &Args,
7848 const char *LinkingOutput) const {
7849 const toolchains::FreeBSD &ToolChain =
7850 static_cast<const toolchains::FreeBSD &>(getToolChain());
7851 const Driver &D = ToolChain.getDriver();
7852 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7853 const bool IsPIE =
7854 !Args.hasArg(options::OPT_shared) &&
7855 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7856 ArgStringList CmdArgs;
7857
7858 // Silence warning for "clang -g foo.o -o foo"
7859 Args.ClaimAllArgs(options::OPT_g_Group);
7860 // and "clang -emit-llvm foo.o -o foo"
7861 Args.ClaimAllArgs(options::OPT_emit_llvm);
7862 // and for "clang -w foo.o -o foo". Other warning options are already
7863 // handled somewhere else.
7864 Args.ClaimAllArgs(options::OPT_w);
7865
7866 if (!D.SysRoot.empty())
7867 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7868
7869 if (IsPIE)
7870 CmdArgs.push_back("-pie");
7871
7872 if (Args.hasArg(options::OPT_static)) {
7873 CmdArgs.push_back("-Bstatic");
7874 } else {
7875 if (Args.hasArg(options::OPT_rdynamic))
7876 CmdArgs.push_back("-export-dynamic");
7877 CmdArgs.push_back("--eh-frame-hdr");
7878 if (Args.hasArg(options::OPT_shared)) {
7879 CmdArgs.push_back("-Bshareable");
7880 } else {
7881 CmdArgs.push_back("-dynamic-linker");
7882 CmdArgs.push_back("/libexec/ld-elf.so.1");
7883 }
7884 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7885 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7886 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7887 CmdArgs.push_back("--hash-style=both");
7888 }
7889 }
7890 CmdArgs.push_back("--enable-new-dtags");
7891 }
7892
7893 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7894 // instruct ld in the base system to link 32-bit code.
7895 if (Arch == llvm::Triple::x86) {
7896 CmdArgs.push_back("-m");
7897 CmdArgs.push_back("elf_i386_fbsd");
7898 }
7899
7900 if (Arch == llvm::Triple::ppc) {
7901 CmdArgs.push_back("-m");
7902 CmdArgs.push_back("elf32ppc_fbsd");
7903 }
7904
7905 if (Output.isFilename()) {
7906 CmdArgs.push_back("-o");
7907 CmdArgs.push_back(Output.getFilename());
7908 } else {
7909 assert(Output.isNothing() && "Invalid output.");
7910 }
7911
7912 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7913 const char *crt1 = nullptr;
7914 if (!Args.hasArg(options::OPT_shared)) {
7915 if (Args.hasArg(options::OPT_pg))
7916 crt1 = "gcrt1.o";
7917 else if (IsPIE)
7918 crt1 = "Scrt1.o";
7919 else
7920 crt1 = "crt1.o";
7921 }
7922 if (crt1)
7923 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7924
7925 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7926
7927 const char *crtbegin = nullptr;
7928 if (Args.hasArg(options::OPT_static))
7929 crtbegin = "crtbeginT.o";
7930 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7931 crtbegin = "crtbeginS.o";
7932 else
7933 crtbegin = "crtbegin.o";
7934
7935 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7936 }
7937
7938 Args.AddAllArgs(CmdArgs, options::OPT_L);
7939 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7940 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7941 Args.AddAllArgs(CmdArgs, options::OPT_e);
7942 Args.AddAllArgs(CmdArgs, options::OPT_s);
7943 Args.AddAllArgs(CmdArgs, options::OPT_t);
7944 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7945 Args.AddAllArgs(CmdArgs, options::OPT_r);
7946
7947 if (D.isUsingLTO())
7948 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7949
7950 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7951 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7952
7953 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7954 addOpenMPRuntime(CmdArgs, ToolChain, Args);
7955 if (D.CCCIsCXX()) {
7956 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7957 if (Args.hasArg(options::OPT_pg))
7958 CmdArgs.push_back("-lm_p");
7959 else
7960 CmdArgs.push_back("-lm");
7961 }
7962 if (NeedsSanitizerDeps)
7963 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7964 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7965 // the default system libraries. Just mimic this for now.
7966 if (Args.hasArg(options::OPT_pg))
7967 CmdArgs.push_back("-lgcc_p");
7968 else
7969 CmdArgs.push_back("-lgcc");
7970 if (Args.hasArg(options::OPT_static)) {
7971 CmdArgs.push_back("-lgcc_eh");
7972 } else if (Args.hasArg(options::OPT_pg)) {
7973 CmdArgs.push_back("-lgcc_eh_p");
7974 } else {
7975 CmdArgs.push_back("--as-needed");
7976 CmdArgs.push_back("-lgcc_s");
7977 CmdArgs.push_back("--no-as-needed");
7978 }
7979
7980 if (Args.hasArg(options::OPT_pthread)) {
7981 if (Args.hasArg(options::OPT_pg))
7982 CmdArgs.push_back("-lpthread_p");
7983 else
7984 CmdArgs.push_back("-lpthread");
7985 }
7986
7987 if (Args.hasArg(options::OPT_pg)) {
7988 if (Args.hasArg(options::OPT_shared))
7989 CmdArgs.push_back("-lc");
7990 else
7991 CmdArgs.push_back("-lc_p");
7992 CmdArgs.push_back("-lgcc_p");
7993 } else {
7994 CmdArgs.push_back("-lc");
7995 CmdArgs.push_back("-lgcc");
7996 }
7997
7998 if (Args.hasArg(options::OPT_static)) {
7999 CmdArgs.push_back("-lgcc_eh");
8000 } else if (Args.hasArg(options::OPT_pg)) {
8001 CmdArgs.push_back("-lgcc_eh_p");
8002 } else {
8003 CmdArgs.push_back("--as-needed");
8004 CmdArgs.push_back("-lgcc_s");
8005 CmdArgs.push_back("--no-as-needed");
8006 }
8007 }
8008
8009 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8010 if (Args.hasArg(options::OPT_shared) || IsPIE)
8011 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8012 else
8013 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8014 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8015 }
8016
8017 ToolChain.addProfileRTLibs(Args, CmdArgs);
8018
8019 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8020 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8021 }
8022
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8023 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8024 const InputInfo &Output,
8025 const InputInfoList &Inputs,
8026 const ArgList &Args,
8027 const char *LinkingOutput) const {
8028 claimNoWarnArgs(Args);
8029 ArgStringList CmdArgs;
8030
8031 // GNU as needs different flags for creating the correct output format
8032 // on architectures with different ABIs or optional feature sets.
8033 switch (getToolChain().getArch()) {
8034 case llvm::Triple::x86:
8035 CmdArgs.push_back("--32");
8036 break;
8037 case llvm::Triple::arm:
8038 case llvm::Triple::armeb:
8039 case llvm::Triple::thumb:
8040 case llvm::Triple::thumbeb: {
8041 StringRef MArch, MCPU;
8042 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8043 std::string Arch =
8044 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8045 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8046 break;
8047 }
8048
8049 case llvm::Triple::mips:
8050 case llvm::Triple::mipsel:
8051 case llvm::Triple::mips64:
8052 case llvm::Triple::mips64el: {
8053 StringRef CPUName;
8054 StringRef ABIName;
8055 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8056
8057 CmdArgs.push_back("-march");
8058 CmdArgs.push_back(CPUName.data());
8059
8060 CmdArgs.push_back("-mabi");
8061 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8062
8063 if (getToolChain().getArch() == llvm::Triple::mips ||
8064 getToolChain().getArch() == llvm::Triple::mips64)
8065 CmdArgs.push_back("-EB");
8066 else
8067 CmdArgs.push_back("-EL");
8068
8069 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8070 break;
8071 }
8072
8073 case llvm::Triple::sparc:
8074 case llvm::Triple::sparcel: {
8075 CmdArgs.push_back("-32");
8076 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8077 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8078 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8079 break;
8080 }
8081
8082 case llvm::Triple::sparcv9: {
8083 CmdArgs.push_back("-64");
8084 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8085 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8086 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8087 break;
8088 }
8089
8090 default:
8091 break;
8092 }
8093
8094 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8095
8096 CmdArgs.push_back("-o");
8097 CmdArgs.push_back(Output.getFilename());
8098
8099 for (const auto &II : Inputs)
8100 CmdArgs.push_back(II.getFilename());
8101
8102 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8103 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8104 }
8105
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8106 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8107 const InputInfo &Output,
8108 const InputInfoList &Inputs,
8109 const ArgList &Args,
8110 const char *LinkingOutput) const {
8111 const Driver &D = getToolChain().getDriver();
8112 ArgStringList CmdArgs;
8113
8114 if (!D.SysRoot.empty())
8115 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8116
8117 CmdArgs.push_back("--eh-frame-hdr");
8118 if (Args.hasArg(options::OPT_static)) {
8119 CmdArgs.push_back("-Bstatic");
8120 } else {
8121 if (Args.hasArg(options::OPT_rdynamic))
8122 CmdArgs.push_back("-export-dynamic");
8123 if (Args.hasArg(options::OPT_shared)) {
8124 CmdArgs.push_back("-Bshareable");
8125 } else {
8126 CmdArgs.push_back("-dynamic-linker");
8127 CmdArgs.push_back("/libexec/ld.elf_so");
8128 }
8129 }
8130
8131 // Many NetBSD architectures support more than one ABI.
8132 // Determine the correct emulation for ld.
8133 switch (getToolChain().getArch()) {
8134 case llvm::Triple::x86:
8135 CmdArgs.push_back("-m");
8136 CmdArgs.push_back("elf_i386");
8137 break;
8138 case llvm::Triple::arm:
8139 case llvm::Triple::thumb:
8140 CmdArgs.push_back("-m");
8141 switch (getToolChain().getTriple().getEnvironment()) {
8142 case llvm::Triple::EABI:
8143 case llvm::Triple::GNUEABI:
8144 CmdArgs.push_back("armelf_nbsd_eabi");
8145 break;
8146 case llvm::Triple::EABIHF:
8147 case llvm::Triple::GNUEABIHF:
8148 CmdArgs.push_back("armelf_nbsd_eabihf");
8149 break;
8150 default:
8151 CmdArgs.push_back("armelf_nbsd");
8152 break;
8153 }
8154 break;
8155 case llvm::Triple::armeb:
8156 case llvm::Triple::thumbeb:
8157 arm::appendEBLinkFlags(
8158 Args, CmdArgs,
8159 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8160 CmdArgs.push_back("-m");
8161 switch (getToolChain().getTriple().getEnvironment()) {
8162 case llvm::Triple::EABI:
8163 case llvm::Triple::GNUEABI:
8164 CmdArgs.push_back("armelfb_nbsd_eabi");
8165 break;
8166 case llvm::Triple::EABIHF:
8167 case llvm::Triple::GNUEABIHF:
8168 CmdArgs.push_back("armelfb_nbsd_eabihf");
8169 break;
8170 default:
8171 CmdArgs.push_back("armelfb_nbsd");
8172 break;
8173 }
8174 break;
8175 case llvm::Triple::mips64:
8176 case llvm::Triple::mips64el:
8177 if (mips::hasMipsAbiArg(Args, "32")) {
8178 CmdArgs.push_back("-m");
8179 if (getToolChain().getArch() == llvm::Triple::mips64)
8180 CmdArgs.push_back("elf32btsmip");
8181 else
8182 CmdArgs.push_back("elf32ltsmip");
8183 } else if (mips::hasMipsAbiArg(Args, "64")) {
8184 CmdArgs.push_back("-m");
8185 if (getToolChain().getArch() == llvm::Triple::mips64)
8186 CmdArgs.push_back("elf64btsmip");
8187 else
8188 CmdArgs.push_back("elf64ltsmip");
8189 }
8190 break;
8191 case llvm::Triple::ppc:
8192 CmdArgs.push_back("-m");
8193 CmdArgs.push_back("elf32ppc_nbsd");
8194 break;
8195
8196 case llvm::Triple::ppc64:
8197 case llvm::Triple::ppc64le:
8198 CmdArgs.push_back("-m");
8199 CmdArgs.push_back("elf64ppc");
8200 break;
8201
8202 case llvm::Triple::sparc:
8203 CmdArgs.push_back("-m");
8204 CmdArgs.push_back("elf32_sparc");
8205 break;
8206
8207 case llvm::Triple::sparcv9:
8208 CmdArgs.push_back("-m");
8209 CmdArgs.push_back("elf64_sparc");
8210 break;
8211
8212 default:
8213 break;
8214 }
8215
8216 if (Output.isFilename()) {
8217 CmdArgs.push_back("-o");
8218 CmdArgs.push_back(Output.getFilename());
8219 } else {
8220 assert(Output.isNothing() && "Invalid output.");
8221 }
8222
8223 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8224 if (!Args.hasArg(options::OPT_shared)) {
8225 CmdArgs.push_back(
8226 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8227 CmdArgs.push_back(
8228 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8229 CmdArgs.push_back(
8230 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8231 } else {
8232 CmdArgs.push_back(
8233 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8234 CmdArgs.push_back(
8235 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8236 }
8237 }
8238
8239 Args.AddAllArgs(CmdArgs, options::OPT_L);
8240 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8241 Args.AddAllArgs(CmdArgs, options::OPT_e);
8242 Args.AddAllArgs(CmdArgs, options::OPT_s);
8243 Args.AddAllArgs(CmdArgs, options::OPT_t);
8244 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8245 Args.AddAllArgs(CmdArgs, options::OPT_r);
8246
8247 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8248
8249 unsigned Major, Minor, Micro;
8250 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8251 bool useLibgcc = true;
8252 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
8253 switch (getToolChain().getArch()) {
8254 case llvm::Triple::aarch64:
8255 case llvm::Triple::arm:
8256 case llvm::Triple::armeb:
8257 case llvm::Triple::thumb:
8258 case llvm::Triple::thumbeb:
8259 case llvm::Triple::ppc:
8260 case llvm::Triple::ppc64:
8261 case llvm::Triple::ppc64le:
8262 case llvm::Triple::x86:
8263 case llvm::Triple::x86_64:
8264 useLibgcc = false;
8265 break;
8266 default:
8267 break;
8268 }
8269 }
8270
8271 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8272 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8273 if (D.CCCIsCXX()) {
8274 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8275 CmdArgs.push_back("-lm");
8276 }
8277 if (Args.hasArg(options::OPT_pthread))
8278 CmdArgs.push_back("-lpthread");
8279 CmdArgs.push_back("-lc");
8280
8281 if (useLibgcc) {
8282 if (Args.hasArg(options::OPT_static)) {
8283 // libgcc_eh depends on libc, so resolve as much as possible,
8284 // pull in any new requirements from libc and then get the rest
8285 // of libgcc.
8286 CmdArgs.push_back("-lgcc_eh");
8287 CmdArgs.push_back("-lc");
8288 CmdArgs.push_back("-lgcc");
8289 } else {
8290 CmdArgs.push_back("-lgcc");
8291 CmdArgs.push_back("--as-needed");
8292 CmdArgs.push_back("-lgcc_s");
8293 CmdArgs.push_back("--no-as-needed");
8294 }
8295 }
8296 }
8297
8298 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8299 if (!Args.hasArg(options::OPT_shared))
8300 CmdArgs.push_back(
8301 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8302 else
8303 CmdArgs.push_back(
8304 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8305 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8306 }
8307
8308 getToolChain().addProfileRTLibs(Args, CmdArgs);
8309
8310 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8311 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8312 }
8313
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8314 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8315 const InputInfo &Output,
8316 const InputInfoList &Inputs,
8317 const ArgList &Args,
8318 const char *LinkingOutput) const {
8319 claimNoWarnArgs(Args);
8320
8321 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8322 llvm::Triple Triple = llvm::Triple(TripleStr);
8323
8324 ArgStringList CmdArgs;
8325
8326 llvm::Reloc::Model RelocationModel;
8327 unsigned PICLevel;
8328 bool IsPIE;
8329 std::tie(RelocationModel, PICLevel, IsPIE) =
8330 ParsePICArgs(getToolChain(), Triple, Args);
8331
8332 switch (getToolChain().getArch()) {
8333 default:
8334 break;
8335 // Add --32/--64 to make sure we get the format we want.
8336 // This is incomplete
8337 case llvm::Triple::x86:
8338 CmdArgs.push_back("--32");
8339 break;
8340 case llvm::Triple::x86_64:
8341 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8342 CmdArgs.push_back("--x32");
8343 else
8344 CmdArgs.push_back("--64");
8345 break;
8346 case llvm::Triple::ppc:
8347 CmdArgs.push_back("-a32");
8348 CmdArgs.push_back("-mppc");
8349 CmdArgs.push_back("-many");
8350 break;
8351 case llvm::Triple::ppc64:
8352 CmdArgs.push_back("-a64");
8353 CmdArgs.push_back("-mppc64");
8354 CmdArgs.push_back("-many");
8355 break;
8356 case llvm::Triple::ppc64le:
8357 CmdArgs.push_back("-a64");
8358 CmdArgs.push_back("-mppc64");
8359 CmdArgs.push_back("-many");
8360 CmdArgs.push_back("-mlittle-endian");
8361 break;
8362 case llvm::Triple::sparc:
8363 case llvm::Triple::sparcel: {
8364 CmdArgs.push_back("-32");
8365 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8366 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8367 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8368 break;
8369 }
8370 case llvm::Triple::sparcv9: {
8371 CmdArgs.push_back("-64");
8372 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8373 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8374 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8375 break;
8376 }
8377 case llvm::Triple::arm:
8378 case llvm::Triple::armeb:
8379 case llvm::Triple::thumb:
8380 case llvm::Triple::thumbeb: {
8381 const llvm::Triple &Triple2 = getToolChain().getTriple();
8382 switch (Triple2.getSubArch()) {
8383 case llvm::Triple::ARMSubArch_v7:
8384 CmdArgs.push_back("-mfpu=neon");
8385 break;
8386 case llvm::Triple::ARMSubArch_v8:
8387 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
8388 break;
8389 default:
8390 break;
8391 }
8392
8393 switch (arm::getARMFloatABI(getToolChain(), Args)) {
8394 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
8395 case arm::FloatABI::Soft:
8396 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
8397 break;
8398 case arm::FloatABI::SoftFP:
8399 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
8400 break;
8401 case arm::FloatABI::Hard:
8402 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
8403 break;
8404 }
8405
8406 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
8407
8408 // FIXME: remove krait check when GNU tools support krait cpu
8409 // for now replace it with -mcpu=cortex-a15 to avoid a lower
8410 // march from being picked in the absence of a cpu flag.
8411 Arg *A;
8412 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
8413 StringRef(A->getValue()).lower() == "krait")
8414 CmdArgs.push_back("-mcpu=cortex-a15");
8415 else
8416 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
8417 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
8418 break;
8419 }
8420 case llvm::Triple::mips:
8421 case llvm::Triple::mipsel:
8422 case llvm::Triple::mips64:
8423 case llvm::Triple::mips64el: {
8424 StringRef CPUName;
8425 StringRef ABIName;
8426 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8427 ABIName = getGnuCompatibleMipsABIName(ABIName);
8428
8429 CmdArgs.push_back("-march");
8430 CmdArgs.push_back(CPUName.data());
8431
8432 CmdArgs.push_back("-mabi");
8433 CmdArgs.push_back(ABIName.data());
8434
8435 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
8436 // or -mshared (not implemented) is in effect.
8437 if (RelocationModel == llvm::Reloc::Static)
8438 CmdArgs.push_back("-mno-shared");
8439
8440 // LLVM doesn't support -mplt yet and acts as if it is always given.
8441 // However, -mplt has no effect with the N64 ABI.
8442 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
8443
8444 if (getToolChain().getArch() == llvm::Triple::mips ||
8445 getToolChain().getArch() == llvm::Triple::mips64)
8446 CmdArgs.push_back("-EB");
8447 else
8448 CmdArgs.push_back("-EL");
8449
8450 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
8451 if (StringRef(A->getValue()) == "2008")
8452 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
8453 }
8454
8455 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
8456 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
8457 options::OPT_mfp64)) {
8458 A->claim();
8459 A->render(Args, CmdArgs);
8460 } else if (mips::shouldUseFPXX(
8461 Args, getToolChain().getTriple(), CPUName, ABIName,
8462 getMipsFloatABI(getToolChain().getDriver(), Args)))
8463 CmdArgs.push_back("-mfpxx");
8464
8465 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
8466 // -mno-mips16 is actually -no-mips16.
8467 if (Arg *A =
8468 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
8469 if (A->getOption().matches(options::OPT_mips16)) {
8470 A->claim();
8471 A->render(Args, CmdArgs);
8472 } else {
8473 A->claim();
8474 CmdArgs.push_back("-no-mips16");
8475 }
8476 }
8477
8478 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
8479 options::OPT_mno_micromips);
8480 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
8481 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
8482
8483 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
8484 // Do not use AddLastArg because not all versions of MIPS assembler
8485 // support -mmsa / -mno-msa options.
8486 if (A->getOption().matches(options::OPT_mmsa))
8487 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
8488 }
8489
8490 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
8491 options::OPT_msoft_float);
8492
8493 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
8494 options::OPT_msingle_float);
8495
8496 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
8497 options::OPT_mno_odd_spreg);
8498
8499 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8500 break;
8501 }
8502 case llvm::Triple::systemz: {
8503 // Always pass an -march option, since our default of z10 is later
8504 // than the GNU assembler's default.
8505 StringRef CPUName = getSystemZTargetCPU(Args);
8506 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
8507 break;
8508 }
8509 }
8510
8511 Args.AddAllArgs(CmdArgs, options::OPT_I);
8512 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8513
8514 CmdArgs.push_back("-o");
8515 CmdArgs.push_back(Output.getFilename());
8516
8517 for (const auto &II : Inputs)
8518 CmdArgs.push_back(II.getFilename());
8519
8520 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8521 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8522
8523 // Handle the debug info splitting at object creation time if we're
8524 // creating an object.
8525 // TODO: Currently only works on linux with newer objcopy.
8526 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
8527 getToolChain().getTriple().isOSLinux())
8528 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8529 SplitDebugName(Args, Inputs[0]));
8530 }
8531
AddLibgcc(const llvm::Triple & Triple,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)8532 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
8533 ArgStringList &CmdArgs, const ArgList &Args) {
8534 bool isAndroid = Triple.isAndroid();
8535 bool isCygMing = Triple.isOSCygMing();
8536 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
8537 Args.hasArg(options::OPT_static);
8538 if (!D.CCCIsCXX())
8539 CmdArgs.push_back("-lgcc");
8540
8541 if (StaticLibgcc || isAndroid) {
8542 if (D.CCCIsCXX())
8543 CmdArgs.push_back("-lgcc");
8544 } else {
8545 if (!D.CCCIsCXX() && !isCygMing)
8546 CmdArgs.push_back("--as-needed");
8547 CmdArgs.push_back("-lgcc_s");
8548 if (!D.CCCIsCXX() && !isCygMing)
8549 CmdArgs.push_back("--no-as-needed");
8550 }
8551
8552 if (StaticLibgcc && !isAndroid)
8553 CmdArgs.push_back("-lgcc_eh");
8554 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
8555 CmdArgs.push_back("-lgcc");
8556
8557 // According to Android ABI, we have to link with libdl if we are
8558 // linking with non-static libgcc.
8559 //
8560 // NOTE: This fixes a link error on Android MIPS as well. The non-static
8561 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
8562 if (isAndroid && !StaticLibgcc)
8563 CmdArgs.push_back("-ldl");
8564 }
8565
getLinuxDynamicLinker(const ArgList & Args,const toolchains::Linux & ToolChain)8566 static std::string getLinuxDynamicLinker(const ArgList &Args,
8567 const toolchains::Linux &ToolChain) {
8568 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8569
8570 if (ToolChain.getTriple().isAndroid()) {
8571 if (ToolChain.getTriple().isArch64Bit())
8572 return "/system/bin/linker64";
8573 else
8574 return "/system/bin/linker";
8575 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
8576 Arch == llvm::Triple::sparcel)
8577 return "/lib/ld-linux.so.2";
8578 else if (Arch == llvm::Triple::aarch64)
8579 return "/lib/ld-linux-aarch64.so.1";
8580 else if (Arch == llvm::Triple::aarch64_be)
8581 return "/lib/ld-linux-aarch64_be.so.1";
8582 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
8583 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8584 arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8585 return "/lib/ld-linux-armhf.so.3";
8586 else
8587 return "/lib/ld-linux.so.3";
8588 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
8589 // TODO: check which dynamic linker name.
8590 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8591 arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8592 return "/lib/ld-linux-armhf.so.3";
8593 else
8594 return "/lib/ld-linux.so.3";
8595 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8596 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8597 std::string LibDir =
8598 "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
8599 StringRef LibName;
8600 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8601 if (mips::isUCLibc(Args))
8602 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8603 else if (!ToolChain.getTriple().hasEnvironment()) {
8604 bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
8605 (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
8606 LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
8607 } else
8608 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8609
8610 return (LibDir + "/" + LibName).str();
8611 } else if (Arch == llvm::Triple::ppc)
8612 return "/lib/ld.so.1";
8613 else if (Arch == llvm::Triple::ppc64) {
8614 if (ppc::hasPPCAbiArg(Args, "elfv2"))
8615 return "/lib64/ld64.so.2";
8616 return "/lib64/ld64.so.1";
8617 } else if (Arch == llvm::Triple::ppc64le) {
8618 if (ppc::hasPPCAbiArg(Args, "elfv1"))
8619 return "/lib64/ld64.so.1";
8620 return "/lib64/ld64.so.2";
8621 } else if (Arch == llvm::Triple::systemz)
8622 return "/lib/ld64.so.1";
8623 else if (Arch == llvm::Triple::sparcv9)
8624 return "/lib64/ld-linux.so.2";
8625 else if (Arch == llvm::Triple::x86_64 &&
8626 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8627 return "/libx32/ld-linux-x32.so.2";
8628 else
8629 return "/lib64/ld-linux-x86-64.so.2";
8630 }
8631
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)8632 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8633 ArgStringList &CmdArgs, const ArgList &Args) {
8634 // Make use of compiler-rt if --rtlib option is used
8635 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8636
8637 switch (RLT) {
8638 case ToolChain::RLT_CompilerRT:
8639 switch (TC.getTriple().getOS()) {
8640 default:
8641 llvm_unreachable("unsupported OS");
8642 case llvm::Triple::Win32:
8643 case llvm::Triple::Linux:
8644 addClangRT(TC, Args, CmdArgs);
8645 break;
8646 }
8647 break;
8648 case ToolChain::RLT_Libgcc:
8649 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8650 break;
8651 }
8652 }
8653
getLDMOption(const llvm::Triple & T,const ArgList & Args)8654 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8655 switch (T.getArch()) {
8656 case llvm::Triple::x86:
8657 return "elf_i386";
8658 case llvm::Triple::aarch64:
8659 return "aarch64linux";
8660 case llvm::Triple::aarch64_be:
8661 return "aarch64_be_linux";
8662 case llvm::Triple::arm:
8663 case llvm::Triple::thumb:
8664 return "armelf_linux_eabi";
8665 case llvm::Triple::armeb:
8666 case llvm::Triple::thumbeb:
8667 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
8668 case llvm::Triple::ppc:
8669 return "elf32ppclinux";
8670 case llvm::Triple::ppc64:
8671 return "elf64ppc";
8672 case llvm::Triple::ppc64le:
8673 return "elf64lppc";
8674 case llvm::Triple::sparc:
8675 case llvm::Triple::sparcel:
8676 return "elf32_sparc";
8677 case llvm::Triple::sparcv9:
8678 return "elf64_sparc";
8679 case llvm::Triple::mips:
8680 return "elf32btsmip";
8681 case llvm::Triple::mipsel:
8682 return "elf32ltsmip";
8683 case llvm::Triple::mips64:
8684 if (mips::hasMipsAbiArg(Args, "n32"))
8685 return "elf32btsmipn32";
8686 return "elf64btsmip";
8687 case llvm::Triple::mips64el:
8688 if (mips::hasMipsAbiArg(Args, "n32"))
8689 return "elf32ltsmipn32";
8690 return "elf64ltsmip";
8691 case llvm::Triple::systemz:
8692 return "elf64_s390";
8693 case llvm::Triple::x86_64:
8694 if (T.getEnvironment() == llvm::Triple::GNUX32)
8695 return "elf32_x86_64";
8696 return "elf_x86_64";
8697 default:
8698 llvm_unreachable("Unexpected arch");
8699 }
8700 }
8701
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8702 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8703 const InputInfo &Output,
8704 const InputInfoList &Inputs,
8705 const ArgList &Args,
8706 const char *LinkingOutput) const {
8707 const toolchains::Linux &ToolChain =
8708 static_cast<const toolchains::Linux &>(getToolChain());
8709 const Driver &D = ToolChain.getDriver();
8710
8711 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8712 llvm::Triple Triple = llvm::Triple(TripleStr);
8713
8714 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8715 const bool isAndroid = ToolChain.getTriple().isAndroid();
8716 const bool IsPIE =
8717 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8718 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8719 const bool HasCRTBeginEndFiles =
8720 ToolChain.getTriple().hasEnvironment() ||
8721 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
8722
8723 ArgStringList CmdArgs;
8724
8725 // Silence warning for "clang -g foo.o -o foo"
8726 Args.ClaimAllArgs(options::OPT_g_Group);
8727 // and "clang -emit-llvm foo.o -o foo"
8728 Args.ClaimAllArgs(options::OPT_emit_llvm);
8729 // and for "clang -w foo.o -o foo". Other warning options are already
8730 // handled somewhere else.
8731 Args.ClaimAllArgs(options::OPT_w);
8732
8733 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8734 if (llvm::sys::path::filename(Exec) == "lld") {
8735 CmdArgs.push_back("-flavor");
8736 CmdArgs.push_back("old-gnu");
8737 CmdArgs.push_back("-target");
8738 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
8739 }
8740
8741 if (!D.SysRoot.empty())
8742 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8743
8744 if (IsPIE)
8745 CmdArgs.push_back("-pie");
8746
8747 if (Args.hasArg(options::OPT_rdynamic))
8748 CmdArgs.push_back("-export-dynamic");
8749
8750 if (Args.hasArg(options::OPT_s))
8751 CmdArgs.push_back("-s");
8752
8753 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8754 arm::appendEBLinkFlags(Args, CmdArgs, Triple);
8755
8756 for (const auto &Opt : ToolChain.ExtraOpts)
8757 CmdArgs.push_back(Opt.c_str());
8758
8759 if (!Args.hasArg(options::OPT_static)) {
8760 CmdArgs.push_back("--eh-frame-hdr");
8761 }
8762
8763 CmdArgs.push_back("-m");
8764 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8765
8766 if (Args.hasArg(options::OPT_static)) {
8767 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8768 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8769 CmdArgs.push_back("-Bstatic");
8770 else
8771 CmdArgs.push_back("-static");
8772 } else if (Args.hasArg(options::OPT_shared)) {
8773 CmdArgs.push_back("-shared");
8774 }
8775
8776 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8777 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8778 (!Args.hasArg(options::OPT_static) &&
8779 !Args.hasArg(options::OPT_shared))) {
8780 CmdArgs.push_back("-dynamic-linker");
8781 CmdArgs.push_back(Args.MakeArgString(
8782 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8783 }
8784
8785 CmdArgs.push_back("-o");
8786 CmdArgs.push_back(Output.getFilename());
8787
8788 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8789 if (!isAndroid) {
8790 const char *crt1 = nullptr;
8791 if (!Args.hasArg(options::OPT_shared)) {
8792 if (Args.hasArg(options::OPT_pg))
8793 crt1 = "gcrt1.o";
8794 else if (IsPIE)
8795 crt1 = "Scrt1.o";
8796 else
8797 crt1 = "crt1.o";
8798 }
8799 if (crt1)
8800 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8801
8802 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8803 }
8804
8805 const char *crtbegin;
8806 if (Args.hasArg(options::OPT_static))
8807 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8808 else if (Args.hasArg(options::OPT_shared))
8809 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8810 else if (IsPIE)
8811 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8812 else
8813 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8814
8815 if (HasCRTBeginEndFiles)
8816 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8817
8818 // Add crtfastmath.o if available and fast math is enabled.
8819 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8820 }
8821
8822 Args.AddAllArgs(CmdArgs, options::OPT_L);
8823 Args.AddAllArgs(CmdArgs, options::OPT_u);
8824
8825 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8826
8827 if (D.isUsingLTO())
8828 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8829
8830 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8831 CmdArgs.push_back("--no-demangle");
8832
8833 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8834 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8835 // The profile runtime also needs access to system libraries.
8836 getToolChain().addProfileRTLibs(Args, CmdArgs);
8837
8838 if (D.CCCIsCXX() &&
8839 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8840 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8841 !Args.hasArg(options::OPT_static);
8842 if (OnlyLibstdcxxStatic)
8843 CmdArgs.push_back("-Bstatic");
8844 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8845 if (OnlyLibstdcxxStatic)
8846 CmdArgs.push_back("-Bdynamic");
8847 CmdArgs.push_back("-lm");
8848 }
8849 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8850 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8851
8852 if (!Args.hasArg(options::OPT_nostdlib)) {
8853 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8854 if (Args.hasArg(options::OPT_static))
8855 CmdArgs.push_back("--start-group");
8856
8857 if (NeedsSanitizerDeps)
8858 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8859
8860 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8861 Args.hasArg(options::OPT_pthreads);
8862
8863 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8864 options::OPT_fno_openmp, false)) {
8865 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8866 // FIXME: Does this really make sense for all GNU toolchains?
8867 WantPthread = true;
8868
8869 // Also link the particular OpenMP runtimes.
8870 switch (getOpenMPRuntime(ToolChain, Args)) {
8871 case OMPRT_OMP:
8872 CmdArgs.push_back("-lomp");
8873 break;
8874 case OMPRT_GOMP:
8875 CmdArgs.push_back("-lgomp");
8876
8877 // FIXME: Exclude this for platforms with libgomp that don't require
8878 // librt. Most modern Linux platforms require it, but some may not.
8879 CmdArgs.push_back("-lrt");
8880 break;
8881 case OMPRT_IOMP5:
8882 CmdArgs.push_back("-liomp5");
8883 break;
8884 case OMPRT_Unknown:
8885 // Already diagnosed.
8886 break;
8887 }
8888 }
8889
8890 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8891
8892 if (WantPthread && !isAndroid)
8893 CmdArgs.push_back("-lpthread");
8894
8895 CmdArgs.push_back("-lc");
8896
8897 if (Args.hasArg(options::OPT_static))
8898 CmdArgs.push_back("--end-group");
8899 else
8900 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8901 }
8902
8903 if (!Args.hasArg(options::OPT_nostartfiles)) {
8904 const char *crtend;
8905 if (Args.hasArg(options::OPT_shared))
8906 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8907 else if (IsPIE)
8908 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8909 else
8910 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8911
8912 if (HasCRTBeginEndFiles)
8913 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8914 if (!isAndroid)
8915 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8916 }
8917 }
8918
8919 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8920 }
8921
8922 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8923 // for the various SFI requirements like register masking. The assembly tool
8924 // inserts the file containing the macros as an input into all the assembly
8925 // jobs.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8926 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8927 const InputInfo &Output,
8928 const InputInfoList &Inputs,
8929 const ArgList &Args,
8930 const char *LinkingOutput) const {
8931 const toolchains::NaClToolChain &ToolChain =
8932 static_cast<const toolchains::NaClToolChain &>(getToolChain());
8933 InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8934 "nacl-arm-macros.s");
8935 InputInfoList NewInputs;
8936 NewInputs.push_back(NaClMacros);
8937 NewInputs.append(Inputs.begin(), Inputs.end());
8938 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8939 LinkingOutput);
8940 }
8941
8942 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8943 // we use static by default, do not yet support sanitizers or LTO, and a few
8944 // others. Eventually we can support more of that and hopefully migrate back
8945 // to gnutools::Linker.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8946 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8947 const InputInfo &Output,
8948 const InputInfoList &Inputs,
8949 const ArgList &Args,
8950 const char *LinkingOutput) const {
8951
8952 const toolchains::NaClToolChain &ToolChain =
8953 static_cast<const toolchains::NaClToolChain &>(getToolChain());
8954 const Driver &D = ToolChain.getDriver();
8955 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8956 const bool IsStatic =
8957 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8958
8959 ArgStringList CmdArgs;
8960
8961 // Silence warning for "clang -g foo.o -o foo"
8962 Args.ClaimAllArgs(options::OPT_g_Group);
8963 // and "clang -emit-llvm foo.o -o foo"
8964 Args.ClaimAllArgs(options::OPT_emit_llvm);
8965 // and for "clang -w foo.o -o foo". Other warning options are already
8966 // handled somewhere else.
8967 Args.ClaimAllArgs(options::OPT_w);
8968
8969 if (!D.SysRoot.empty())
8970 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8971
8972 if (Args.hasArg(options::OPT_rdynamic))
8973 CmdArgs.push_back("-export-dynamic");
8974
8975 if (Args.hasArg(options::OPT_s))
8976 CmdArgs.push_back("-s");
8977
8978 // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
8979 // from there is --build-id, which we do want.
8980 CmdArgs.push_back("--build-id");
8981
8982 if (!IsStatic)
8983 CmdArgs.push_back("--eh-frame-hdr");
8984
8985 CmdArgs.push_back("-m");
8986 if (Arch == llvm::Triple::x86)
8987 CmdArgs.push_back("elf_i386_nacl");
8988 else if (Arch == llvm::Triple::arm)
8989 CmdArgs.push_back("armelf_nacl");
8990 else if (Arch == llvm::Triple::x86_64)
8991 CmdArgs.push_back("elf_x86_64_nacl");
8992 else if (Arch == llvm::Triple::mipsel)
8993 CmdArgs.push_back("mipselelf_nacl");
8994 else
8995 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8996 << "Native Client";
8997
8998 if (IsStatic)
8999 CmdArgs.push_back("-static");
9000 else if (Args.hasArg(options::OPT_shared))
9001 CmdArgs.push_back("-shared");
9002
9003 CmdArgs.push_back("-o");
9004 CmdArgs.push_back(Output.getFilename());
9005 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9006 if (!Args.hasArg(options::OPT_shared))
9007 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9008 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9009
9010 const char *crtbegin;
9011 if (IsStatic)
9012 crtbegin = "crtbeginT.o";
9013 else if (Args.hasArg(options::OPT_shared))
9014 crtbegin = "crtbeginS.o";
9015 else
9016 crtbegin = "crtbegin.o";
9017 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9018 }
9019
9020 Args.AddAllArgs(CmdArgs, options::OPT_L);
9021 Args.AddAllArgs(CmdArgs, options::OPT_u);
9022
9023 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9024
9025 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9026 CmdArgs.push_back("--no-demangle");
9027
9028 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9029
9030 if (D.CCCIsCXX() &&
9031 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9032 bool OnlyLibstdcxxStatic =
9033 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9034 if (OnlyLibstdcxxStatic)
9035 CmdArgs.push_back("-Bstatic");
9036 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9037 if (OnlyLibstdcxxStatic)
9038 CmdArgs.push_back("-Bdynamic");
9039 CmdArgs.push_back("-lm");
9040 }
9041
9042 if (!Args.hasArg(options::OPT_nostdlib)) {
9043 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9044 // Always use groups, since it has no effect on dynamic libraries.
9045 CmdArgs.push_back("--start-group");
9046 CmdArgs.push_back("-lc");
9047 // NaCl's libc++ currently requires libpthread, so just always include it
9048 // in the group for C++.
9049 if (Args.hasArg(options::OPT_pthread) ||
9050 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9051 // Gold, used by Mips, handles nested groups differently than ld, and
9052 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9053 // which is not a desired behaviour here.
9054 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9055 if (getToolChain().getArch() == llvm::Triple::mipsel)
9056 CmdArgs.push_back("-lnacl");
9057
9058 CmdArgs.push_back("-lpthread");
9059 }
9060
9061 CmdArgs.push_back("-lgcc");
9062 CmdArgs.push_back("--as-needed");
9063 if (IsStatic)
9064 CmdArgs.push_back("-lgcc_eh");
9065 else
9066 CmdArgs.push_back("-lgcc_s");
9067 CmdArgs.push_back("--no-as-needed");
9068
9069 // Mips needs to create and use pnacl_legacy library that contains
9070 // definitions from bitcode/pnaclmm.c and definitions for
9071 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9072 if (getToolChain().getArch() == llvm::Triple::mipsel)
9073 CmdArgs.push_back("-lpnacl_legacy");
9074
9075 CmdArgs.push_back("--end-group");
9076 }
9077
9078 if (!Args.hasArg(options::OPT_nostartfiles)) {
9079 const char *crtend;
9080 if (Args.hasArg(options::OPT_shared))
9081 crtend = "crtendS.o";
9082 else
9083 crtend = "crtend.o";
9084
9085 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9086 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9087 }
9088 }
9089
9090 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9091 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9092 }
9093
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9094 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9095 const InputInfo &Output,
9096 const InputInfoList &Inputs,
9097 const ArgList &Args,
9098 const char *LinkingOutput) const {
9099 claimNoWarnArgs(Args);
9100 ArgStringList CmdArgs;
9101
9102 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9103
9104 CmdArgs.push_back("-o");
9105 CmdArgs.push_back(Output.getFilename());
9106
9107 for (const auto &II : Inputs)
9108 CmdArgs.push_back(II.getFilename());
9109
9110 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9111 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9112 }
9113
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9114 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9115 const InputInfo &Output,
9116 const InputInfoList &Inputs,
9117 const ArgList &Args,
9118 const char *LinkingOutput) const {
9119 const Driver &D = getToolChain().getDriver();
9120 ArgStringList CmdArgs;
9121
9122 if (Output.isFilename()) {
9123 CmdArgs.push_back("-o");
9124 CmdArgs.push_back(Output.getFilename());
9125 } else {
9126 assert(Output.isNothing() && "Invalid output.");
9127 }
9128
9129 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9130 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9131 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9132 CmdArgs.push_back(
9133 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9134 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9135 }
9136
9137 Args.AddAllArgs(CmdArgs,
9138 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9139
9140 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9141
9142 getToolChain().addProfileRTLibs(Args, CmdArgs);
9143
9144 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9145 if (D.CCCIsCXX()) {
9146 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9147 CmdArgs.push_back("-lm");
9148 }
9149 }
9150
9151 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9152 if (Args.hasArg(options::OPT_pthread))
9153 CmdArgs.push_back("-lpthread");
9154 CmdArgs.push_back("-lc");
9155 CmdArgs.push_back("-lCompilerRT-Generic");
9156 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9157 CmdArgs.push_back(
9158 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9159 }
9160
9161 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9162 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9163 }
9164
9165 /// DragonFly Tools
9166
9167 // For now, DragonFly Assemble does just about the same as for
9168 // FreeBSD, but this may change soon.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9169 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9170 const InputInfo &Output,
9171 const InputInfoList &Inputs,
9172 const ArgList &Args,
9173 const char *LinkingOutput) const {
9174 claimNoWarnArgs(Args);
9175 ArgStringList CmdArgs;
9176
9177 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9178 // instruct as in the base system to assemble 32-bit code.
9179 if (getToolChain().getArch() == llvm::Triple::x86)
9180 CmdArgs.push_back("--32");
9181
9182 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9183
9184 CmdArgs.push_back("-o");
9185 CmdArgs.push_back(Output.getFilename());
9186
9187 for (const auto &II : Inputs)
9188 CmdArgs.push_back(II.getFilename());
9189
9190 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9191 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9192 }
9193
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9194 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9195 const InputInfo &Output,
9196 const InputInfoList &Inputs,
9197 const ArgList &Args,
9198 const char *LinkingOutput) const {
9199 const Driver &D = getToolChain().getDriver();
9200 ArgStringList CmdArgs;
9201 bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
9202
9203 if (!D.SysRoot.empty())
9204 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9205
9206 CmdArgs.push_back("--eh-frame-hdr");
9207 if (Args.hasArg(options::OPT_static)) {
9208 CmdArgs.push_back("-Bstatic");
9209 } else {
9210 if (Args.hasArg(options::OPT_rdynamic))
9211 CmdArgs.push_back("-export-dynamic");
9212 if (Args.hasArg(options::OPT_shared))
9213 CmdArgs.push_back("-Bshareable");
9214 else {
9215 CmdArgs.push_back("-dynamic-linker");
9216 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9217 }
9218 CmdArgs.push_back("--hash-style=both");
9219 }
9220
9221 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9222 // instruct ld in the base system to link 32-bit code.
9223 if (getToolChain().getArch() == llvm::Triple::x86) {
9224 CmdArgs.push_back("-m");
9225 CmdArgs.push_back("elf_i386");
9226 }
9227
9228 if (Output.isFilename()) {
9229 CmdArgs.push_back("-o");
9230 CmdArgs.push_back(Output.getFilename());
9231 } else {
9232 assert(Output.isNothing() && "Invalid output.");
9233 }
9234
9235 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9236 if (!Args.hasArg(options::OPT_shared)) {
9237 if (Args.hasArg(options::OPT_pg))
9238 CmdArgs.push_back(
9239 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9240 else {
9241 if (Args.hasArg(options::OPT_pie))
9242 CmdArgs.push_back(
9243 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9244 else
9245 CmdArgs.push_back(
9246 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9247 }
9248 }
9249 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9250 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9251 CmdArgs.push_back(
9252 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9253 else
9254 CmdArgs.push_back(
9255 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9256 }
9257
9258 Args.AddAllArgs(CmdArgs,
9259 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9260
9261 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9262
9263 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9264 // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
9265 // rpaths
9266 if (UseGCC47)
9267 CmdArgs.push_back("-L/usr/lib/gcc47");
9268 else
9269 CmdArgs.push_back("-L/usr/lib/gcc44");
9270
9271 if (!Args.hasArg(options::OPT_static)) {
9272 if (UseGCC47) {
9273 CmdArgs.push_back("-rpath");
9274 CmdArgs.push_back("/usr/lib/gcc47");
9275 } else {
9276 CmdArgs.push_back("-rpath");
9277 CmdArgs.push_back("/usr/lib/gcc44");
9278 }
9279 }
9280
9281 if (D.CCCIsCXX()) {
9282 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9283 CmdArgs.push_back("-lm");
9284 }
9285
9286 if (Args.hasArg(options::OPT_pthread))
9287 CmdArgs.push_back("-lpthread");
9288
9289 if (!Args.hasArg(options::OPT_nolibc)) {
9290 CmdArgs.push_back("-lc");
9291 }
9292
9293 if (UseGCC47) {
9294 if (Args.hasArg(options::OPT_static) ||
9295 Args.hasArg(options::OPT_static_libgcc)) {
9296 CmdArgs.push_back("-lgcc");
9297 CmdArgs.push_back("-lgcc_eh");
9298 } else {
9299 if (Args.hasArg(options::OPT_shared_libgcc)) {
9300 CmdArgs.push_back("-lgcc_pic");
9301 if (!Args.hasArg(options::OPT_shared))
9302 CmdArgs.push_back("-lgcc");
9303 } else {
9304 CmdArgs.push_back("-lgcc");
9305 CmdArgs.push_back("--as-needed");
9306 CmdArgs.push_back("-lgcc_pic");
9307 CmdArgs.push_back("--no-as-needed");
9308 }
9309 }
9310 } else {
9311 if (Args.hasArg(options::OPT_shared)) {
9312 CmdArgs.push_back("-lgcc_pic");
9313 } else {
9314 CmdArgs.push_back("-lgcc");
9315 }
9316 }
9317 }
9318
9319 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9320 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9321 CmdArgs.push_back(
9322 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9323 else
9324 CmdArgs.push_back(
9325 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9326 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9327 }
9328
9329 getToolChain().addProfileRTLibs(Args, CmdArgs);
9330
9331 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9332 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9333 }
9334
9335 // Try to find Exe from a Visual Studio distribution. This first tries to find
9336 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9337 // making sure that whatever executable that's found is not a same-named exe
9338 // from clang itself to prevent clang from falling back to itself.
FindVisualStudioExecutable(const ToolChain & TC,const char * Exe,const char * ClangProgramPath)9339 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9340 const char *Exe,
9341 const char *ClangProgramPath) {
9342 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9343 std::string visualStudioBinDir;
9344 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9345 visualStudioBinDir)) {
9346 SmallString<128> FilePath(visualStudioBinDir);
9347 llvm::sys::path::append(FilePath, Exe);
9348 if (llvm::sys::fs::can_execute(FilePath.c_str()))
9349 return FilePath.str();
9350 }
9351
9352 return Exe;
9353 }
9354
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9355 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9356 const InputInfo &Output,
9357 const InputInfoList &Inputs,
9358 const ArgList &Args,
9359 const char *LinkingOutput) const {
9360 ArgStringList CmdArgs;
9361 const ToolChain &TC = getToolChain();
9362
9363 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9364 if (Output.isFilename())
9365 CmdArgs.push_back(
9366 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9367
9368 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9369 !C.getDriver().IsCLMode())
9370 CmdArgs.push_back("-defaultlib:libcmt");
9371
9372 if (!llvm::sys::Process::GetEnv("LIB")) {
9373 // If the VC environment hasn't been configured (perhaps because the user
9374 // did not run vcvarsall), try to build a consistent link environment. If
9375 // the environment variable is set however, assume the user knows what
9376 // they're doing.
9377 std::string VisualStudioDir;
9378 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9379 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9380 SmallString<128> LibDir(VisualStudioDir);
9381 llvm::sys::path::append(LibDir, "VC", "lib");
9382 switch (MSVC.getArch()) {
9383 case llvm::Triple::x86:
9384 // x86 just puts the libraries directly in lib
9385 break;
9386 case llvm::Triple::x86_64:
9387 llvm::sys::path::append(LibDir, "amd64");
9388 break;
9389 case llvm::Triple::arm:
9390 llvm::sys::path::append(LibDir, "arm");
9391 break;
9392 default:
9393 break;
9394 }
9395 CmdArgs.push_back(
9396 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
9397
9398 if (MSVC.useUniversalCRT(VisualStudioDir)) {
9399 std::string UniversalCRTLibPath;
9400 if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
9401 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9402 UniversalCRTLibPath.c_str()));
9403 }
9404 }
9405
9406 std::string WindowsSdkLibPath;
9407 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
9408 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9409 WindowsSdkLibPath.c_str()));
9410 }
9411
9412 CmdArgs.push_back("-nologo");
9413
9414 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
9415 CmdArgs.push_back("-debug");
9416
9417 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
9418 options::OPT_shared);
9419 if (DLL) {
9420 CmdArgs.push_back(Args.MakeArgString("-dll"));
9421
9422 SmallString<128> ImplibName(Output.getFilename());
9423 llvm::sys::path::replace_extension(ImplibName, "lib");
9424 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
9425 }
9426
9427 if (TC.getSanitizerArgs().needsAsanRt()) {
9428 CmdArgs.push_back(Args.MakeArgString("-debug"));
9429 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
9430 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
9431 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
9432 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9433 // Make sure the dynamic runtime thunk is not optimized out at link time
9434 // to ensure proper SEH handling.
9435 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
9436 } else if (DLL) {
9437 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
9438 } else {
9439 for (const auto &Lib : {"asan", "asan_cxx"})
9440 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9441 }
9442 }
9443
9444 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
9445
9446 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9447 options::OPT_fno_openmp, false)) {
9448 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
9449 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
9450 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9451 TC.getDriver().Dir + "/../lib"));
9452 switch (getOpenMPRuntime(getToolChain(), Args)) {
9453 case OMPRT_OMP:
9454 CmdArgs.push_back("-defaultlib:libomp.lib");
9455 break;
9456 case OMPRT_IOMP5:
9457 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
9458 break;
9459 case OMPRT_GOMP:
9460 break;
9461 case OMPRT_Unknown:
9462 // Already diagnosed.
9463 break;
9464 }
9465 }
9466
9467 // Add filenames, libraries, and other linker inputs.
9468 for (const auto &Input : Inputs) {
9469 if (Input.isFilename()) {
9470 CmdArgs.push_back(Input.getFilename());
9471 continue;
9472 }
9473
9474 const Arg &A = Input.getInputArg();
9475
9476 // Render -l options differently for the MSVC linker.
9477 if (A.getOption().matches(options::OPT_l)) {
9478 StringRef Lib = A.getValue();
9479 const char *LinkLibArg;
9480 if (Lib.endswith(".lib"))
9481 LinkLibArg = Args.MakeArgString(Lib);
9482 else
9483 LinkLibArg = Args.MakeArgString(Lib + ".lib");
9484 CmdArgs.push_back(LinkLibArg);
9485 continue;
9486 }
9487
9488 // Otherwise, this is some other kind of linker input option like -Wl, -z,
9489 // or -L. Render it, even if MSVC doesn't understand it.
9490 A.renderAsInput(Args, CmdArgs);
9491 }
9492
9493 // We need to special case some linker paths. In the case of lld, we need to
9494 // translate 'lld' into 'lld-link', and in the case of the regular msvc
9495 // linker, we need to use a special search algorithm.
9496 llvm::SmallString<128> linkPath;
9497 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
9498 if (Linker.equals_lower("lld"))
9499 Linker = "lld-link";
9500
9501 if (Linker.equals_lower("link")) {
9502 // If we're using the MSVC linker, it's not sufficient to just use link
9503 // from the program PATH, because other environments like GnuWin32 install
9504 // their own link.exe which may come first.
9505 linkPath = FindVisualStudioExecutable(TC, "link.exe",
9506 C.getDriver().getClangProgramPath());
9507 } else {
9508 linkPath = Linker;
9509 llvm::sys::path::replace_extension(linkPath, "exe");
9510 linkPath = TC.GetProgramPath(linkPath.c_str());
9511 }
9512
9513 const char *Exec = Args.MakeArgString(linkPath);
9514 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9515 }
9516
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9517 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9518 const InputInfo &Output,
9519 const InputInfoList &Inputs,
9520 const ArgList &Args,
9521 const char *LinkingOutput) const {
9522 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
9523 }
9524
GetCommand(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9525 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
9526 Compilation &C, const JobAction &JA, const InputInfo &Output,
9527 const InputInfoList &Inputs, const ArgList &Args,
9528 const char *LinkingOutput) const {
9529 ArgStringList CmdArgs;
9530 CmdArgs.push_back("/nologo");
9531 CmdArgs.push_back("/c"); // Compile only.
9532 CmdArgs.push_back("/W0"); // No warnings.
9533
9534 // The goal is to be able to invoke this tool correctly based on
9535 // any flag accepted by clang-cl.
9536
9537 // These are spelled the same way in clang and cl.exe,.
9538 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
9539
9540 // Optimization level.
9541 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
9542 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
9543 : "/Oi-");
9544 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
9545 if (A->getOption().getID() == options::OPT_O0) {
9546 CmdArgs.push_back("/Od");
9547 } else {
9548 CmdArgs.push_back("/Og");
9549
9550 StringRef OptLevel = A->getValue();
9551 if (OptLevel == "s" || OptLevel == "z")
9552 CmdArgs.push_back("/Os");
9553 else
9554 CmdArgs.push_back("/Ot");
9555
9556 CmdArgs.push_back("/Ob2");
9557 }
9558 }
9559 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
9560 options::OPT_fno_omit_frame_pointer))
9561 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
9562 ? "/Oy"
9563 : "/Oy-");
9564 if (!Args.hasArg(options::OPT_fwritable_strings))
9565 CmdArgs.push_back("/GF");
9566
9567 // Flags for which clang-cl has an alias.
9568 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
9569
9570 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
9571 /*default=*/false))
9572 CmdArgs.push_back("/GR-");
9573 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
9574 options::OPT_fno_function_sections))
9575 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
9576 ? "/Gy"
9577 : "/Gy-");
9578 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
9579 options::OPT_fno_data_sections))
9580 CmdArgs.push_back(
9581 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
9582 if (Args.hasArg(options::OPT_fsyntax_only))
9583 CmdArgs.push_back("/Zs");
9584 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
9585 options::OPT__SLASH_Z7))
9586 CmdArgs.push_back("/Z7");
9587
9588 std::vector<std::string> Includes =
9589 Args.getAllArgValues(options::OPT_include);
9590 for (const auto &Include : Includes)
9591 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
9592
9593 // Flags that can simply be passed through.
9594 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
9595 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
9596 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
9597 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
9598
9599 // The order of these flags is relevant, so pick the last one.
9600 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
9601 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
9602 A->render(Args, CmdArgs);
9603
9604 // Input filename.
9605 assert(Inputs.size() == 1);
9606 const InputInfo &II = Inputs[0];
9607 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9608 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
9609 if (II.isFilename())
9610 CmdArgs.push_back(II.getFilename());
9611 else
9612 II.getInputArg().renderAsInput(Args, CmdArgs);
9613
9614 // Output filename.
9615 assert(Output.getType() == types::TY_Object);
9616 const char *Fo =
9617 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
9618 CmdArgs.push_back(Fo);
9619
9620 const Driver &D = getToolChain().getDriver();
9621 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
9622 D.getClangProgramPath());
9623 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9624 CmdArgs, Inputs);
9625 }
9626
9627 /// MinGW Tools
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9628 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9629 const InputInfo &Output,
9630 const InputInfoList &Inputs,
9631 const ArgList &Args,
9632 const char *LinkingOutput) const {
9633 claimNoWarnArgs(Args);
9634 ArgStringList CmdArgs;
9635
9636 if (getToolChain().getArch() == llvm::Triple::x86) {
9637 CmdArgs.push_back("--32");
9638 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9639 CmdArgs.push_back("--64");
9640 }
9641
9642 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9643
9644 CmdArgs.push_back("-o");
9645 CmdArgs.push_back(Output.getFilename());
9646
9647 for (const auto &II : Inputs)
9648 CmdArgs.push_back(II.getFilename());
9649
9650 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9651 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9652
9653 if (Args.hasArg(options::OPT_gsplit_dwarf))
9654 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9655 SplitDebugName(Args, Inputs[0]));
9656 }
9657
AddLibGCC(const ArgList & Args,ArgStringList & CmdArgs) const9658 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9659 ArgStringList &CmdArgs) const {
9660 if (Args.hasArg(options::OPT_mthreads))
9661 CmdArgs.push_back("-lmingwthrd");
9662 CmdArgs.push_back("-lmingw32");
9663
9664 // Make use of compiler-rt if --rtlib option is used
9665 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
9666 if (RLT == ToolChain::RLT_Libgcc) {
9667 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
9668 Args.hasArg(options::OPT_static);
9669 bool Shared = Args.hasArg(options::OPT_shared);
9670 bool CXX = getToolChain().getDriver().CCCIsCXX();
9671
9672 if (Static || (!CXX && !Shared)) {
9673 CmdArgs.push_back("-lgcc");
9674 CmdArgs.push_back("-lgcc_eh");
9675 } else {
9676 CmdArgs.push_back("-lgcc_s");
9677 CmdArgs.push_back("-lgcc");
9678 }
9679 } else {
9680 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9681 }
9682
9683 CmdArgs.push_back("-lmoldname");
9684 CmdArgs.push_back("-lmingwex");
9685 CmdArgs.push_back("-lmsvcrt");
9686 }
9687
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9688 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9689 const InputInfo &Output,
9690 const InputInfoList &Inputs,
9691 const ArgList &Args,
9692 const char *LinkingOutput) const {
9693 const ToolChain &TC = getToolChain();
9694 const Driver &D = TC.getDriver();
9695 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9696
9697 ArgStringList CmdArgs;
9698
9699 // Silence warning for "clang -g foo.o -o foo"
9700 Args.ClaimAllArgs(options::OPT_g_Group);
9701 // and "clang -emit-llvm foo.o -o foo"
9702 Args.ClaimAllArgs(options::OPT_emit_llvm);
9703 // and for "clang -w foo.o -o foo". Other warning options are already
9704 // handled somewhere else.
9705 Args.ClaimAllArgs(options::OPT_w);
9706
9707 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9708 if (LinkerName.equals_lower("lld")) {
9709 CmdArgs.push_back("-flavor");
9710 CmdArgs.push_back("gnu");
9711 } else if (!LinkerName.equals_lower("ld")) {
9712 D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
9713 }
9714
9715 if (!D.SysRoot.empty())
9716 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9717
9718 if (Args.hasArg(options::OPT_s))
9719 CmdArgs.push_back("-s");
9720
9721 CmdArgs.push_back("-m");
9722 if (TC.getArch() == llvm::Triple::x86)
9723 CmdArgs.push_back("i386pe");
9724 if (TC.getArch() == llvm::Triple::x86_64)
9725 CmdArgs.push_back("i386pep");
9726 if (TC.getArch() == llvm::Triple::arm)
9727 CmdArgs.push_back("thumb2pe");
9728
9729 if (Args.hasArg(options::OPT_mwindows)) {
9730 CmdArgs.push_back("--subsystem");
9731 CmdArgs.push_back("windows");
9732 } else if (Args.hasArg(options::OPT_mconsole)) {
9733 CmdArgs.push_back("--subsystem");
9734 CmdArgs.push_back("console");
9735 }
9736
9737 if (Args.hasArg(options::OPT_static))
9738 CmdArgs.push_back("-Bstatic");
9739 else {
9740 if (Args.hasArg(options::OPT_mdll))
9741 CmdArgs.push_back("--dll");
9742 else if (Args.hasArg(options::OPT_shared))
9743 CmdArgs.push_back("--shared");
9744 CmdArgs.push_back("-Bdynamic");
9745 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9746 CmdArgs.push_back("-e");
9747 if (TC.getArch() == llvm::Triple::x86)
9748 CmdArgs.push_back("_DllMainCRTStartup@12");
9749 else
9750 CmdArgs.push_back("DllMainCRTStartup");
9751 CmdArgs.push_back("--enable-auto-image-base");
9752 }
9753 }
9754
9755 CmdArgs.push_back("-o");
9756 CmdArgs.push_back(Output.getFilename());
9757
9758 Args.AddAllArgs(CmdArgs, options::OPT_e);
9759 // FIXME: add -N, -n flags
9760 Args.AddLastArg(CmdArgs, options::OPT_r);
9761 Args.AddLastArg(CmdArgs, options::OPT_s);
9762 Args.AddLastArg(CmdArgs, options::OPT_t);
9763 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9764 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9765
9766 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9767 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9768 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9769 } else {
9770 if (Args.hasArg(options::OPT_municode))
9771 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9772 else
9773 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9774 }
9775 if (Args.hasArg(options::OPT_pg))
9776 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9777 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9778 }
9779
9780 Args.AddAllArgs(CmdArgs, options::OPT_L);
9781 TC.AddFilePathLibArgs(Args, CmdArgs);
9782 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9783
9784 // TODO: Add ASan stuff here
9785
9786 // TODO: Add profile stuff here
9787
9788 if (D.CCCIsCXX() &&
9789 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9790 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9791 !Args.hasArg(options::OPT_static);
9792 if (OnlyLibstdcxxStatic)
9793 CmdArgs.push_back("-Bstatic");
9794 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9795 if (OnlyLibstdcxxStatic)
9796 CmdArgs.push_back("-Bdynamic");
9797 }
9798
9799 if (!Args.hasArg(options::OPT_nostdlib)) {
9800 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9801 if (Args.hasArg(options::OPT_static))
9802 CmdArgs.push_back("--start-group");
9803
9804 if (Args.hasArg(options::OPT_fstack_protector) ||
9805 Args.hasArg(options::OPT_fstack_protector_strong) ||
9806 Args.hasArg(options::OPT_fstack_protector_all)) {
9807 CmdArgs.push_back("-lssp_nonshared");
9808 CmdArgs.push_back("-lssp");
9809 }
9810 if (Args.hasArg(options::OPT_fopenmp))
9811 CmdArgs.push_back("-lgomp");
9812
9813 AddLibGCC(Args, CmdArgs);
9814
9815 if (Args.hasArg(options::OPT_pg))
9816 CmdArgs.push_back("-lgmon");
9817
9818 if (Args.hasArg(options::OPT_pthread))
9819 CmdArgs.push_back("-lpthread");
9820
9821 // add system libraries
9822 if (Args.hasArg(options::OPT_mwindows)) {
9823 CmdArgs.push_back("-lgdi32");
9824 CmdArgs.push_back("-lcomdlg32");
9825 }
9826 CmdArgs.push_back("-ladvapi32");
9827 CmdArgs.push_back("-lshell32");
9828 CmdArgs.push_back("-luser32");
9829 CmdArgs.push_back("-lkernel32");
9830
9831 if (Args.hasArg(options::OPT_static))
9832 CmdArgs.push_back("--end-group");
9833 else if (!LinkerName.equals_lower("lld"))
9834 AddLibGCC(Args, CmdArgs);
9835 }
9836
9837 if (!Args.hasArg(options::OPT_nostartfiles)) {
9838 // Add crtfastmath.o if available and fast math is enabled.
9839 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9840
9841 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9842 }
9843 }
9844 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9845 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9846 }
9847
9848 /// XCore Tools
9849 // We pass assemble and link construction to the xcc tool.
9850
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9851 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9852 const InputInfo &Output,
9853 const InputInfoList &Inputs,
9854 const ArgList &Args,
9855 const char *LinkingOutput) const {
9856 claimNoWarnArgs(Args);
9857 ArgStringList CmdArgs;
9858
9859 CmdArgs.push_back("-o");
9860 CmdArgs.push_back(Output.getFilename());
9861
9862 CmdArgs.push_back("-c");
9863
9864 if (Args.hasArg(options::OPT_v))
9865 CmdArgs.push_back("-v");
9866
9867 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9868 if (!A->getOption().matches(options::OPT_g0))
9869 CmdArgs.push_back("-g");
9870
9871 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9872 false))
9873 CmdArgs.push_back("-fverbose-asm");
9874
9875 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9876
9877 for (const auto &II : Inputs)
9878 CmdArgs.push_back(II.getFilename());
9879
9880 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9881 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9882 }
9883
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9884 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9885 const InputInfo &Output,
9886 const InputInfoList &Inputs,
9887 const ArgList &Args,
9888 const char *LinkingOutput) const {
9889 ArgStringList CmdArgs;
9890
9891 if (Output.isFilename()) {
9892 CmdArgs.push_back("-o");
9893 CmdArgs.push_back(Output.getFilename());
9894 } else {
9895 assert(Output.isNothing() && "Invalid output.");
9896 }
9897
9898 if (Args.hasArg(options::OPT_v))
9899 CmdArgs.push_back("-v");
9900
9901 // Pass -fexceptions through to the linker if it was present.
9902 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9903 false))
9904 CmdArgs.push_back("-fexceptions");
9905
9906 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9907
9908 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9909 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9910 }
9911
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9912 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9913 const InputInfo &Output,
9914 const InputInfoList &Inputs,
9915 const ArgList &Args,
9916 const char *LinkingOutput) const {
9917 claimNoWarnArgs(Args);
9918 const auto &TC =
9919 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9920 ArgStringList CmdArgs;
9921 const char *Exec;
9922
9923 switch (TC.getArch()) {
9924 default:
9925 llvm_unreachable("unsupported architecture");
9926 case llvm::Triple::arm:
9927 case llvm::Triple::thumb:
9928 break;
9929 case llvm::Triple::x86:
9930 CmdArgs.push_back("--32");
9931 break;
9932 case llvm::Triple::x86_64:
9933 CmdArgs.push_back("--64");
9934 break;
9935 }
9936
9937 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9938
9939 CmdArgs.push_back("-o");
9940 CmdArgs.push_back(Output.getFilename());
9941
9942 for (const auto &Input : Inputs)
9943 CmdArgs.push_back(Input.getFilename());
9944
9945 const std::string Assembler = TC.GetProgramPath("as");
9946 Exec = Args.MakeArgString(Assembler);
9947
9948 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9949 }
9950
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9951 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9952 const InputInfo &Output,
9953 const InputInfoList &Inputs,
9954 const ArgList &Args,
9955 const char *LinkingOutput) const {
9956 const auto &TC =
9957 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9958 const llvm::Triple &T = TC.getTriple();
9959 const Driver &D = TC.getDriver();
9960 SmallString<128> EntryPoint;
9961 ArgStringList CmdArgs;
9962 const char *Exec;
9963
9964 // Silence warning for "clang -g foo.o -o foo"
9965 Args.ClaimAllArgs(options::OPT_g_Group);
9966 // and "clang -emit-llvm foo.o -o foo"
9967 Args.ClaimAllArgs(options::OPT_emit_llvm);
9968 // and for "clang -w foo.o -o foo"
9969 Args.ClaimAllArgs(options::OPT_w);
9970 // Other warning options are already handled somewhere else.
9971
9972 if (!D.SysRoot.empty())
9973 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9974
9975 if (Args.hasArg(options::OPT_pie))
9976 CmdArgs.push_back("-pie");
9977 if (Args.hasArg(options::OPT_rdynamic))
9978 CmdArgs.push_back("-export-dynamic");
9979 if (Args.hasArg(options::OPT_s))
9980 CmdArgs.push_back("--strip-all");
9981
9982 CmdArgs.push_back("-m");
9983 switch (TC.getArch()) {
9984 default:
9985 llvm_unreachable("unsupported architecture");
9986 case llvm::Triple::arm:
9987 case llvm::Triple::thumb:
9988 // FIXME: this is incorrect for WinCE
9989 CmdArgs.push_back("thumb2pe");
9990 break;
9991 case llvm::Triple::x86:
9992 CmdArgs.push_back("i386pe");
9993 EntryPoint.append("_");
9994 break;
9995 case llvm::Triple::x86_64:
9996 CmdArgs.push_back("i386pep");
9997 break;
9998 }
9999
10000 if (Args.hasArg(options::OPT_shared)) {
10001 switch (T.getArch()) {
10002 default:
10003 llvm_unreachable("unsupported architecture");
10004 case llvm::Triple::arm:
10005 case llvm::Triple::thumb:
10006 case llvm::Triple::x86_64:
10007 EntryPoint.append("_DllMainCRTStartup");
10008 break;
10009 case llvm::Triple::x86:
10010 EntryPoint.append("_DllMainCRTStartup@12");
10011 break;
10012 }
10013
10014 CmdArgs.push_back("-shared");
10015 CmdArgs.push_back("-Bdynamic");
10016
10017 CmdArgs.push_back("--enable-auto-image-base");
10018
10019 CmdArgs.push_back("--entry");
10020 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10021 } else {
10022 EntryPoint.append("mainCRTStartup");
10023
10024 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10025 : "-Bdynamic");
10026
10027 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10028 CmdArgs.push_back("--entry");
10029 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10030 }
10031
10032 // FIXME: handle subsystem
10033 }
10034
10035 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10036 CmdArgs.push_back("--allow-multiple-definition");
10037
10038 CmdArgs.push_back("-o");
10039 CmdArgs.push_back(Output.getFilename());
10040
10041 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10042 SmallString<261> ImpLib(Output.getFilename());
10043 llvm::sys::path::replace_extension(ImpLib, ".lib");
10044
10045 CmdArgs.push_back("--out-implib");
10046 CmdArgs.push_back(Args.MakeArgString(ImpLib));
10047 }
10048
10049 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10050 const std::string CRTPath(D.SysRoot + "/usr/lib/");
10051 const char *CRTBegin;
10052
10053 CRTBegin =
10054 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10055 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10056 }
10057
10058 Args.AddAllArgs(CmdArgs, options::OPT_L);
10059 TC.AddFilePathLibArgs(Args, CmdArgs);
10060 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10061
10062 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10063 !Args.hasArg(options::OPT_nodefaultlibs)) {
10064 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10065 !Args.hasArg(options::OPT_static);
10066 if (StaticCXX)
10067 CmdArgs.push_back("-Bstatic");
10068 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10069 if (StaticCXX)
10070 CmdArgs.push_back("-Bdynamic");
10071 }
10072
10073 if (!Args.hasArg(options::OPT_nostdlib)) {
10074 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10075 // TODO handle /MT[d] /MD[d]
10076 CmdArgs.push_back("-lmsvcrt");
10077 AddRunTimeLibs(TC, D, CmdArgs, Args);
10078 }
10079 }
10080
10081 if (TC.getSanitizerArgs().needsAsanRt()) {
10082 // TODO handle /MT[d] /MD[d]
10083 if (Args.hasArg(options::OPT_shared)) {
10084 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10085 } else {
10086 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10087 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10088 // Make sure the dynamic runtime thunk is not optimized out at link time
10089 // to ensure proper SEH handling.
10090 CmdArgs.push_back(Args.MakeArgString("--undefined"));
10091 CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10092 ? "___asan_seh_interceptor"
10093 : "__asan_seh_interceptor"));
10094 }
10095 }
10096
10097 Exec = Args.MakeArgString(TC.GetLinkerPath());
10098
10099 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10100 }
10101
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10102 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10103 const InputInfo &Output,
10104 const InputInfoList &Inputs,
10105 const ArgList &Args,
10106 const char *LinkingOutput) const {
10107 ArgStringList CmdArgs;
10108 assert(Inputs.size() == 1);
10109 const InputInfo &II = Inputs[0];
10110 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10111 II.getType() == types::TY_PP_CXX);
10112
10113 if (JA.getKind() == Action::PreprocessJobClass) {
10114 Args.ClaimAllArgs();
10115 CmdArgs.push_back("-E");
10116 } else {
10117 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10118 CmdArgs.push_back("-S");
10119 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10120 }
10121 CmdArgs.push_back("-mcpu=myriad2");
10122 CmdArgs.push_back("-DMYRIAD2");
10123
10124 // Append all -I, -iquote, -isystem paths, defines/undefines,
10125 // 'f' flags, optimize flags, and warning options.
10126 // These are spelled the same way in clang and moviCompile.
10127 Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10128 options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10129 options::OPT_f_Group, options::OPT_f_clang_Group,
10130 options::OPT_g_Group, options::OPT_M_Group,
10131 options::OPT_O_Group, options::OPT_W_Group});
10132
10133 // If we're producing a dependency file, and assembly is the final action,
10134 // then the name of the target in the dependency file should be the '.o'
10135 // file, not the '.s' file produced by this step. For example, instead of
10136 // /tmp/mumble.s: mumble.c .../someheader.h
10137 // the filename on the lefthand side should be "mumble.o"
10138 if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10139 C.getActions().size() == 1 &&
10140 C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10141 Arg *A = Args.getLastArg(options::OPT_o);
10142 if (A) {
10143 CmdArgs.push_back("-MT");
10144 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10145 }
10146 }
10147
10148 CmdArgs.push_back(II.getFilename());
10149 CmdArgs.push_back("-o");
10150 CmdArgs.push_back(Output.getFilename());
10151
10152 std::string Exec =
10153 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10154 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10155 CmdArgs, Inputs));
10156 }
10157
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10158 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10159 const InputInfo &Output,
10160 const InputInfoList &Inputs,
10161 const ArgList &Args,
10162 const char *LinkingOutput) const {
10163 ArgStringList CmdArgs;
10164
10165 assert(Inputs.size() == 1);
10166 const InputInfo &II = Inputs[0];
10167 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10168 assert(Output.getType() == types::TY_Object);
10169
10170 CmdArgs.push_back("-no6thSlotCompression");
10171 CmdArgs.push_back("-cv:myriad2"); // Chip Version
10172 CmdArgs.push_back("-noSPrefixing");
10173 CmdArgs.push_back("-a"); // Mystery option.
10174 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10175 for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10176 A->claim();
10177 CmdArgs.push_back(
10178 Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10179 }
10180 CmdArgs.push_back("-elf"); // Output format.
10181 CmdArgs.push_back(II.getFilename());
10182 CmdArgs.push_back(
10183 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10184
10185 std::string Exec =
10186 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10187 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10188 CmdArgs, Inputs));
10189 }
10190
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10191 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10192 const InputInfo &Output,
10193 const InputInfoList &Inputs,
10194 const ArgList &Args,
10195 const char *LinkingOutput) const {
10196 const auto &TC =
10197 static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10198 const llvm::Triple &T = TC.getTriple();
10199 ArgStringList CmdArgs;
10200 bool UseStartfiles =
10201 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10202 bool UseDefaultLibs =
10203 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10204
10205 if (T.getArch() == llvm::Triple::sparc)
10206 CmdArgs.push_back("-EB");
10207 else // SHAVE assumes little-endian, and sparcel is expressly so.
10208 CmdArgs.push_back("-EL");
10209
10210 // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10211 // but we never pass through a --sysroot option and various other bits.
10212 // For example, there are no sanitizers (yet) nor gold linker.
10213
10214 // Eat some arguments that may be present but have no effect.
10215 Args.ClaimAllArgs(options::OPT_g_Group);
10216 Args.ClaimAllArgs(options::OPT_w);
10217 Args.ClaimAllArgs(options::OPT_static_libgcc);
10218
10219 if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10220 CmdArgs.push_back("-s");
10221
10222 CmdArgs.push_back("-o");
10223 CmdArgs.push_back(Output.getFilename());
10224
10225 if (UseStartfiles) {
10226 // If you want startfiles, it means you want the builtin crti and crtbegin,
10227 // but not crt0. Myriad link commands provide their own crt0.o as needed.
10228 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10229 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10230 }
10231
10232 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10233 options::OPT_e, options::OPT_s, options::OPT_t,
10234 options::OPT_Z_Flag, options::OPT_r});
10235
10236 TC.AddFilePathLibArgs(Args, CmdArgs);
10237
10238 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10239
10240 if (UseDefaultLibs) {
10241 if (C.getDriver().CCCIsCXX())
10242 CmdArgs.push_back("-lstdc++");
10243 if (T.getOS() == llvm::Triple::RTEMS) {
10244 CmdArgs.push_back("--start-group");
10245 CmdArgs.push_back("-lc");
10246 // You must provide your own "-L" option to enable finding these.
10247 CmdArgs.push_back("-lrtemscpu");
10248 CmdArgs.push_back("-lrtemsbsp");
10249 CmdArgs.push_back("--end-group");
10250 } else {
10251 CmdArgs.push_back("-lc");
10252 }
10253 CmdArgs.push_back("-lgcc");
10254 }
10255 if (UseStartfiles) {
10256 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10257 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10258 }
10259
10260 std::string Exec =
10261 Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10262 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10263 CmdArgs, Inputs));
10264 }
10265
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10266 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10267 const InputInfo &Output,
10268 const InputInfoList &Inputs,
10269 const ArgList &Args,
10270 const char *LinkingOutput) const {
10271 claimNoWarnArgs(Args);
10272 ArgStringList CmdArgs;
10273
10274 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10275
10276 CmdArgs.push_back("-o");
10277 CmdArgs.push_back(Output.getFilename());
10278
10279 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10280 const InputInfo &Input = Inputs[0];
10281 assert(Input.isFilename() && "Invalid input.");
10282 CmdArgs.push_back(Input.getFilename());
10283
10284 const char *Exec =
10285 Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
10286 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10287 }
10288
AddPS4SanitizerArgs(const ToolChain & TC,ArgStringList & CmdArgs)10289 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10290 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10291 if (SanArgs.needsUbsanRt()) {
10292 CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10293 }
10294 if (SanArgs.needsAsanRt()) {
10295 CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10296 }
10297 }
10298
ConstructPS4LinkJob(const Tool & T,Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput)10299 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10300 const JobAction &JA, const InputInfo &Output,
10301 const InputInfoList &Inputs,
10302 const ArgList &Args,
10303 const char *LinkingOutput) {
10304 const toolchains::FreeBSD &ToolChain =
10305 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10306 const Driver &D = ToolChain.getDriver();
10307 ArgStringList CmdArgs;
10308
10309 // Silence warning for "clang -g foo.o -o foo"
10310 Args.ClaimAllArgs(options::OPT_g_Group);
10311 // and "clang -emit-llvm foo.o -o foo"
10312 Args.ClaimAllArgs(options::OPT_emit_llvm);
10313 // and for "clang -w foo.o -o foo". Other warning options are already
10314 // handled somewhere else.
10315 Args.ClaimAllArgs(options::OPT_w);
10316
10317 if (!D.SysRoot.empty())
10318 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10319
10320 if (Args.hasArg(options::OPT_pie))
10321 CmdArgs.push_back("-pie");
10322
10323 if (Args.hasArg(options::OPT_rdynamic))
10324 CmdArgs.push_back("-export-dynamic");
10325 if (Args.hasArg(options::OPT_shared))
10326 CmdArgs.push_back("--oformat=so");
10327
10328 if (Output.isFilename()) {
10329 CmdArgs.push_back("-o");
10330 CmdArgs.push_back(Output.getFilename());
10331 } else {
10332 assert(Output.isNothing() && "Invalid output.");
10333 }
10334
10335 AddPS4SanitizerArgs(ToolChain, CmdArgs);
10336
10337 Args.AddAllArgs(CmdArgs, options::OPT_L);
10338 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10339 Args.AddAllArgs(CmdArgs, options::OPT_e);
10340 Args.AddAllArgs(CmdArgs, options::OPT_s);
10341 Args.AddAllArgs(CmdArgs, options::OPT_t);
10342 Args.AddAllArgs(CmdArgs, options::OPT_r);
10343
10344 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10345 CmdArgs.push_back("--no-demangle");
10346
10347 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10348
10349 if (Args.hasArg(options::OPT_pthread)) {
10350 CmdArgs.push_back("-lpthread");
10351 }
10352
10353 const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10354
10355 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10356 }
10357
ConstructGoldLinkJob(const Tool & T,Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput)10358 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10359 const JobAction &JA, const InputInfo &Output,
10360 const InputInfoList &Inputs,
10361 const ArgList &Args,
10362 const char *LinkingOutput) {
10363 const toolchains::FreeBSD &ToolChain =
10364 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10365 const Driver &D = ToolChain.getDriver();
10366 ArgStringList CmdArgs;
10367
10368 // Silence warning for "clang -g foo.o -o foo"
10369 Args.ClaimAllArgs(options::OPT_g_Group);
10370 // and "clang -emit-llvm foo.o -o foo"
10371 Args.ClaimAllArgs(options::OPT_emit_llvm);
10372 // and for "clang -w foo.o -o foo". Other warning options are already
10373 // handled somewhere else.
10374 Args.ClaimAllArgs(options::OPT_w);
10375
10376 if (!D.SysRoot.empty())
10377 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10378
10379 if (Args.hasArg(options::OPT_pie))
10380 CmdArgs.push_back("-pie");
10381
10382 if (Args.hasArg(options::OPT_static)) {
10383 CmdArgs.push_back("-Bstatic");
10384 } else {
10385 if (Args.hasArg(options::OPT_rdynamic))
10386 CmdArgs.push_back("-export-dynamic");
10387 CmdArgs.push_back("--eh-frame-hdr");
10388 if (Args.hasArg(options::OPT_shared)) {
10389 CmdArgs.push_back("-Bshareable");
10390 } else {
10391 CmdArgs.push_back("-dynamic-linker");
10392 CmdArgs.push_back("/libexec/ld-elf.so.1");
10393 }
10394 CmdArgs.push_back("--enable-new-dtags");
10395 }
10396
10397 if (Output.isFilename()) {
10398 CmdArgs.push_back("-o");
10399 CmdArgs.push_back(Output.getFilename());
10400 } else {
10401 assert(Output.isNothing() && "Invalid output.");
10402 }
10403
10404 AddPS4SanitizerArgs(ToolChain, CmdArgs);
10405
10406 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10407 const char *crt1 = nullptr;
10408 if (!Args.hasArg(options::OPT_shared)) {
10409 if (Args.hasArg(options::OPT_pg))
10410 crt1 = "gcrt1.o";
10411 else if (Args.hasArg(options::OPT_pie))
10412 crt1 = "Scrt1.o";
10413 else
10414 crt1 = "crt1.o";
10415 }
10416 if (crt1)
10417 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10418
10419 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10420
10421 const char *crtbegin = nullptr;
10422 if (Args.hasArg(options::OPT_static))
10423 crtbegin = "crtbeginT.o";
10424 else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10425 crtbegin = "crtbeginS.o";
10426 else
10427 crtbegin = "crtbegin.o";
10428
10429 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10430 }
10431
10432 Args.AddAllArgs(CmdArgs, options::OPT_L);
10433 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10434 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10435 Args.AddAllArgs(CmdArgs, options::OPT_e);
10436 Args.AddAllArgs(CmdArgs, options::OPT_s);
10437 Args.AddAllArgs(CmdArgs, options::OPT_t);
10438 Args.AddAllArgs(CmdArgs, options::OPT_r);
10439
10440 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10441 CmdArgs.push_back("--no-demangle");
10442
10443 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10444
10445 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10446 // For PS4, we always want to pass libm, libstdc++ and libkernel
10447 // libraries for both C and C++ compilations.
10448 CmdArgs.push_back("-lkernel");
10449 if (D.CCCIsCXX()) {
10450 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10451 if (Args.hasArg(options::OPT_pg))
10452 CmdArgs.push_back("-lm_p");
10453 else
10454 CmdArgs.push_back("-lm");
10455 }
10456 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
10457 // the default system libraries. Just mimic this for now.
10458 if (Args.hasArg(options::OPT_pg))
10459 CmdArgs.push_back("-lgcc_p");
10460 else
10461 CmdArgs.push_back("-lcompiler_rt");
10462 if (Args.hasArg(options::OPT_static)) {
10463 CmdArgs.push_back("-lstdc++");
10464 } else if (Args.hasArg(options::OPT_pg)) {
10465 CmdArgs.push_back("-lgcc_eh_p");
10466 } else {
10467 CmdArgs.push_back("--as-needed");
10468 CmdArgs.push_back("-lstdc++");
10469 CmdArgs.push_back("--no-as-needed");
10470 }
10471
10472 if (Args.hasArg(options::OPT_pthread)) {
10473 if (Args.hasArg(options::OPT_pg))
10474 CmdArgs.push_back("-lpthread_p");
10475 else
10476 CmdArgs.push_back("-lpthread");
10477 }
10478
10479 if (Args.hasArg(options::OPT_pg)) {
10480 if (Args.hasArg(options::OPT_shared))
10481 CmdArgs.push_back("-lc");
10482 else {
10483 if (Args.hasArg(options::OPT_static)) {
10484 CmdArgs.push_back("--start-group");
10485 CmdArgs.push_back("-lc_p");
10486 CmdArgs.push_back("-lpthread_p");
10487 CmdArgs.push_back("--end-group");
10488 } else {
10489 CmdArgs.push_back("-lc_p");
10490 }
10491 }
10492 CmdArgs.push_back("-lgcc_p");
10493 } else {
10494 if (Args.hasArg(options::OPT_static)) {
10495 CmdArgs.push_back("--start-group");
10496 CmdArgs.push_back("-lc");
10497 CmdArgs.push_back("-lpthread");
10498 CmdArgs.push_back("--end-group");
10499 } else {
10500 CmdArgs.push_back("-lc");
10501 }
10502 CmdArgs.push_back("-lcompiler_rt");
10503 }
10504
10505 if (Args.hasArg(options::OPT_static)) {
10506 CmdArgs.push_back("-lstdc++");
10507 } else if (Args.hasArg(options::OPT_pg)) {
10508 CmdArgs.push_back("-lgcc_eh_p");
10509 } else {
10510 CmdArgs.push_back("--as-needed");
10511 CmdArgs.push_back("-lstdc++");
10512 CmdArgs.push_back("--no-as-needed");
10513 }
10514 }
10515
10516 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10517 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10518 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
10519 else
10520 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
10521 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10522 }
10523
10524 const char *Exec =
10525 #ifdef LLVM_ON_WIN32
10526 Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
10527 #else
10528 Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10529 #endif
10530
10531 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10532 }
10533
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10534 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
10535 const InputInfo &Output,
10536 const InputInfoList &Inputs,
10537 const ArgList &Args,
10538 const char *LinkingOutput) const {
10539 const toolchains::FreeBSD &ToolChain =
10540 static_cast<const toolchains::FreeBSD &>(getToolChain());
10541 const Driver &D = ToolChain.getDriver();
10542 bool PS4Linker;
10543 StringRef LinkerOptName;
10544 if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
10545 LinkerOptName = A->getValue();
10546 if (LinkerOptName != "ps4" && LinkerOptName != "gold")
10547 D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
10548 }
10549
10550 if (LinkerOptName == "gold")
10551 PS4Linker = false;
10552 else if (LinkerOptName == "ps4")
10553 PS4Linker = true;
10554 else
10555 PS4Linker = !Args.hasArg(options::OPT_shared);
10556
10557 if (PS4Linker)
10558 ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10559 else
10560 ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10561 }
10562