1 //===--- Tools.cpp - Tools Implementations --------------------------------===//
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/TargetParser.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
45 #ifdef LLVM_ON_UNIX
46 #include <unistd.h> // For getuid().
47 #endif
48
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
53
addAssemblerKPIC(const ArgList & Args,ArgStringList & CmdArgs)54 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
55 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
56 options::OPT_fpic, options::OPT_fno_pic,
57 options::OPT_fPIE, options::OPT_fno_PIE,
58 options::OPT_fpie, options::OPT_fno_pie);
59 if (!LastPICArg)
60 return;
61 if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
62 LastPICArg->getOption().matches(options::OPT_fpic) ||
63 LastPICArg->getOption().matches(options::OPT_fPIE) ||
64 LastPICArg->getOption().matches(options::OPT_fpie)) {
65 CmdArgs.push_back("-KPIC");
66 }
67 }
68
69 /// CheckPreprocessingOptions - Perform some validation of preprocessing
70 /// arguments that is shared with gcc.
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)71 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
73 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
74 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
75 D.Diag(diag::err_drv_argument_only_allowed_with)
76 << A->getBaseArg().getAsString(Args)
77 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
78 }
79 }
80 }
81
82 /// CheckCodeGenerationOptions - Perform some validation of code generation
83 /// arguments that is shared with gcc.
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)84 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
85 // In gcc, only ARM checks this, but it seems reasonable to check universally.
86 if (Args.hasArg(options::OPT_static))
87 if (const Arg *A =
88 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
89 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
90 << "-static";
91 }
92
93 // Add backslashes to escape spaces and other backslashes.
94 // This is used for the space-separated argument list specified with
95 // the -dwarf-debug-flags option.
EscapeSpacesAndBackslashes(const char * Arg,SmallVectorImpl<char> & Res)96 static void EscapeSpacesAndBackslashes(const char *Arg,
97 SmallVectorImpl<char> &Res) {
98 for (; *Arg; ++Arg) {
99 switch (*Arg) {
100 default:
101 break;
102 case ' ':
103 case '\\':
104 Res.push_back('\\');
105 break;
106 }
107 Res.push_back(*Arg);
108 }
109 }
110
111 // Quote target names for inclusion in GNU Make dependency files.
112 // Only the characters '$', '#', ' ', '\t' are quoted.
QuoteTarget(StringRef Target,SmallVectorImpl<char> & Res)113 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
114 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
115 switch (Target[i]) {
116 case ' ':
117 case '\t':
118 // Escape the preceding backslashes
119 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
120 Res.push_back('\\');
121
122 // Escape the space/tab
123 Res.push_back('\\');
124 break;
125 case '$':
126 Res.push_back('$');
127 break;
128 case '#':
129 Res.push_back('\\');
130 break;
131 default:
132 break;
133 }
134
135 Res.push_back(Target[i]);
136 }
137 }
138
addDirectoryList(const ArgList & Args,ArgStringList & CmdArgs,const char * ArgName,const char * EnvVar)139 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
140 const char *ArgName, const char *EnvVar) {
141 const char *DirList = ::getenv(EnvVar);
142 bool CombinedArg = false;
143
144 if (!DirList)
145 return; // Nothing to do.
146
147 StringRef Name(ArgName);
148 if (Name.equals("-I") || Name.equals("-L"))
149 CombinedArg = true;
150
151 StringRef Dirs(DirList);
152 if (Dirs.empty()) // Empty string should not add '.'.
153 return;
154
155 StringRef::size_type Delim;
156 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
157 if (Delim == 0) { // Leading colon.
158 if (CombinedArg) {
159 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
160 } else {
161 CmdArgs.push_back(ArgName);
162 CmdArgs.push_back(".");
163 }
164 } else {
165 if (CombinedArg) {
166 CmdArgs.push_back(
167 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
168 } else {
169 CmdArgs.push_back(ArgName);
170 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
171 }
172 }
173 Dirs = Dirs.substr(Delim + 1);
174 }
175
176 if (Dirs.empty()) { // Trailing colon.
177 if (CombinedArg) {
178 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
179 } else {
180 CmdArgs.push_back(ArgName);
181 CmdArgs.push_back(".");
182 }
183 } else { // Add the last path.
184 if (CombinedArg) {
185 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
186 } else {
187 CmdArgs.push_back(ArgName);
188 CmdArgs.push_back(Args.MakeArgString(Dirs));
189 }
190 }
191 }
192
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs)193 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
194 const ArgList &Args, ArgStringList &CmdArgs) {
195 const Driver &D = TC.getDriver();
196
197 // Add extra linker input arguments which are not treated as inputs
198 // (constructed via -Xarch_).
199 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
200
201 for (const auto &II : Inputs) {
202 if (!TC.HasNativeLLVMSupport()) {
203 // Don't try to pass LLVM inputs unless we have native support.
204 if (II.getType() == types::TY_LLVM_IR ||
205 II.getType() == types::TY_LTO_IR ||
206 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
207 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
208 }
209
210 // Add filenames immediately.
211 if (II.isFilename()) {
212 CmdArgs.push_back(II.getFilename());
213 continue;
214 }
215
216 // Otherwise, this is a linker input argument.
217 const Arg &A = II.getInputArg();
218
219 // Handle reserved library options.
220 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
221 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
222 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
223 TC.AddCCKextLibArgs(Args, CmdArgs);
224 else if (A.getOption().matches(options::OPT_z)) {
225 // Pass -z prefix for gcc linker compatibility.
226 A.claim();
227 A.render(Args, CmdArgs);
228 } else {
229 A.renderAsInput(Args, CmdArgs);
230 }
231 }
232
233 // LIBRARY_PATH - included following the user specified library paths.
234 // and only supported on native toolchains.
235 if (!TC.isCrossCompiling())
236 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
237 }
238
239 /// \brief Determine whether Objective-C automated reference counting is
240 /// enabled.
isObjCAutoRefCount(const ArgList & Args)241 static bool isObjCAutoRefCount(const ArgList &Args) {
242 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
243 }
244
245 /// \brief Determine whether we are linking the ObjC runtime.
isObjCRuntimeLinked(const ArgList & Args)246 static bool isObjCRuntimeLinked(const ArgList &Args) {
247 if (isObjCAutoRefCount(Args)) {
248 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
249 return true;
250 }
251 return Args.hasArg(options::OPT_fobjc_link_runtime);
252 }
253
forwardToGCC(const Option & O)254 static bool forwardToGCC(const Option &O) {
255 // Don't forward inputs from the original command line. They are added from
256 // InputInfoList.
257 return O.getKind() != Option::InputClass &&
258 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
259 }
260
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs) const261 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
262 const Driver &D, const ArgList &Args,
263 ArgStringList &CmdArgs,
264 const InputInfo &Output,
265 const InputInfoList &Inputs) const {
266 Arg *A;
267
268 CheckPreprocessingOptions(D, Args);
269
270 Args.AddLastArg(CmdArgs, options::OPT_C);
271 Args.AddLastArg(CmdArgs, options::OPT_CC);
272
273 // Handle dependency file generation.
274 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
275 (A = Args.getLastArg(options::OPT_MD)) ||
276 (A = Args.getLastArg(options::OPT_MMD))) {
277 // Determine the output location.
278 const char *DepFile;
279 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
280 DepFile = MF->getValue();
281 C.addFailureResultFile(DepFile, &JA);
282 } else if (Output.getType() == types::TY_Dependencies) {
283 DepFile = Output.getFilename();
284 } else if (A->getOption().matches(options::OPT_M) ||
285 A->getOption().matches(options::OPT_MM)) {
286 DepFile = "-";
287 } else {
288 DepFile = getDependencyFileName(Args, Inputs);
289 C.addFailureResultFile(DepFile, &JA);
290 }
291 CmdArgs.push_back("-dependency-file");
292 CmdArgs.push_back(DepFile);
293
294 // Add a default target if one wasn't specified.
295 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
296 const char *DepTarget;
297
298 // If user provided -o, that is the dependency target, except
299 // when we are only generating a dependency file.
300 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
301 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
302 DepTarget = OutputOpt->getValue();
303 } else {
304 // Otherwise derive from the base input.
305 //
306 // FIXME: This should use the computed output file location.
307 SmallString<128> P(Inputs[0].getBaseInput());
308 llvm::sys::path::replace_extension(P, "o");
309 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
310 }
311
312 CmdArgs.push_back("-MT");
313 SmallString<128> Quoted;
314 QuoteTarget(DepTarget, Quoted);
315 CmdArgs.push_back(Args.MakeArgString(Quoted));
316 }
317
318 if (A->getOption().matches(options::OPT_M) ||
319 A->getOption().matches(options::OPT_MD))
320 CmdArgs.push_back("-sys-header-deps");
321 if ((isa<PrecompileJobAction>(JA) &&
322 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
323 Args.hasArg(options::OPT_fmodule_file_deps))
324 CmdArgs.push_back("-module-file-deps");
325 }
326
327 if (Args.hasArg(options::OPT_MG)) {
328 if (!A || A->getOption().matches(options::OPT_MD) ||
329 A->getOption().matches(options::OPT_MMD))
330 D.Diag(diag::err_drv_mg_requires_m_or_mm);
331 CmdArgs.push_back("-MG");
332 }
333
334 Args.AddLastArg(CmdArgs, options::OPT_MP);
335 Args.AddLastArg(CmdArgs, options::OPT_MV);
336
337 // Convert all -MQ <target> args to -MT <quoted target>
338 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
339 A->claim();
340
341 if (A->getOption().matches(options::OPT_MQ)) {
342 CmdArgs.push_back("-MT");
343 SmallString<128> Quoted;
344 QuoteTarget(A->getValue(), Quoted);
345 CmdArgs.push_back(Args.MakeArgString(Quoted));
346
347 // -MT flag - no change
348 } else {
349 A->render(Args, CmdArgs);
350 }
351 }
352
353 // Add -i* options, and automatically translate to
354 // -include-pch/-include-pth for transparent PCH support. It's
355 // wonky, but we include looking for .gch so we can support seamless
356 // replacement into a build system already set up to be generating
357 // .gch files.
358 bool RenderedImplicitInclude = false;
359 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
360 if (A->getOption().matches(options::OPT_include)) {
361 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
362 RenderedImplicitInclude = true;
363
364 // Use PCH if the user requested it.
365 bool UsePCH = D.CCCUsePCH;
366
367 bool FoundPTH = false;
368 bool FoundPCH = false;
369 SmallString<128> P(A->getValue());
370 // We want the files to have a name like foo.h.pch. Add a dummy extension
371 // so that replace_extension does the right thing.
372 P += ".dummy";
373 if (UsePCH) {
374 llvm::sys::path::replace_extension(P, "pch");
375 if (llvm::sys::fs::exists(P))
376 FoundPCH = true;
377 }
378
379 if (!FoundPCH) {
380 llvm::sys::path::replace_extension(P, "pth");
381 if (llvm::sys::fs::exists(P))
382 FoundPTH = true;
383 }
384
385 if (!FoundPCH && !FoundPTH) {
386 llvm::sys::path::replace_extension(P, "gch");
387 if (llvm::sys::fs::exists(P)) {
388 FoundPCH = UsePCH;
389 FoundPTH = !UsePCH;
390 }
391 }
392
393 if (FoundPCH || FoundPTH) {
394 if (IsFirstImplicitInclude) {
395 A->claim();
396 if (UsePCH)
397 CmdArgs.push_back("-include-pch");
398 else
399 CmdArgs.push_back("-include-pth");
400 CmdArgs.push_back(Args.MakeArgString(P));
401 continue;
402 } else {
403 // Ignore the PCH if not first on command line and emit warning.
404 D.Diag(diag::warn_drv_pch_not_first_include) << P
405 << A->getAsString(Args);
406 }
407 }
408 }
409
410 // Not translated, render as usual.
411 A->claim();
412 A->render(Args, CmdArgs);
413 }
414
415 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
416 Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
417 options::OPT_index_header_map);
418
419 // Add -Wp, and -Xassembler if using the preprocessor.
420
421 // FIXME: There is a very unfortunate problem here, some troubled
422 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
423 // really support that we would have to parse and then translate
424 // those options. :(
425 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
426 options::OPT_Xpreprocessor);
427
428 // -I- is a deprecated GCC feature, reject it.
429 if (Arg *A = Args.getLastArg(options::OPT_I_))
430 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
431
432 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
433 // -isysroot to the CC1 invocation.
434 StringRef sysroot = C.getSysRoot();
435 if (sysroot != "") {
436 if (!Args.hasArg(options::OPT_isysroot)) {
437 CmdArgs.push_back("-isysroot");
438 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
439 }
440 }
441
442 // Parse additional include paths from environment variables.
443 // FIXME: We should probably sink the logic for handling these from the
444 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
445 // CPATH - included following the user specified includes (but prior to
446 // builtin and standard includes).
447 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
448 // C_INCLUDE_PATH - system includes enabled when compiling C.
449 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
450 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
451 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
452 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
453 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
454 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
455 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
456
457 // Add C++ include arguments, if needed.
458 if (types::isCXX(Inputs[0].getType()))
459 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
460
461 // Add system include arguments.
462 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
463 }
464
465 // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)466 static bool isSignedCharDefault(const llvm::Triple &Triple) {
467 switch (Triple.getArch()) {
468 default:
469 return true;
470
471 case llvm::Triple::aarch64:
472 case llvm::Triple::aarch64_be:
473 case llvm::Triple::arm:
474 case llvm::Triple::armeb:
475 case llvm::Triple::thumb:
476 case llvm::Triple::thumbeb:
477 if (Triple.isOSDarwin() || Triple.isOSWindows())
478 return true;
479 return false;
480
481 case llvm::Triple::ppc:
482 case llvm::Triple::ppc64:
483 if (Triple.isOSDarwin())
484 return true;
485 return false;
486
487 case llvm::Triple::hexagon:
488 case llvm::Triple::ppc64le:
489 case llvm::Triple::systemz:
490 case llvm::Triple::xcore:
491 return false;
492 }
493 }
494
isNoCommonDefault(const llvm::Triple & Triple)495 static bool isNoCommonDefault(const llvm::Triple &Triple) {
496 switch (Triple.getArch()) {
497 default:
498 return false;
499
500 case llvm::Triple::xcore:
501 return true;
502 }
503 }
504
505 // ARM tools start.
506
507 // Get SubArch (vN).
getARMSubArchVersionNumber(const llvm::Triple & Triple)508 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
509 llvm::StringRef Arch = Triple.getArchName();
510 return llvm::ARMTargetParser::parseArchVersion(Arch);
511 }
512
513 // True if M-profile.
isARMMProfile(const llvm::Triple & Triple)514 static bool isARMMProfile(const llvm::Triple &Triple) {
515 llvm::StringRef Arch = Triple.getArchName();
516 unsigned Profile = llvm::ARMTargetParser::parseArchProfile(Arch);
517 return Profile == llvm::ARM::PK_M;
518 }
519
520 // Get Arch/CPU from args.
getARMArchCPUFromArgs(const ArgList & Args,llvm::StringRef & Arch,llvm::StringRef & CPU,bool FromAs=false)521 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
522 llvm::StringRef &CPU, bool FromAs = false) {
523 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
524 CPU = A->getValue();
525 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
526 Arch = A->getValue();
527 if (!FromAs)
528 return;
529
530 for (const Arg *A :
531 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
532 StringRef Value = A->getValue();
533 if (Value.startswith("-mcpu="))
534 CPU = Value.substr(6);
535 if (Value.startswith("-march="))
536 Arch = Value.substr(7);
537 }
538 }
539
540 // Handle -mhwdiv=.
541 // FIXME: Use ARMTargetParser.
getARMHWDivFeatures(const Driver & D,const Arg * A,const ArgList & Args,StringRef HWDiv,std::vector<const char * > & Features)542 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
543 const ArgList &Args, StringRef HWDiv,
544 std::vector<const char *> &Features) {
545 if (HWDiv == "arm") {
546 Features.push_back("+hwdiv-arm");
547 Features.push_back("-hwdiv");
548 } else if (HWDiv == "thumb") {
549 Features.push_back("-hwdiv-arm");
550 Features.push_back("+hwdiv");
551 } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
552 Features.push_back("+hwdiv-arm");
553 Features.push_back("+hwdiv");
554 } else if (HWDiv == "none") {
555 Features.push_back("-hwdiv-arm");
556 Features.push_back("-hwdiv");
557 } else
558 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
559 }
560
561 // Handle -mfpu=.
getARMFPUFeatures(const Driver & D,const Arg * A,const ArgList & Args,StringRef FPU,std::vector<const char * > & Features)562 static void getARMFPUFeatures(const Driver &D, const Arg *A,
563 const ArgList &Args, StringRef FPU,
564 std::vector<const char *> &Features) {
565 unsigned FPUID = llvm::ARMTargetParser::parseFPU(FPU);
566 if (!llvm::ARMTargetParser::getFPUFeatures(FPUID, Features))
567 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
568 }
569
570 // Check if -march is valid by checking if it can be canonicalised and parsed.
571 // getARMArch is used here instead of just checking the -march value in order
572 // to handle -march=native correctly.
checkARMArchName(const Driver & D,const Arg * A,const ArgList & Args,llvm::StringRef ArchName,const llvm::Triple & Triple)573 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
574 llvm::StringRef ArchName,
575 const llvm::Triple &Triple) {
576 std::string MArch = arm::getARMArch(ArchName, Triple);
577 if (llvm::ARMTargetParser::parseArch(MArch) == llvm::ARM::AK_INVALID)
578 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
579 }
580
581 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
checkARMCPUName(const Driver & D,const Arg * A,const ArgList & Args,llvm::StringRef CPUName,llvm::StringRef ArchName,const llvm::Triple & Triple)582 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
583 llvm::StringRef CPUName, llvm::StringRef ArchName,
584 const llvm::Triple &Triple) {
585 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
586 std::string Arch = arm::getARMArch(ArchName, Triple);
587 if (strcmp(arm::getLLVMArchSuffixForARM(CPU, Arch), "") == 0)
588 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
589 }
590
591 // Select the float ABI as determined by -msoft-float, -mhard-float, and
592 // -mfloat-abi=.
getARMFloatABI(const Driver & D,const ArgList & Args,const llvm::Triple & Triple)593 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
594 const llvm::Triple &Triple) {
595 StringRef FloatABI;
596 if (Arg *A =
597 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
598 options::OPT_mfloat_abi_EQ)) {
599 if (A->getOption().matches(options::OPT_msoft_float))
600 FloatABI = "soft";
601 else if (A->getOption().matches(options::OPT_mhard_float))
602 FloatABI = "hard";
603 else {
604 FloatABI = A->getValue();
605 if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
606 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
607 FloatABI = "soft";
608 }
609 }
610 }
611
612 // If unspecified, choose the default based on the platform.
613 if (FloatABI.empty()) {
614 switch (Triple.getOS()) {
615 case llvm::Triple::Darwin:
616 case llvm::Triple::MacOSX:
617 case llvm::Triple::IOS: {
618 // Darwin defaults to "softfp" for v6 and v7.
619 //
620 if (getARMSubArchVersionNumber(Triple) == 6 ||
621 getARMSubArchVersionNumber(Triple) == 7)
622 FloatABI = "softfp";
623 else
624 FloatABI = "soft";
625 break;
626 }
627
628 // FIXME: this is invalid for WindowsCE
629 case llvm::Triple::Win32:
630 FloatABI = "hard";
631 break;
632
633 case llvm::Triple::FreeBSD:
634 switch (Triple.getEnvironment()) {
635 case llvm::Triple::GNUEABIHF:
636 FloatABI = "hard";
637 break;
638 default:
639 // FreeBSD defaults to soft float
640 FloatABI = "soft";
641 break;
642 }
643 break;
644
645 default:
646 switch (Triple.getEnvironment()) {
647 case llvm::Triple::GNUEABIHF:
648 FloatABI = "hard";
649 break;
650 case llvm::Triple::GNUEABI:
651 FloatABI = "softfp";
652 break;
653 case llvm::Triple::EABIHF:
654 FloatABI = "hard";
655 break;
656 case llvm::Triple::EABI:
657 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
658 FloatABI = "softfp";
659 break;
660 case llvm::Triple::Android: {
661 if (getARMSubArchVersionNumber(Triple) == 7)
662 FloatABI = "softfp";
663 else
664 FloatABI = "soft";
665 break;
666 }
667 default:
668 // Assume "soft", but warn the user we are guessing.
669 FloatABI = "soft";
670 if (Triple.getOS() != llvm::Triple::UnknownOS ||
671 !Triple.isOSBinFormatMachO())
672 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
673 break;
674 }
675 }
676 }
677
678 return FloatABI;
679 }
680
getARMTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features,bool ForAS)681 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
682 const ArgList &Args,
683 std::vector<const char *> &Features,
684 bool ForAS) {
685 bool KernelOrKext =
686 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
687 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
688 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
689 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
690
691 if (!ForAS) {
692 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
693 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
694 // stripped out by the ARM target. We should probably pass this a new
695 // -target-option, which is handled by the -cc1/-cc1as invocation.
696 //
697 // FIXME2: For consistency, it would be ideal if we set up the target
698 // machine state the same when using the frontend or the assembler. We don't
699 // currently do that for the assembler, we pass the options directly to the
700 // backend and never even instantiate the frontend TargetInfo. If we did,
701 // and used its handleTargetFeatures hook, then we could ensure the
702 // assembler and the frontend behave the same.
703
704 // Use software floating point operations?
705 if (FloatABI == "soft")
706 Features.push_back("+soft-float");
707
708 // Use software floating point argument passing?
709 if (FloatABI != "hard")
710 Features.push_back("+soft-float-abi");
711 } else {
712 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
713 // to the assembler correctly.
714 for (const Arg *A :
715 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
716 StringRef Value = A->getValue();
717 if (Value.startswith("-mfpu=")) {
718 WaFPU = A;
719 } else if (Value.startswith("-mcpu=")) {
720 WaCPU = A;
721 } else if (Value.startswith("-mhwdiv=")) {
722 WaHDiv = A;
723 } else if (Value.startswith("-march=")) {
724 WaArch = A;
725 }
726 }
727 }
728
729 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
730 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
731 if (WaFPU) {
732 if (FPUArg)
733 D.Diag(clang::diag::warn_drv_unused_argument)
734 << FPUArg->getAsString(Args);
735 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
736 Features);
737 } else if (FPUArg) {
738 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
739 }
740
741 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
742 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
743 if (WaHDiv) {
744 if (HDivArg)
745 D.Diag(clang::diag::warn_drv_unused_argument)
746 << HDivArg->getAsString(Args);
747 getARMHWDivFeatures(D, WaHDiv, Args,
748 StringRef(WaHDiv->getValue()).substr(8), Features);
749 } else if (HDivArg)
750 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
751
752 // Check -march. ClangAs gives preference to -Wa,-march=.
753 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
754 StringRef ArchName;
755 if (WaArch) {
756 if (ArchArg)
757 D.Diag(clang::diag::warn_drv_unused_argument)
758 << ArchArg->getAsString(Args);
759 ArchName = StringRef(WaArch->getValue()).substr(7);
760 checkARMArchName(D, WaArch, Args, ArchName, Triple);
761 // FIXME: Set Arch.
762 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
763 } else if (ArchArg) {
764 ArchName = ArchArg->getValue();
765 checkARMArchName(D, ArchArg, Args, ArchName, Triple);
766 }
767
768 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
769 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
770 StringRef CPUName;
771 if (WaCPU) {
772 if (CPUArg)
773 D.Diag(clang::diag::warn_drv_unused_argument)
774 << CPUArg->getAsString(Args);
775 CPUName = StringRef(WaCPU->getValue()).substr(6);
776 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Triple);
777 } else if (CPUArg) {
778 CPUName = CPUArg->getValue();
779 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Triple);
780 }
781
782 // Setting -msoft-float effectively disables NEON because of the GCC
783 // implementation, although the same isn't true of VFP or VFP3.
784 if (FloatABI == "soft") {
785 Features.push_back("-neon");
786 // Also need to explicitly disable features which imply NEON.
787 Features.push_back("-crypto");
788 }
789
790 // En/disable crc code generation.
791 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
792 if (A->getOption().matches(options::OPT_mcrc))
793 Features.push_back("+crc");
794 else
795 Features.push_back("-crc");
796 }
797
798 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
799 Features.insert(Features.begin(), "+v8.1a");
800 }
801
802 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
803 // neither options are specified, see if we are compiling for kernel/kext and
804 // decide whether to pass "+long-calls" based on the OS and its version.
805 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
806 options::OPT_mno_long_calls)) {
807 if (A->getOption().matches(options::OPT_mlong_calls))
808 Features.push_back("+long-calls");
809 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6))) {
810 Features.push_back("+long-calls");
811 }
812 }
813
AddARMTargetArgs(const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const814 void Clang::AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs,
815 bool KernelOrKext) const {
816 const Driver &D = getToolChain().getDriver();
817 // Get the effective triple, which takes into account the deployment target.
818 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
819 llvm::Triple Triple(TripleStr);
820
821 // Select the ABI to use.
822 //
823 // FIXME: Support -meabi.
824 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
825 const char *ABIName = nullptr;
826 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
827 ABIName = A->getValue();
828 } else if (Triple.isOSBinFormatMachO()) {
829 // The backend is hardwired to assume AAPCS for M-class processors, ensure
830 // the frontend matches that.
831 if (Triple.getEnvironment() == llvm::Triple::EABI ||
832 Triple.getOS() == llvm::Triple::UnknownOS || isARMMProfile(Triple)) {
833 ABIName = "aapcs";
834 } else {
835 ABIName = "apcs-gnu";
836 }
837 } else if (Triple.isOSWindows()) {
838 // FIXME: this is invalid for WindowsCE
839 ABIName = "aapcs";
840 } else {
841 // Select the default based on the platform.
842 switch (Triple.getEnvironment()) {
843 case llvm::Triple::Android:
844 case llvm::Triple::GNUEABI:
845 case llvm::Triple::GNUEABIHF:
846 ABIName = "aapcs-linux";
847 break;
848 case llvm::Triple::EABIHF:
849 case llvm::Triple::EABI:
850 ABIName = "aapcs";
851 break;
852 default:
853 if (Triple.getOS() == llvm::Triple::NetBSD)
854 ABIName = "apcs-gnu";
855 else
856 ABIName = "aapcs";
857 break;
858 }
859 }
860 CmdArgs.push_back("-target-abi");
861 CmdArgs.push_back(ABIName);
862
863 // Determine floating point ABI from the options & target defaults.
864 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
865 if (FloatABI == "soft") {
866 // Floating point operations and argument passing are soft.
867 //
868 // FIXME: This changes CPP defines, we need -target-soft-float.
869 CmdArgs.push_back("-msoft-float");
870 CmdArgs.push_back("-mfloat-abi");
871 CmdArgs.push_back("soft");
872 } else if (FloatABI == "softfp") {
873 // Floating point operations are hard, but argument passing is soft.
874 CmdArgs.push_back("-mfloat-abi");
875 CmdArgs.push_back("soft");
876 } else {
877 // Floating point operations and argument passing are hard.
878 assert(FloatABI == "hard" && "Invalid float abi!");
879 CmdArgs.push_back("-mfloat-abi");
880 CmdArgs.push_back("hard");
881 }
882
883 // Kernel code has more strict alignment requirements.
884 if (KernelOrKext) {
885 CmdArgs.push_back("-backend-option");
886 CmdArgs.push_back("-arm-strict-align");
887
888 // The kext linker doesn't know how to deal with movw/movt.
889 CmdArgs.push_back("-backend-option");
890 CmdArgs.push_back("-arm-use-movt=0");
891 }
892
893 // -mkernel implies -mstrict-align; don't add the redundant option.
894 if (!KernelOrKext) {
895 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
896 options::OPT_munaligned_access)) {
897 CmdArgs.push_back("-backend-option");
898 if (A->getOption().matches(options::OPT_mno_unaligned_access))
899 CmdArgs.push_back("-arm-strict-align");
900 else {
901 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
902 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
903 CmdArgs.push_back("-arm-no-strict-align");
904 }
905 }
906 }
907
908 // Forward the -mglobal-merge option for explicit control over the pass.
909 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
910 options::OPT_mno_global_merge)) {
911 CmdArgs.push_back("-backend-option");
912 if (A->getOption().matches(options::OPT_mno_global_merge))
913 CmdArgs.push_back("-arm-global-merge=false");
914 else
915 CmdArgs.push_back("-arm-global-merge=true");
916 }
917
918 if (!Args.hasFlag(options::OPT_mimplicit_float,
919 options::OPT_mno_implicit_float, true))
920 CmdArgs.push_back("-no-implicit-float");
921
922 // llvm does not support reserving registers in general. There is support
923 // for reserving r9 on ARM though (defined as a platform-specific register
924 // in ARM EABI).
925 if (Args.hasArg(options::OPT_ffixed_r9)) {
926 CmdArgs.push_back("-backend-option");
927 CmdArgs.push_back("-arm-reserve-r9");
928 }
929 }
930 // ARM tools end.
931
932 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
933 /// targeting.
getAArch64TargetCPU(const ArgList & Args)934 static std::string getAArch64TargetCPU(const ArgList &Args) {
935 Arg *A;
936 std::string CPU;
937 // If we have -mtune or -mcpu, use that.
938 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
939 CPU = A->getValue();
940 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
941 StringRef Mcpu = A->getValue();
942 CPU = Mcpu.split("+").first.lower();
943 }
944
945 // Handle CPU name is 'native'.
946 if (CPU == "native")
947 return llvm::sys::getHostCPUName();
948 else if (CPU.size())
949 return CPU;
950
951 // Make sure we pick "cyclone" if -arch is used.
952 // FIXME: Should this be picked by checking the target triple instead?
953 if (Args.getLastArg(options::OPT_arch))
954 return "cyclone";
955
956 return "generic";
957 }
958
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const959 void Clang::AddAArch64TargetArgs(const ArgList &Args,
960 ArgStringList &CmdArgs) const {
961 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
962 llvm::Triple Triple(TripleStr);
963
964 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
965 Args.hasArg(options::OPT_mkernel) ||
966 Args.hasArg(options::OPT_fapple_kext))
967 CmdArgs.push_back("-disable-red-zone");
968
969 if (!Args.hasFlag(options::OPT_mimplicit_float,
970 options::OPT_mno_implicit_float, true))
971 CmdArgs.push_back("-no-implicit-float");
972
973 const char *ABIName = nullptr;
974 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
975 ABIName = A->getValue();
976 else if (Triple.isOSDarwin())
977 ABIName = "darwinpcs";
978 else
979 ABIName = "aapcs";
980
981 CmdArgs.push_back("-target-abi");
982 CmdArgs.push_back(ABIName);
983
984 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
985 options::OPT_munaligned_access)) {
986 CmdArgs.push_back("-backend-option");
987 if (A->getOption().matches(options::OPT_mno_unaligned_access))
988 CmdArgs.push_back("-aarch64-strict-align");
989 else
990 CmdArgs.push_back("-aarch64-no-strict-align");
991 }
992
993 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
994 options::OPT_mno_fix_cortex_a53_835769)) {
995 CmdArgs.push_back("-backend-option");
996 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
997 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
998 else
999 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1000 } else if (Triple.getEnvironment() == llvm::Triple::Android) {
1001 // Enabled A53 errata (835769) workaround by default on android
1002 CmdArgs.push_back("-backend-option");
1003 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1004 }
1005
1006 // Forward the -mglobal-merge option for explicit control over the pass.
1007 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1008 options::OPT_mno_global_merge)) {
1009 CmdArgs.push_back("-backend-option");
1010 if (A->getOption().matches(options::OPT_mno_global_merge))
1011 CmdArgs.push_back("-aarch64-global-merge=false");
1012 else
1013 CmdArgs.push_back("-aarch64-global-merge=true");
1014 }
1015
1016 if (Args.hasArg(options::OPT_ffixed_x18)) {
1017 CmdArgs.push_back("-backend-option");
1018 CmdArgs.push_back("-aarch64-reserve-x18");
1019 }
1020 }
1021
1022 // Get CPU and ABI names. They are not independent
1023 // so we have to calculate them together.
getMipsCPUAndABI(const ArgList & Args,const llvm::Triple & Triple,StringRef & CPUName,StringRef & ABIName)1024 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1025 StringRef &CPUName, StringRef &ABIName) {
1026 const char *DefMips32CPU = "mips32r2";
1027 const char *DefMips64CPU = "mips64r2";
1028
1029 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1030 // default for mips64(el)?-img-linux-gnu.
1031 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1032 Triple.getEnvironment() == llvm::Triple::GNU) {
1033 DefMips32CPU = "mips32r6";
1034 DefMips64CPU = "mips64r6";
1035 }
1036
1037 // MIPS3 is the default for mips64*-unknown-openbsd.
1038 if (Triple.getOS() == llvm::Triple::OpenBSD)
1039 DefMips64CPU = "mips3";
1040
1041 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1042 CPUName = A->getValue();
1043
1044 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1045 ABIName = A->getValue();
1046 // Convert a GNU style Mips ABI name to the name
1047 // accepted by LLVM Mips backend.
1048 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1049 .Case("32", "o32")
1050 .Case("64", "n64")
1051 .Default(ABIName);
1052 }
1053
1054 // Setup default CPU and ABI names.
1055 if (CPUName.empty() && ABIName.empty()) {
1056 switch (Triple.getArch()) {
1057 default:
1058 llvm_unreachable("Unexpected triple arch name");
1059 case llvm::Triple::mips:
1060 case llvm::Triple::mipsel:
1061 CPUName = DefMips32CPU;
1062 break;
1063 case llvm::Triple::mips64:
1064 case llvm::Triple::mips64el:
1065 CPUName = DefMips64CPU;
1066 break;
1067 }
1068 }
1069
1070 if (ABIName.empty()) {
1071 // Deduce ABI name from the target triple.
1072 if (Triple.getArch() == llvm::Triple::mips ||
1073 Triple.getArch() == llvm::Triple::mipsel)
1074 ABIName = "o32";
1075 else
1076 ABIName = "n64";
1077 }
1078
1079 if (CPUName.empty()) {
1080 // Deduce CPU name from ABI name.
1081 CPUName = llvm::StringSwitch<const char *>(ABIName)
1082 .Cases("o32", "eabi", DefMips32CPU)
1083 .Cases("n32", "n64", DefMips64CPU)
1084 .Default("");
1085 }
1086
1087 // FIXME: Warn on inconsistent use of -march and -mabi.
1088 }
1089
1090 // Convert ABI name to the GNU tools acceptable variant.
getGnuCompatibleMipsABIName(StringRef ABI)1091 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1092 return llvm::StringSwitch<llvm::StringRef>(ABI)
1093 .Case("o32", "32")
1094 .Case("n64", "64")
1095 .Default(ABI);
1096 }
1097
1098 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1099 // and -mfloat-abi=.
getMipsFloatABI(const Driver & D,const ArgList & Args)1100 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
1101 StringRef FloatABI;
1102 if (Arg *A =
1103 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1104 options::OPT_mfloat_abi_EQ)) {
1105 if (A->getOption().matches(options::OPT_msoft_float))
1106 FloatABI = "soft";
1107 else if (A->getOption().matches(options::OPT_mhard_float))
1108 FloatABI = "hard";
1109 else {
1110 FloatABI = A->getValue();
1111 if (FloatABI != "soft" && FloatABI != "hard") {
1112 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1113 FloatABI = "hard";
1114 }
1115 }
1116 }
1117
1118 // If unspecified, choose the default based on the platform.
1119 if (FloatABI.empty()) {
1120 // Assume "hard", because it's a default value used by gcc.
1121 // When we start to recognize specific target MIPS processors,
1122 // we will be able to select the default more correctly.
1123 FloatABI = "hard";
1124 }
1125
1126 return FloatABI;
1127 }
1128
AddTargetFeature(const ArgList & Args,std::vector<const char * > & Features,OptSpecifier OnOpt,OptSpecifier OffOpt,StringRef FeatureName)1129 static void AddTargetFeature(const ArgList &Args,
1130 std::vector<const char *> &Features,
1131 OptSpecifier OnOpt, OptSpecifier OffOpt,
1132 StringRef FeatureName) {
1133 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1134 if (A->getOption().matches(OnOpt))
1135 Features.push_back(Args.MakeArgString("+" + FeatureName));
1136 else
1137 Features.push_back(Args.MakeArgString("-" + FeatureName));
1138 }
1139 }
1140
getMIPSTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)1141 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1142 const ArgList &Args,
1143 std::vector<const char *> &Features) {
1144 StringRef CPUName;
1145 StringRef ABIName;
1146 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1147 ABIName = getGnuCompatibleMipsABIName(ABIName);
1148
1149 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1150 options::OPT_mabicalls, "noabicalls");
1151
1152 StringRef FloatABI = getMipsFloatABI(D, Args);
1153 if (FloatABI == "soft") {
1154 // FIXME: Note, this is a hack. We need to pass the selected float
1155 // mode to the MipsTargetInfoBase to define appropriate macros there.
1156 // Now it is the only method.
1157 Features.push_back("+soft-float");
1158 }
1159
1160 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1161 StringRef Val = StringRef(A->getValue());
1162 if (Val == "2008") {
1163 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1164 Features.push_back("+nan2008");
1165 else {
1166 Features.push_back("-nan2008");
1167 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1168 }
1169 } else if (Val == "legacy") {
1170 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1171 Features.push_back("-nan2008");
1172 else {
1173 Features.push_back("+nan2008");
1174 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1175 }
1176 } else
1177 D.Diag(diag::err_drv_unsupported_option_argument)
1178 << A->getOption().getName() << Val;
1179 }
1180
1181 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1182 options::OPT_mdouble_float, "single-float");
1183 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1184 "mips16");
1185 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1186 options::OPT_mno_micromips, "micromips");
1187 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1188 "dsp");
1189 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1190 "dspr2");
1191 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1192 "msa");
1193
1194 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1195 // pass -mfpxx
1196 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1197 options::OPT_mfp64)) {
1198 if (A->getOption().matches(options::OPT_mfp32))
1199 Features.push_back(Args.MakeArgString("-fp64"));
1200 else if (A->getOption().matches(options::OPT_mfpxx)) {
1201 Features.push_back(Args.MakeArgString("+fpxx"));
1202 Features.push_back(Args.MakeArgString("+nooddspreg"));
1203 } else
1204 Features.push_back(Args.MakeArgString("+fp64"));
1205 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1206 Features.push_back(Args.MakeArgString("+fpxx"));
1207 Features.push_back(Args.MakeArgString("+nooddspreg"));
1208 }
1209
1210 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1211 options::OPT_modd_spreg, "nooddspreg");
1212 }
1213
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1214 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1215 ArgStringList &CmdArgs) const {
1216 const Driver &D = getToolChain().getDriver();
1217 StringRef CPUName;
1218 StringRef ABIName;
1219 const llvm::Triple &Triple = getToolChain().getTriple();
1220 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1221
1222 CmdArgs.push_back("-target-abi");
1223 CmdArgs.push_back(ABIName.data());
1224
1225 StringRef FloatABI = getMipsFloatABI(D, Args);
1226
1227 if (FloatABI == "soft") {
1228 // Floating point operations and argument passing are soft.
1229 CmdArgs.push_back("-msoft-float");
1230 CmdArgs.push_back("-mfloat-abi");
1231 CmdArgs.push_back("soft");
1232 } else {
1233 // Floating point operations and argument passing are hard.
1234 assert(FloatABI == "hard" && "Invalid float abi!");
1235 CmdArgs.push_back("-mfloat-abi");
1236 CmdArgs.push_back("hard");
1237 }
1238
1239 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1240 if (A->getOption().matches(options::OPT_mxgot)) {
1241 CmdArgs.push_back("-mllvm");
1242 CmdArgs.push_back("-mxgot");
1243 }
1244 }
1245
1246 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1247 options::OPT_mno_ldc1_sdc1)) {
1248 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1249 CmdArgs.push_back("-mllvm");
1250 CmdArgs.push_back("-mno-ldc1-sdc1");
1251 }
1252 }
1253
1254 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1255 options::OPT_mno_check_zero_division)) {
1256 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1257 CmdArgs.push_back("-mllvm");
1258 CmdArgs.push_back("-mno-check-zero-division");
1259 }
1260 }
1261
1262 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1263 StringRef v = A->getValue();
1264 CmdArgs.push_back("-mllvm");
1265 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1266 A->claim();
1267 }
1268 }
1269
1270 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
getPPCTargetCPU(const ArgList & Args)1271 static std::string getPPCTargetCPU(const ArgList &Args) {
1272 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1273 StringRef CPUName = A->getValue();
1274
1275 if (CPUName == "native") {
1276 std::string CPU = llvm::sys::getHostCPUName();
1277 if (!CPU.empty() && CPU != "generic")
1278 return CPU;
1279 else
1280 return "";
1281 }
1282
1283 return llvm::StringSwitch<const char *>(CPUName)
1284 .Case("common", "generic")
1285 .Case("440", "440")
1286 .Case("440fp", "440")
1287 .Case("450", "450")
1288 .Case("601", "601")
1289 .Case("602", "602")
1290 .Case("603", "603")
1291 .Case("603e", "603e")
1292 .Case("603ev", "603ev")
1293 .Case("604", "604")
1294 .Case("604e", "604e")
1295 .Case("620", "620")
1296 .Case("630", "pwr3")
1297 .Case("G3", "g3")
1298 .Case("7400", "7400")
1299 .Case("G4", "g4")
1300 .Case("7450", "7450")
1301 .Case("G4+", "g4+")
1302 .Case("750", "750")
1303 .Case("970", "970")
1304 .Case("G5", "g5")
1305 .Case("a2", "a2")
1306 .Case("a2q", "a2q")
1307 .Case("e500mc", "e500mc")
1308 .Case("e5500", "e5500")
1309 .Case("power3", "pwr3")
1310 .Case("power4", "pwr4")
1311 .Case("power5", "pwr5")
1312 .Case("power5x", "pwr5x")
1313 .Case("power6", "pwr6")
1314 .Case("power6x", "pwr6x")
1315 .Case("power7", "pwr7")
1316 .Case("power8", "pwr8")
1317 .Case("pwr3", "pwr3")
1318 .Case("pwr4", "pwr4")
1319 .Case("pwr5", "pwr5")
1320 .Case("pwr5x", "pwr5x")
1321 .Case("pwr6", "pwr6")
1322 .Case("pwr6x", "pwr6x")
1323 .Case("pwr7", "pwr7")
1324 .Case("pwr8", "pwr8")
1325 .Case("powerpc", "ppc")
1326 .Case("powerpc64", "ppc64")
1327 .Case("powerpc64le", "ppc64le")
1328 .Default("");
1329 }
1330
1331 return "";
1332 }
1333
getPPCTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)1334 static void getPPCTargetFeatures(const ArgList &Args,
1335 std::vector<const char *> &Features) {
1336 for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
1337 StringRef Name = A->getOption().getName();
1338 A->claim();
1339
1340 // Skip over "-m".
1341 assert(Name.startswith("m") && "Invalid feature name.");
1342 Name = Name.substr(1);
1343
1344 bool IsNegative = Name.startswith("no-");
1345 if (IsNegative)
1346 Name = Name.substr(3);
1347
1348 // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1349 // pass the correct option to the backend while calling the frontend
1350 // option the same.
1351 // TODO: Change the LLVM backend option maybe?
1352 if (Name == "mfcrf")
1353 Name = "mfocrf";
1354
1355 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1356 }
1357
1358 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1359 AddTargetFeature(Args, Features, options::OPT_faltivec,
1360 options::OPT_fno_altivec, "altivec");
1361 }
1362
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1363 void Clang::AddPPCTargetArgs(const ArgList &Args,
1364 ArgStringList &CmdArgs) const {
1365 // Select the ABI to use.
1366 const char *ABIName = nullptr;
1367 if (getToolChain().getTriple().isOSLinux())
1368 switch (getToolChain().getArch()) {
1369 case llvm::Triple::ppc64: {
1370 // When targeting a processor that supports QPX, or if QPX is
1371 // specifically enabled, default to using the ABI that supports QPX (so
1372 // long as it is not specifically disabled).
1373 bool HasQPX = false;
1374 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1375 HasQPX = A->getValue() == StringRef("a2q");
1376 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1377 if (HasQPX) {
1378 ABIName = "elfv1-qpx";
1379 break;
1380 }
1381
1382 ABIName = "elfv1";
1383 break;
1384 }
1385 case llvm::Triple::ppc64le:
1386 ABIName = "elfv2";
1387 break;
1388 default:
1389 break;
1390 }
1391
1392 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1393 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1394 // the option if given as we don't have backend support for any targets
1395 // that don't use the altivec abi.
1396 if (StringRef(A->getValue()) != "altivec")
1397 ABIName = A->getValue();
1398
1399 if (ABIName) {
1400 CmdArgs.push_back("-target-abi");
1401 CmdArgs.push_back(ABIName);
1402 }
1403 }
1404
hasPPCAbiArg(const ArgList & Args,const char * Value)1405 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1406 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1407 return A && (A->getValue() == StringRef(Value));
1408 }
1409
1410 /// Get the (LLVM) name of the R600 gpu we are targeting.
getR600TargetGPU(const ArgList & Args)1411 static std::string getR600TargetGPU(const ArgList &Args) {
1412 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1413 const char *GPUName = A->getValue();
1414 return llvm::StringSwitch<const char *>(GPUName)
1415 .Cases("rv630", "rv635", "r600")
1416 .Cases("rv610", "rv620", "rs780", "rs880")
1417 .Case("rv740", "rv770")
1418 .Case("palm", "cedar")
1419 .Cases("sumo", "sumo2", "sumo")
1420 .Case("hemlock", "cypress")
1421 .Case("aruba", "cayman")
1422 .Default(GPUName);
1423 }
1424 return "";
1425 }
1426
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1427 void Clang::AddSparcTargetArgs(const ArgList &Args,
1428 ArgStringList &CmdArgs) const {
1429 const Driver &D = getToolChain().getDriver();
1430 std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1431
1432 bool SoftFloatABI = false;
1433 if (Arg *A =
1434 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1435 if (A->getOption().matches(options::OPT_msoft_float))
1436 SoftFloatABI = true;
1437 }
1438
1439 // Only the hard-float ABI on Sparc is standardized, and it is the
1440 // default. GCC also supports a nonstandard soft-float ABI mode, and
1441 // perhaps LLVM should implement that, too. However, since llvm
1442 // currently does not support Sparc soft-float, at all, display an
1443 // error if it's requested.
1444 if (SoftFloatABI) {
1445 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1446 << Triple;
1447 }
1448 }
1449
getSystemZTargetCPU(const ArgList & Args)1450 static const char *getSystemZTargetCPU(const ArgList &Args) {
1451 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1452 return A->getValue();
1453 return "z10";
1454 }
1455
getSystemZTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)1456 static void getSystemZTargetFeatures(const ArgList &Args,
1457 std::vector<const char *> &Features) {
1458 // -m(no-)htm overrides use of the transactional-execution facility.
1459 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1460 if (A->getOption().matches(options::OPT_mhtm))
1461 Features.push_back("+transactional-execution");
1462 else
1463 Features.push_back("-transactional-execution");
1464 }
1465 // -m(no-)vx overrides use of the vector facility.
1466 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1467 if (A->getOption().matches(options::OPT_mvx))
1468 Features.push_back("+vector");
1469 else
1470 Features.push_back("-vector");
1471 }
1472 }
1473
getX86TargetCPU(const ArgList & Args,const llvm::Triple & Triple)1474 static const char *getX86TargetCPU(const ArgList &Args,
1475 const llvm::Triple &Triple) {
1476 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1477 if (StringRef(A->getValue()) != "native") {
1478 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1479 return "core-avx2";
1480
1481 return A->getValue();
1482 }
1483
1484 // FIXME: Reject attempts to use -march=native unless the target matches
1485 // the host.
1486 //
1487 // FIXME: We should also incorporate the detected target features for use
1488 // with -native.
1489 std::string CPU = llvm::sys::getHostCPUName();
1490 if (!CPU.empty() && CPU != "generic")
1491 return Args.MakeArgString(CPU);
1492 }
1493
1494 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1495 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1496 StringRef Arch = A->getValue();
1497 const char *CPU;
1498 if (Triple.getArch() == llvm::Triple::x86) {
1499 CPU = llvm::StringSwitch<const char *>(Arch)
1500 .Case("IA32", "i386")
1501 .Case("SSE", "pentium3")
1502 .Case("SSE2", "pentium4")
1503 .Case("AVX", "sandybridge")
1504 .Case("AVX2", "haswell")
1505 .Default(nullptr);
1506 } else {
1507 CPU = llvm::StringSwitch<const char *>(Arch)
1508 .Case("AVX", "sandybridge")
1509 .Case("AVX2", "haswell")
1510 .Default(nullptr);
1511 }
1512 if (CPU)
1513 return CPU;
1514 }
1515
1516 // Select the default CPU if none was given (or detection failed).
1517
1518 if (Triple.getArch() != llvm::Triple::x86_64 &&
1519 Triple.getArch() != llvm::Triple::x86)
1520 return nullptr; // This routine is only handling x86 targets.
1521
1522 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1523
1524 // FIXME: Need target hooks.
1525 if (Triple.isOSDarwin()) {
1526 if (Triple.getArchName() == "x86_64h")
1527 return "core-avx2";
1528 return Is64Bit ? "core2" : "yonah";
1529 }
1530
1531 // Set up default CPU name for PS4 compilers.
1532 if (Triple.isPS4CPU())
1533 return "btver2";
1534
1535 // On Android use targets compatible with gcc
1536 if (Triple.getEnvironment() == llvm::Triple::Android)
1537 return Is64Bit ? "x86-64" : "i686";
1538
1539 // Everything else goes to x86-64 in 64-bit mode.
1540 if (Is64Bit)
1541 return "x86-64";
1542
1543 switch (Triple.getOS()) {
1544 case llvm::Triple::FreeBSD:
1545 case llvm::Triple::NetBSD:
1546 case llvm::Triple::OpenBSD:
1547 return "i486";
1548 case llvm::Triple::Haiku:
1549 return "i586";
1550 case llvm::Triple::Bitrig:
1551 return "i686";
1552 default:
1553 // Fallback to p4.
1554 return "pentium4";
1555 }
1556 }
1557
getCPUName(const ArgList & Args,const llvm::Triple & T,bool FromAs=false)1558 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1559 bool FromAs = false) {
1560 switch (T.getArch()) {
1561 default:
1562 return "";
1563
1564 case llvm::Triple::aarch64:
1565 case llvm::Triple::aarch64_be:
1566 return getAArch64TargetCPU(Args);
1567
1568 case llvm::Triple::arm:
1569 case llvm::Triple::armeb:
1570 case llvm::Triple::thumb:
1571 case llvm::Triple::thumbeb: {
1572 StringRef MArch, MCPU;
1573 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1574 return arm::getARMTargetCPU(MCPU, MArch, T);
1575 }
1576 case llvm::Triple::mips:
1577 case llvm::Triple::mipsel:
1578 case llvm::Triple::mips64:
1579 case llvm::Triple::mips64el: {
1580 StringRef CPUName;
1581 StringRef ABIName;
1582 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1583 return CPUName;
1584 }
1585
1586 case llvm::Triple::nvptx:
1587 case llvm::Triple::nvptx64:
1588 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1589 return A->getValue();
1590 return "";
1591
1592 case llvm::Triple::ppc:
1593 case llvm::Triple::ppc64:
1594 case llvm::Triple::ppc64le: {
1595 std::string TargetCPUName = getPPCTargetCPU(Args);
1596 // LLVM may default to generating code for the native CPU,
1597 // but, like gcc, we default to a more generic option for
1598 // each architecture. (except on Darwin)
1599 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1600 if (T.getArch() == llvm::Triple::ppc64)
1601 TargetCPUName = "ppc64";
1602 else if (T.getArch() == llvm::Triple::ppc64le)
1603 TargetCPUName = "ppc64le";
1604 else
1605 TargetCPUName = "ppc";
1606 }
1607 return TargetCPUName;
1608 }
1609
1610 case llvm::Triple::sparc:
1611 case llvm::Triple::sparcel:
1612 case llvm::Triple::sparcv9:
1613 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1614 return A->getValue();
1615 return "";
1616
1617 case llvm::Triple::x86:
1618 case llvm::Triple::x86_64:
1619 return getX86TargetCPU(Args, T);
1620
1621 case llvm::Triple::hexagon:
1622 return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1623
1624 case llvm::Triple::systemz:
1625 return getSystemZTargetCPU(Args);
1626
1627 case llvm::Triple::r600:
1628 case llvm::Triple::amdgcn:
1629 return getR600TargetGPU(Args);
1630 }
1631 }
1632
AddGoldPlugin(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)1633 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1634 ArgStringList &CmdArgs) {
1635 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1636 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1637 // forward.
1638 CmdArgs.push_back("-plugin");
1639 std::string Plugin =
1640 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1641 CmdArgs.push_back(Args.MakeArgString(Plugin));
1642
1643 // Try to pass driver level flags relevant to LTO code generation down to
1644 // the plugin.
1645
1646 // Handle flags for selecting CPU variants.
1647 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1648 if (!CPU.empty())
1649 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1650 }
1651
1652 /// This is a helper function for validating the optional refinement step
1653 /// parameter in reciprocal argument strings. Return false if there is an error
1654 /// parsing the refinement step. Otherwise, return true and set the Position
1655 /// of the refinement step in the input string.
getRefinementStep(const StringRef & In,const Driver & D,const Arg & A,size_t & Position)1656 static bool getRefinementStep(const StringRef &In, const Driver &D,
1657 const Arg &A, size_t &Position) {
1658 const char RefinementStepToken = ':';
1659 Position = In.find(RefinementStepToken);
1660 if (Position != StringRef::npos) {
1661 StringRef Option = A.getOption().getName();
1662 StringRef RefStep = In.substr(Position + 1);
1663 // Allow exactly one numeric character for the additional refinement
1664 // step parameter. This is reasonable for all currently-supported
1665 // operations and architectures because we would expect that a larger value
1666 // of refinement steps would cause the estimate "optimization" to
1667 // under-perform the native operation. Also, if the estimate does not
1668 // converge quickly, it probably will not ever converge, so further
1669 // refinement steps will not produce a better answer.
1670 if (RefStep.size() != 1) {
1671 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1672 return false;
1673 }
1674 char RefStepChar = RefStep[0];
1675 if (RefStepChar < '0' || RefStepChar > '9') {
1676 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1677 return false;
1678 }
1679 }
1680 return true;
1681 }
1682
1683 /// The -mrecip flag requires processing of many optional parameters.
ParseMRecip(const Driver & D,const ArgList & Args,ArgStringList & OutStrings)1684 static void ParseMRecip(const Driver &D, const ArgList &Args,
1685 ArgStringList &OutStrings) {
1686 StringRef DisabledPrefixIn = "!";
1687 StringRef DisabledPrefixOut = "!";
1688 StringRef EnabledPrefixOut = "";
1689 StringRef Out = "-mrecip=";
1690
1691 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1692 if (!A)
1693 return;
1694
1695 unsigned NumOptions = A->getNumValues();
1696 if (NumOptions == 0) {
1697 // No option is the same as "all".
1698 OutStrings.push_back(Args.MakeArgString(Out + "all"));
1699 return;
1700 }
1701
1702 // Pass through "all", "none", or "default" with an optional refinement step.
1703 if (NumOptions == 1) {
1704 StringRef Val = A->getValue(0);
1705 size_t RefStepLoc;
1706 if (!getRefinementStep(Val, D, *A, RefStepLoc))
1707 return;
1708 StringRef ValBase = Val.slice(0, RefStepLoc);
1709 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1710 OutStrings.push_back(Args.MakeArgString(Out + Val));
1711 return;
1712 }
1713 }
1714
1715 // Each reciprocal type may be enabled or disabled individually.
1716 // Check each input value for validity, concatenate them all back together,
1717 // and pass through.
1718
1719 llvm::StringMap<bool> OptionStrings;
1720 OptionStrings.insert(std::make_pair("divd", false));
1721 OptionStrings.insert(std::make_pair("divf", false));
1722 OptionStrings.insert(std::make_pair("vec-divd", false));
1723 OptionStrings.insert(std::make_pair("vec-divf", false));
1724 OptionStrings.insert(std::make_pair("sqrtd", false));
1725 OptionStrings.insert(std::make_pair("sqrtf", false));
1726 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1727 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1728
1729 for (unsigned i = 0; i != NumOptions; ++i) {
1730 StringRef Val = A->getValue(i);
1731
1732 bool IsDisabled = Val.startswith(DisabledPrefixIn);
1733 // Ignore the disablement token for string matching.
1734 if (IsDisabled)
1735 Val = Val.substr(1);
1736
1737 size_t RefStep;
1738 if (!getRefinementStep(Val, D, *A, RefStep))
1739 return;
1740
1741 StringRef ValBase = Val.slice(0, RefStep);
1742 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1743 if (OptionIter == OptionStrings.end()) {
1744 // Try again specifying float suffix.
1745 OptionIter = OptionStrings.find(ValBase.str() + 'f');
1746 if (OptionIter == OptionStrings.end()) {
1747 // The input name did not match any known option string.
1748 D.Diag(diag::err_drv_unknown_argument) << Val;
1749 return;
1750 }
1751 // The option was specified without a float or double suffix.
1752 // Make sure that the double entry was not already specified.
1753 // The float entry will be checked below.
1754 if (OptionStrings[ValBase.str() + 'd']) {
1755 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1756 return;
1757 }
1758 }
1759
1760 if (OptionIter->second == true) {
1761 // Duplicate option specified.
1762 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1763 return;
1764 }
1765
1766 // Mark the matched option as found. Do not allow duplicate specifiers.
1767 OptionIter->second = true;
1768
1769 // If the precision was not specified, also mark the double entry as found.
1770 if (ValBase.back() != 'f' && ValBase.back() != 'd')
1771 OptionStrings[ValBase.str() + 'd'] = true;
1772
1773 // Build the output string.
1774 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1775 Out = Args.MakeArgString(Out + Prefix + Val);
1776 if (i != NumOptions - 1)
1777 Out = Args.MakeArgString(Out + ",");
1778 }
1779
1780 OutStrings.push_back(Args.MakeArgString(Out));
1781 }
1782
getX86TargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)1783 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1784 const ArgList &Args,
1785 std::vector<const char *> &Features) {
1786 // If -march=native, autodetect the feature list.
1787 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1788 if (StringRef(A->getValue()) == "native") {
1789 llvm::StringMap<bool> HostFeatures;
1790 if (llvm::sys::getHostCPUFeatures(HostFeatures))
1791 for (auto &F : HostFeatures)
1792 Features.push_back(
1793 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1794 }
1795 }
1796
1797 if (Triple.getArchName() == "x86_64h") {
1798 // x86_64h implies quite a few of the more modern subtarget features
1799 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1800 Features.push_back("-rdrnd");
1801 Features.push_back("-aes");
1802 Features.push_back("-pclmul");
1803 Features.push_back("-rtm");
1804 Features.push_back("-hle");
1805 Features.push_back("-fsgsbase");
1806 }
1807
1808 const llvm::Triple::ArchType ArchType = Triple.getArch();
1809 // Add features to be compatible with gcc for Android.
1810 if (Triple.getEnvironment() == llvm::Triple::Android) {
1811 if (ArchType == llvm::Triple::x86_64) {
1812 Features.push_back("+sse4.2");
1813 Features.push_back("+popcnt");
1814 } else
1815 Features.push_back("+ssse3");
1816 }
1817
1818 // Set features according to the -arch flag on MSVC.
1819 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1820 StringRef Arch = A->getValue();
1821 bool ArchUsed = false;
1822 // First, look for flags that are shared in x86 and x86-64.
1823 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1824 if (Arch == "AVX" || Arch == "AVX2") {
1825 ArchUsed = true;
1826 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1827 }
1828 }
1829 // Then, look for x86-specific flags.
1830 if (ArchType == llvm::Triple::x86) {
1831 if (Arch == "IA32") {
1832 ArchUsed = true;
1833 } else if (Arch == "SSE" || Arch == "SSE2") {
1834 ArchUsed = true;
1835 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1836 }
1837 }
1838 if (!ArchUsed)
1839 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1840 }
1841
1842 // Now add any that the user explicitly requested on the command line,
1843 // which may override the defaults.
1844 for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
1845 StringRef Name = A->getOption().getName();
1846 A->claim();
1847
1848 // Skip over "-m".
1849 assert(Name.startswith("m") && "Invalid feature name.");
1850 Name = Name.substr(1);
1851
1852 bool IsNegative = Name.startswith("no-");
1853 if (IsNegative)
1854 Name = Name.substr(3);
1855
1856 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1857 }
1858 }
1859
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1860 void Clang::AddX86TargetArgs(const ArgList &Args,
1861 ArgStringList &CmdArgs) const {
1862 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1863 Args.hasArg(options::OPT_mkernel) ||
1864 Args.hasArg(options::OPT_fapple_kext))
1865 CmdArgs.push_back("-disable-red-zone");
1866
1867 // Default to avoid implicit floating-point for kernel/kext code, but allow
1868 // that to be overridden with -mno-soft-float.
1869 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1870 Args.hasArg(options::OPT_fapple_kext));
1871 if (Arg *A = Args.getLastArg(
1872 options::OPT_msoft_float, options::OPT_mno_soft_float,
1873 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1874 const Option &O = A->getOption();
1875 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1876 O.matches(options::OPT_msoft_float));
1877 }
1878 if (NoImplicitFloat)
1879 CmdArgs.push_back("-no-implicit-float");
1880
1881 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1882 StringRef Value = A->getValue();
1883 if (Value == "intel" || Value == "att") {
1884 CmdArgs.push_back("-mllvm");
1885 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1886 } else {
1887 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1888 << A->getOption().getName() << Value;
1889 }
1890 }
1891 }
1892
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1893 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1894 ArgStringList &CmdArgs) const {
1895 CmdArgs.push_back("-mqdsp6-compat");
1896 CmdArgs.push_back("-Wreturn-type");
1897
1898 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
1899 std::string SmallDataThreshold = "-hexagon-small-data-threshold=";
1900 SmallDataThreshold += v;
1901 CmdArgs.push_back("-mllvm");
1902 CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
1903 }
1904
1905 if (!Args.hasArg(options::OPT_fno_short_enums))
1906 CmdArgs.push_back("-fshort-enums");
1907 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1908 CmdArgs.push_back("-mllvm");
1909 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1910 }
1911 CmdArgs.push_back("-mllvm");
1912 CmdArgs.push_back("-machine-sink-split=0");
1913 }
1914
1915 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
DecodeAArch64Features(const Driver & D,StringRef text,std::vector<const char * > & Features)1916 static bool DecodeAArch64Features(const Driver &D, StringRef text,
1917 std::vector<const char *> &Features) {
1918 SmallVector<StringRef, 8> Split;
1919 text.split(Split, StringRef("+"), -1, false);
1920
1921 for (const StringRef Feature : Split) {
1922 const char *result = llvm::StringSwitch<const char *>(Feature)
1923 .Case("fp", "+fp-armv8")
1924 .Case("simd", "+neon")
1925 .Case("crc", "+crc")
1926 .Case("crypto", "+crypto")
1927 .Case("nofp", "-fp-armv8")
1928 .Case("nosimd", "-neon")
1929 .Case("nocrc", "-crc")
1930 .Case("nocrypto", "-crypto")
1931 .Default(nullptr);
1932 if (result)
1933 Features.push_back(result);
1934 else if (Feature == "neon" || Feature == "noneon")
1935 D.Diag(diag::err_drv_no_neon_modifier);
1936 else
1937 return false;
1938 }
1939 return true;
1940 }
1941
1942 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1943 // decode CPU and feature.
DecodeAArch64Mcpu(const Driver & D,StringRef Mcpu,StringRef & CPU,std::vector<const char * > & Features)1944 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1945 std::vector<const char *> &Features) {
1946 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1947 CPU = Split.first;
1948 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
1949 CPU == "cortex-a72") {
1950 Features.push_back("+neon");
1951 Features.push_back("+crc");
1952 Features.push_back("+crypto");
1953 } else if (CPU == "generic") {
1954 Features.push_back("+neon");
1955 } else {
1956 return false;
1957 }
1958
1959 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1960 return false;
1961
1962 return true;
1963 }
1964
1965 static bool
getAArch64ArchFeaturesFromMarch(const Driver & D,StringRef March,const ArgList & Args,std::vector<const char * > & Features)1966 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1967 const ArgList &Args,
1968 std::vector<const char *> &Features) {
1969 std::string MarchLowerCase = March.lower();
1970 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
1971
1972 if (Split.first == "armv8-a" || Split.first == "armv8a") {
1973 // ok, no additional features.
1974 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
1975 Features.push_back("+v8.1a");
1976 } else {
1977 return false;
1978 }
1979
1980 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1981 return false;
1982
1983 return true;
1984 }
1985
1986 static bool
getAArch64ArchFeaturesFromMcpu(const Driver & D,StringRef Mcpu,const ArgList & Args,std::vector<const char * > & Features)1987 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1988 const ArgList &Args,
1989 std::vector<const char *> &Features) {
1990 StringRef CPU;
1991 std::string McpuLowerCase = Mcpu.lower();
1992 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
1993 return false;
1994
1995 return true;
1996 }
1997
1998 static bool
getAArch64MicroArchFeaturesFromMtune(const Driver & D,StringRef Mtune,const ArgList & Args,std::vector<const char * > & Features)1999 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2000 const ArgList &Args,
2001 std::vector<const char *> &Features) {
2002 // Handle CPU name is 'native'.
2003 if (Mtune == "native")
2004 Mtune = llvm::sys::getHostCPUName();
2005 if (Mtune == "cyclone") {
2006 Features.push_back("+zcm");
2007 Features.push_back("+zcz");
2008 }
2009 return true;
2010 }
2011
2012 static bool
getAArch64MicroArchFeaturesFromMcpu(const Driver & D,StringRef Mcpu,const ArgList & Args,std::vector<const char * > & Features)2013 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2014 const ArgList &Args,
2015 std::vector<const char *> &Features) {
2016 StringRef CPU;
2017 std::vector<const char *> DecodedFeature;
2018 std::string McpuLowerCase = Mcpu.lower();
2019 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2020 return false;
2021
2022 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2023 }
2024
getAArch64TargetFeatures(const Driver & D,const ArgList & Args,std::vector<const char * > & Features)2025 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2026 std::vector<const char *> &Features) {
2027 Arg *A;
2028 bool success = true;
2029 // Enable NEON by default.
2030 Features.push_back("+neon");
2031 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2032 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2033 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2034 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2035 else if (Args.hasArg(options::OPT_arch))
2036 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2037 Features);
2038
2039 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2040 success =
2041 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2042 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2043 success =
2044 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2045 else if (Args.hasArg(options::OPT_arch))
2046 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2047 Args, Features);
2048
2049 if (!success)
2050 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2051
2052 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2053 Features.push_back("-fp-armv8");
2054 Features.push_back("-crypto");
2055 Features.push_back("-neon");
2056 }
2057
2058 // En/disable crc
2059 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2060 if (A->getOption().matches(options::OPT_mcrc))
2061 Features.push_back("+crc");
2062 else
2063 Features.push_back("-crc");
2064 }
2065 }
2066
getTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool ForAS)2067 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
2068 const ArgList &Args, ArgStringList &CmdArgs,
2069 bool ForAS) {
2070 std::vector<const char *> Features;
2071 switch (Triple.getArch()) {
2072 default:
2073 break;
2074 case llvm::Triple::mips:
2075 case llvm::Triple::mipsel:
2076 case llvm::Triple::mips64:
2077 case llvm::Triple::mips64el:
2078 getMIPSTargetFeatures(D, Triple, Args, Features);
2079 break;
2080
2081 case llvm::Triple::arm:
2082 case llvm::Triple::armeb:
2083 case llvm::Triple::thumb:
2084 case llvm::Triple::thumbeb:
2085 getARMTargetFeatures(D, Triple, Args, Features, ForAS);
2086 break;
2087
2088 case llvm::Triple::ppc:
2089 case llvm::Triple::ppc64:
2090 case llvm::Triple::ppc64le:
2091 getPPCTargetFeatures(Args, Features);
2092 break;
2093 case llvm::Triple::systemz:
2094 getSystemZTargetFeatures(Args, Features);
2095 break;
2096 case llvm::Triple::aarch64:
2097 case llvm::Triple::aarch64_be:
2098 getAArch64TargetFeatures(D, Args, Features);
2099 break;
2100 case llvm::Triple::x86:
2101 case llvm::Triple::x86_64:
2102 getX86TargetFeatures(D, Triple, Args, Features);
2103 break;
2104 }
2105
2106 // Find the last of each feature.
2107 llvm::StringMap<unsigned> LastOpt;
2108 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2109 const char *Name = Features[I];
2110 assert(Name[0] == '-' || Name[0] == '+');
2111 LastOpt[Name + 1] = I;
2112 }
2113
2114 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2115 // If this feature was overridden, ignore it.
2116 const char *Name = Features[I];
2117 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2118 assert(LastI != LastOpt.end());
2119 unsigned Last = LastI->second;
2120 if (Last != I)
2121 continue;
2122
2123 CmdArgs.push_back("-target-feature");
2124 CmdArgs.push_back(Name);
2125 }
2126 }
2127
2128 static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)2129 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2130 const llvm::Triple &Triple) {
2131 // We use the zero-cost exception tables for Objective-C if the non-fragile
2132 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2133 // later.
2134 if (runtime.isNonFragile())
2135 return true;
2136
2137 if (!Triple.isMacOSX())
2138 return false;
2139
2140 return (!Triple.isMacOSXVersionLT(10, 5) &&
2141 (Triple.getArch() == llvm::Triple::x86_64 ||
2142 Triple.getArch() == llvm::Triple::arm));
2143 }
2144
2145 /// Adds exception related arguments to the driver command arguments. There's a
2146 /// master flag, -fexceptions and also language specific flags to enable/disable
2147 /// C++ and Objective-C exceptions. This makes it possible to for example
2148 /// 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)2149 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2150 const ToolChain &TC, bool KernelOrKext,
2151 const ObjCRuntime &objcRuntime,
2152 ArgStringList &CmdArgs) {
2153 const Driver &D = TC.getDriver();
2154 const llvm::Triple &Triple = TC.getTriple();
2155
2156 if (KernelOrKext) {
2157 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2158 // arguments now to avoid warnings about unused arguments.
2159 Args.ClaimAllArgs(options::OPT_fexceptions);
2160 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2161 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2162 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2163 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2164 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2165 return;
2166 }
2167
2168 // See if the user explicitly enabled exceptions.
2169 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2170 false);
2171
2172 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2173 // is not necessarily sensible, but follows GCC.
2174 if (types::isObjC(InputType) &&
2175 Args.hasFlag(options::OPT_fobjc_exceptions,
2176 options::OPT_fno_objc_exceptions, true)) {
2177 CmdArgs.push_back("-fobjc-exceptions");
2178
2179 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2180 }
2181
2182 if (types::isCXX(InputType)) {
2183 // Disable C++ EH by default on XCore, PS4, and MSVC.
2184 // FIXME: Remove MSVC from this list once things work.
2185 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2186 !Triple.isPS4CPU() &&
2187 !Triple.isWindowsMSVCEnvironment();
2188 Arg *ExceptionArg = Args.getLastArg(
2189 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2190 options::OPT_fexceptions, options::OPT_fno_exceptions);
2191 if (ExceptionArg)
2192 CXXExceptionsEnabled =
2193 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2194 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2195
2196 if (CXXExceptionsEnabled) {
2197 if (Triple.isPS4CPU()) {
2198 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2199 assert(ExceptionArg &&
2200 "On the PS4 exceptions should only be enabled if passing "
2201 "an argument");
2202 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2203 const Arg *RTTIArg = TC.getRTTIArg();
2204 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2205 D.Diag(diag::err_drv_argument_not_allowed_with)
2206 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2207 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2208 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2209 } else
2210 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2211
2212 CmdArgs.push_back("-fcxx-exceptions");
2213
2214 EH = true;
2215 }
2216 }
2217
2218 if (EH)
2219 CmdArgs.push_back("-fexceptions");
2220 }
2221
ShouldDisableAutolink(const ArgList & Args,const ToolChain & TC)2222 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2223 bool Default = true;
2224 if (TC.getTriple().isOSDarwin()) {
2225 // The native darwin assembler doesn't support the linker_option directives,
2226 // so we disable them if we think the .s file will be passed to it.
2227 Default = TC.useIntegratedAs();
2228 }
2229 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2230 Default);
2231 }
2232
ShouldDisableDwarfDirectory(const ArgList & Args,const ToolChain & TC)2233 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2234 const ToolChain &TC) {
2235 bool UseDwarfDirectory =
2236 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2237 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2238 return !UseDwarfDirectory;
2239 }
2240
2241 /// \brief Check whether the given input tree contains any compilation actions.
ContainsCompileAction(const Action * A)2242 static bool ContainsCompileAction(const Action *A) {
2243 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2244 return true;
2245
2246 for (const auto &Act : *A)
2247 if (ContainsCompileAction(Act))
2248 return true;
2249
2250 return false;
2251 }
2252
2253 /// \brief Check if -relax-all should be passed to the internal assembler.
2254 /// This is done by default when compiling non-assembler source with -O0.
UseRelaxAll(Compilation & C,const ArgList & Args)2255 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2256 bool RelaxDefault = true;
2257
2258 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2259 RelaxDefault = A->getOption().matches(options::OPT_O0);
2260
2261 if (RelaxDefault) {
2262 RelaxDefault = false;
2263 for (const auto &Act : C.getActions()) {
2264 if (ContainsCompileAction(Act)) {
2265 RelaxDefault = true;
2266 break;
2267 }
2268 }
2269 }
2270
2271 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2272 RelaxDefault);
2273 }
2274
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)2275 static void CollectArgsForIntegratedAssembler(Compilation &C,
2276 const ArgList &Args,
2277 ArgStringList &CmdArgs,
2278 const Driver &D) {
2279 if (UseRelaxAll(C, Args))
2280 CmdArgs.push_back("-mrelax-all");
2281
2282 // When passing -I arguments to the assembler we sometimes need to
2283 // unconditionally take the next argument. For example, when parsing
2284 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2285 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2286 // arg after parsing the '-I' arg.
2287 bool TakeNextArg = false;
2288
2289 // When using an integrated assembler, translate -Wa, and -Xassembler
2290 // options.
2291 bool CompressDebugSections = false;
2292 for (const Arg *A :
2293 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2294 A->claim();
2295
2296 for (const StringRef Value : A->getValues()) {
2297 if (TakeNextArg) {
2298 CmdArgs.push_back(Value.data());
2299 TakeNextArg = false;
2300 continue;
2301 }
2302
2303 if (Value == "-force_cpusubtype_ALL") {
2304 // Do nothing, this is the default and we don't support anything else.
2305 } else if (Value == "-L") {
2306 CmdArgs.push_back("-msave-temp-labels");
2307 } else if (Value == "--fatal-warnings") {
2308 CmdArgs.push_back("-massembler-fatal-warnings");
2309 } else if (Value == "--noexecstack") {
2310 CmdArgs.push_back("-mnoexecstack");
2311 } else if (Value == "-compress-debug-sections" ||
2312 Value == "--compress-debug-sections") {
2313 CompressDebugSections = true;
2314 } else if (Value == "-nocompress-debug-sections" ||
2315 Value == "--nocompress-debug-sections") {
2316 CompressDebugSections = false;
2317 } else if (Value.startswith("-I")) {
2318 CmdArgs.push_back(Value.data());
2319 // We need to consume the next argument if the current arg is a plain
2320 // -I. The next arg will be the include directory.
2321 if (Value == "-I")
2322 TakeNextArg = true;
2323 } else if (Value.startswith("-gdwarf-")) {
2324 CmdArgs.push_back(Value.data());
2325 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2326 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2327 // Do nothing, we'll validate it later.
2328 } else {
2329 D.Diag(diag::err_drv_unsupported_option_argument)
2330 << A->getOption().getName() << Value;
2331 }
2332 }
2333 }
2334 if (CompressDebugSections) {
2335 if (llvm::zlib::isAvailable())
2336 CmdArgs.push_back("-compress-debug-sections");
2337 else
2338 D.Diag(diag::warn_debug_compression_unavailable);
2339 }
2340 }
2341
2342 // Until ARM libraries are build separately, we have them all in one library
getArchNameForCompilerRTLib(const ToolChain & TC)2343 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2344 if (TC.getTriple().isWindowsMSVCEnvironment() &&
2345 TC.getArch() == llvm::Triple::x86)
2346 return "i386";
2347 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
2348 return "arm";
2349 return TC.getArchName();
2350 }
2351
getCompilerRTLibDir(const ToolChain & TC)2352 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2353 // The runtimes are located in the OS-specific resource directory.
2354 SmallString<128> Res(TC.getDriver().ResourceDir);
2355 const llvm::Triple &Triple = TC.getTriple();
2356 // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2357 StringRef OSLibName =
2358 (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
2359 llvm::sys::path::append(Res, "lib", OSLibName);
2360 return Res;
2361 }
2362
getCompilerRT(const ToolChain & TC,StringRef Component,bool Shared)2363 SmallString<128> tools::getCompilerRT(const ToolChain &TC, StringRef Component,
2364 bool Shared) {
2365 const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
2366 ? "-android"
2367 : "";
2368
2369 bool IsOSWindows = TC.getTriple().isOSWindows();
2370 bool IsITANMSVCWindows = TC.getTriple().isWindowsMSVCEnvironment() ||
2371 TC.getTriple().isWindowsItaniumEnvironment();
2372 StringRef Arch = getArchNameForCompilerRTLib(TC);
2373 const char *Prefix = IsITANMSVCWindows ? "" : "lib";
2374 const char *Suffix =
2375 Shared ? (IsOSWindows ? ".dll" : ".so") : (IsITANMSVCWindows ? ".lib" : ".a");
2376
2377 SmallString<128> Path = getCompilerRTLibDir(TC);
2378 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
2379 Arch + Env + Suffix);
2380
2381 return Path;
2382 }
2383
2384 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2385 // FIXME: Make sure we can also emit shared objects if they're requested
2386 // and available, check for possible errors, etc.
addClangRT(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2387 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2388 ArgStringList &CmdArgs) {
2389 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
2390
2391 if (!TC.getTriple().isOSWindows()) {
2392 // FIXME: why do we link against gcc when we are using compiler-rt?
2393 CmdArgs.push_back("-lgcc_s");
2394 if (TC.getDriver().CCCIsCXX())
2395 CmdArgs.push_back("-lgcc_eh");
2396 }
2397 }
2398
addProfileRT(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2399 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
2400 ArgStringList &CmdArgs) {
2401 if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2402 false) ||
2403 Args.hasArg(options::OPT_fprofile_generate) ||
2404 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
2405 Args.hasArg(options::OPT_fprofile_instr_generate) ||
2406 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
2407 Args.hasArg(options::OPT_fcreate_profile) ||
2408 Args.hasArg(options::OPT_coverage)))
2409 return;
2410
2411 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
2412 }
2413
2414 namespace {
2415 enum OpenMPRuntimeKind {
2416 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2417 /// without knowing what runtime to target.
2418 OMPRT_Unknown,
2419
2420 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2421 /// the default for Clang.
2422 OMPRT_OMP,
2423
2424 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2425 /// this runtime but can swallow the pragmas, and find and link against the
2426 /// runtime library itself.
2427 OMPRT_GOMP,
2428
2429 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2430 /// OpenMP runtime. We support this mode for users with existing dependencies
2431 /// on this runtime library name.
2432 OMPRT_IOMP5
2433 };
2434 }
2435
2436 /// Compute the desired OpenMP runtime from the flag provided.
getOpenMPRuntime(const ToolChain & TC,const ArgList & Args)2437 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2438 const ArgList &Args) {
2439 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2440
2441 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2442 if (A)
2443 RuntimeName = A->getValue();
2444
2445 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2446 .Case("libomp", OMPRT_OMP)
2447 .Case("libgomp", OMPRT_GOMP)
2448 .Case("libiomp5", OMPRT_IOMP5)
2449 .Default(OMPRT_Unknown);
2450
2451 if (RT == OMPRT_Unknown) {
2452 if (A)
2453 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2454 << A->getOption().getName() << A->getValue();
2455 else
2456 // FIXME: We could use a nicer diagnostic here.
2457 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2458 }
2459
2460 return RT;
2461 }
2462
addOpenMPRuntime(ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args)2463 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2464 const ArgList &Args) {
2465 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2466 options::OPT_fno_openmp, false))
2467 return;
2468
2469 switch (getOpenMPRuntime(TC, Args)) {
2470 case OMPRT_OMP:
2471 CmdArgs.push_back("-lomp");
2472 break;
2473 case OMPRT_GOMP:
2474 CmdArgs.push_back("-lgomp");
2475 break;
2476 case OMPRT_IOMP5:
2477 CmdArgs.push_back("-liomp5");
2478 break;
2479 case OMPRT_Unknown:
2480 // Already diagnosed.
2481 break;
2482 }
2483 }
2484
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared)2485 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2486 ArgStringList &CmdArgs, StringRef Sanitizer,
2487 bool IsShared) {
2488 // Static runtimes must be forced into executable, so we wrap them in
2489 // whole-archive.
2490 if (!IsShared)
2491 CmdArgs.push_back("-whole-archive");
2492 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
2493 if (!IsShared)
2494 CmdArgs.push_back("-no-whole-archive");
2495 }
2496
2497 // Tries to use a file with the list of dynamic symbols that need to be exported
2498 // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)2499 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2500 ArgStringList &CmdArgs,
2501 StringRef Sanitizer) {
2502 SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
2503 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2504 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2505 return true;
2506 }
2507 return false;
2508 }
2509
linkSanitizerRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)2510 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2511 ArgStringList &CmdArgs) {
2512 // Force linking against the system libraries sanitizers depends on
2513 // (see PR15823 why this is necessary).
2514 CmdArgs.push_back("--no-as-needed");
2515 CmdArgs.push_back("-lpthread");
2516 CmdArgs.push_back("-lrt");
2517 CmdArgs.push_back("-lm");
2518 // There's no libdl on FreeBSD.
2519 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2520 CmdArgs.push_back("-ldl");
2521 }
2522
2523 static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes)2524 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2525 SmallVectorImpl<StringRef> &SharedRuntimes,
2526 SmallVectorImpl<StringRef> &StaticRuntimes,
2527 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2528 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2529 // Collect shared runtimes.
2530 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2531 SharedRuntimes.push_back("asan");
2532 }
2533
2534 // Collect static runtimes.
2535 if (Args.hasArg(options::OPT_shared) ||
2536 (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
2537 // Don't link static runtimes into DSOs or if compiling for Android.
2538 return;
2539 }
2540 if (SanArgs.needsAsanRt()) {
2541 if (SanArgs.needsSharedAsanRt()) {
2542 HelperStaticRuntimes.push_back("asan-preinit");
2543 } else {
2544 StaticRuntimes.push_back("asan");
2545 if (SanArgs.linkCXXRuntimes())
2546 StaticRuntimes.push_back("asan_cxx");
2547 }
2548 }
2549 if (SanArgs.needsDfsanRt())
2550 StaticRuntimes.push_back("dfsan");
2551 if (SanArgs.needsLsanRt())
2552 StaticRuntimes.push_back("lsan");
2553 if (SanArgs.needsMsanRt()) {
2554 StaticRuntimes.push_back("msan");
2555 if (SanArgs.linkCXXRuntimes())
2556 StaticRuntimes.push_back("msan_cxx");
2557 }
2558 if (SanArgs.needsTsanRt()) {
2559 StaticRuntimes.push_back("tsan");
2560 if (SanArgs.linkCXXRuntimes())
2561 StaticRuntimes.push_back("tsan_cxx");
2562 }
2563 if (SanArgs.needsUbsanRt()) {
2564 StaticRuntimes.push_back("ubsan_standalone");
2565 if (SanArgs.linkCXXRuntimes())
2566 StaticRuntimes.push_back("ubsan_standalone_cxx");
2567 }
2568 if (SanArgs.needsSafeStackRt())
2569 StaticRuntimes.push_back("safestack");
2570 }
2571
2572 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2573 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2574 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2575 ArgStringList &CmdArgs) {
2576 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2577 HelperStaticRuntimes;
2578 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2579 HelperStaticRuntimes);
2580 for (auto RT : SharedRuntimes)
2581 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2582 for (auto RT : HelperStaticRuntimes)
2583 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2584 bool AddExportDynamic = false;
2585 for (auto RT : StaticRuntimes) {
2586 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2587 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2588 }
2589 // If there is a static runtime with no dynamic list, force all the symbols
2590 // to be dynamic to be sure we export sanitizer interface functions.
2591 if (AddExportDynamic)
2592 CmdArgs.push_back("-export-dynamic");
2593 return !StaticRuntimes.empty();
2594 }
2595
areOptimizationsEnabled(const ArgList & Args)2596 static bool areOptimizationsEnabled(const ArgList &Args) {
2597 // Find the last -O arg and see if it is non-zero.
2598 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2599 return !A->getOption().matches(options::OPT_O0);
2600 // Defaults to -O0.
2601 return false;
2602 }
2603
shouldUseFramePointerForTarget(const ArgList & Args,const llvm::Triple & Triple)2604 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2605 const llvm::Triple &Triple) {
2606 // XCore never wants frame pointers, regardless of OS.
2607 if (Triple.getArch() == llvm::Triple::xcore) {
2608 return false;
2609 }
2610
2611 if (Triple.isOSLinux()) {
2612 switch (Triple.getArch()) {
2613 // Don't use a frame pointer on linux if optimizing for certain targets.
2614 case llvm::Triple::mips64:
2615 case llvm::Triple::mips64el:
2616 case llvm::Triple::mips:
2617 case llvm::Triple::mipsel:
2618 case llvm::Triple::systemz:
2619 case llvm::Triple::x86:
2620 case llvm::Triple::x86_64:
2621 return !areOptimizationsEnabled(Args);
2622 default:
2623 return true;
2624 }
2625 }
2626
2627 if (Triple.isOSWindows()) {
2628 switch (Triple.getArch()) {
2629 case llvm::Triple::x86:
2630 return !areOptimizationsEnabled(Args);
2631 default:
2632 // All other supported Windows ISAs use xdata unwind information, so frame
2633 // pointers are not generally useful.
2634 return false;
2635 }
2636 }
2637
2638 return true;
2639 }
2640
shouldUseFramePointer(const ArgList & Args,const llvm::Triple & Triple)2641 static bool shouldUseFramePointer(const ArgList &Args,
2642 const llvm::Triple &Triple) {
2643 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2644 options::OPT_fomit_frame_pointer))
2645 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2646
2647 return shouldUseFramePointerForTarget(Args, Triple);
2648 }
2649
shouldUseLeafFramePointer(const ArgList & Args,const llvm::Triple & Triple)2650 static bool shouldUseLeafFramePointer(const ArgList &Args,
2651 const llvm::Triple &Triple) {
2652 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2653 options::OPT_momit_leaf_frame_pointer))
2654 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2655
2656 if (Triple.isPS4CPU())
2657 return false;
2658
2659 return shouldUseFramePointerForTarget(Args, Triple);
2660 }
2661
2662 /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs)2663 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2664 SmallString<128> cwd;
2665 if (!llvm::sys::fs::current_path(cwd)) {
2666 CmdArgs.push_back("-fdebug-compilation-dir");
2667 CmdArgs.push_back(Args.MakeArgString(cwd));
2668 }
2669 }
2670
SplitDebugName(const ArgList & Args,const InputInfo & Input)2671 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2672 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2673 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2674 SmallString<128> T(FinalOutput->getValue());
2675 llvm::sys::path::replace_extension(T, "dwo");
2676 return Args.MakeArgString(T);
2677 } else {
2678 // Use the compilation dir.
2679 SmallString<128> T(
2680 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2681 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2682 llvm::sys::path::replace_extension(F, "dwo");
2683 T += F;
2684 return Args.MakeArgString(F);
2685 }
2686 }
2687
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)2688 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2689 const JobAction &JA, const ArgList &Args,
2690 const InputInfo &Output, const char *OutFile) {
2691 ArgStringList ExtractArgs;
2692 ExtractArgs.push_back("--extract-dwo");
2693
2694 ArgStringList StripArgs;
2695 StripArgs.push_back("--strip-dwo");
2696
2697 // Grabbing the output of the earlier compile step.
2698 StripArgs.push_back(Output.getFilename());
2699 ExtractArgs.push_back(Output.getFilename());
2700 ExtractArgs.push_back(OutFile);
2701
2702 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2703
2704 // First extract the dwo sections.
2705 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
2706
2707 // Then remove them from the original .o file.
2708 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
2709 }
2710
2711 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2712 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
shouldEnableVectorizerAtOLevel(const ArgList & Args,bool isSlpVec)2713 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2714 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2715 if (A->getOption().matches(options::OPT_O4) ||
2716 A->getOption().matches(options::OPT_Ofast))
2717 return true;
2718
2719 if (A->getOption().matches(options::OPT_O0))
2720 return false;
2721
2722 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2723
2724 // Vectorize -Os.
2725 StringRef S(A->getValue());
2726 if (S == "s")
2727 return true;
2728
2729 // Don't vectorize -Oz, unless it's the slp vectorizer.
2730 if (S == "z")
2731 return isSlpVec;
2732
2733 unsigned OptLevel = 0;
2734 if (S.getAsInteger(10, OptLevel))
2735 return false;
2736
2737 return OptLevel > 1;
2738 }
2739
2740 return false;
2741 }
2742
2743 /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)2744 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2745 ArgStringList &CmdArgs) {
2746 // When using -verify-pch, we don't want to provide the type
2747 // 'precompiled-header' if it was inferred from the file extension
2748 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2749 return;
2750
2751 CmdArgs.push_back("-x");
2752 if (Args.hasArg(options::OPT_rewrite_objc))
2753 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2754 else
2755 CmdArgs.push_back(types::getTypeName(Input.getType()));
2756 }
2757
getMSCompatibilityVersion(unsigned Version)2758 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
2759 if (Version < 100)
2760 return VersionTuple(Version);
2761
2762 if (Version < 10000)
2763 return VersionTuple(Version / 100, Version % 100);
2764
2765 unsigned Build = 0, Factor = 1;
2766 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2767 Build = Build + (Version % 10) * Factor;
2768 return VersionTuple(Version / 100, Version % 100, Build);
2769 }
2770
2771 // Claim options we don't want to warn if they are unused. We do this for
2772 // options that build systems might add but are unused when assembling or only
2773 // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)2774 static void claimNoWarnArgs(const ArgList &Args) {
2775 // Don't warn about unused -f(no-)?lto. This can happen when we're
2776 // preprocessing, precompiling or assembling.
2777 Args.ClaimAllArgs(options::OPT_flto);
2778 Args.ClaimAllArgs(options::OPT_fno_lto);
2779 }
2780
appendUserToPath(SmallVectorImpl<char> & Result)2781 static void appendUserToPath(SmallVectorImpl<char> &Result) {
2782 #ifdef LLVM_ON_UNIX
2783 const char *Username = getenv("LOGNAME");
2784 #else
2785 const char *Username = getenv("USERNAME");
2786 #endif
2787 if (Username) {
2788 // Validate that LoginName can be used in a path, and get its length.
2789 size_t Len = 0;
2790 for (const char *P = Username; *P; ++P, ++Len) {
2791 if (!isAlphanumeric(*P) && *P != '_') {
2792 Username = nullptr;
2793 break;
2794 }
2795 }
2796
2797 if (Username && Len > 0) {
2798 Result.append(Username, Username + Len);
2799 return;
2800 }
2801 }
2802
2803 // Fallback to user id.
2804 #ifdef LLVM_ON_UNIX
2805 std::string UID = llvm::utostr(getuid());
2806 #else
2807 // FIXME: Windows seems to have an 'SID' that might work.
2808 std::string UID = "9999";
2809 #endif
2810 Result.append(UID.begin(), UID.end());
2811 }
2812
getMSVCVersion(const Driver * D,const llvm::Triple & Triple,const llvm::opt::ArgList & Args,bool IsWindowsMSVC)2813 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
2814 const llvm::Triple &Triple,
2815 const llvm::opt::ArgList &Args,
2816 bool IsWindowsMSVC) {
2817 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2818 IsWindowsMSVC) ||
2819 Args.hasArg(options::OPT_fmsc_version) ||
2820 Args.hasArg(options::OPT_fms_compatibility_version)) {
2821 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
2822 const Arg *MSCompatibilityVersion =
2823 Args.getLastArg(options::OPT_fms_compatibility_version);
2824
2825 if (MSCVersion && MSCompatibilityVersion) {
2826 if (D)
2827 D->Diag(diag::err_drv_argument_not_allowed_with)
2828 << MSCVersion->getAsString(Args)
2829 << MSCompatibilityVersion->getAsString(Args);
2830 return VersionTuple();
2831 }
2832
2833 if (MSCompatibilityVersion) {
2834 VersionTuple MSVT;
2835 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
2836 D->Diag(diag::err_drv_invalid_value)
2837 << MSCompatibilityVersion->getAsString(Args)
2838 << MSCompatibilityVersion->getValue();
2839 return MSVT;
2840 }
2841
2842 if (MSCVersion) {
2843 unsigned Version = 0;
2844 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
2845 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
2846 << MSCVersion->getValue();
2847 return getMSCompatibilityVersion(Version);
2848 }
2849
2850 unsigned Major, Minor, Micro;
2851 Triple.getEnvironmentVersion(Major, Minor, Micro);
2852 if (Major || Minor || Micro)
2853 return VersionTuple(Major, Minor, Micro);
2854
2855 return VersionTuple(18);
2856 }
2857 return VersionTuple();
2858 }
2859
addPGOAndCoverageFlags(Compilation & C,const Driver & D,const InputInfo & Output,const ArgList & Args,ArgStringList & CmdArgs)2860 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
2861 const InputInfo &Output, const ArgList &Args,
2862 ArgStringList &CmdArgs) {
2863 auto *ProfileGenerateArg = Args.getLastArg(
2864 options::OPT_fprofile_instr_generate,
2865 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
2866 options::OPT_fprofile_generate_EQ);
2867
2868 auto *ProfileUseArg = Args.getLastArg(
2869 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
2870 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
2871
2872 if (ProfileGenerateArg && ProfileUseArg)
2873 D.Diag(diag::err_drv_argument_not_allowed_with)
2874 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
2875
2876 if (ProfileGenerateArg &&
2877 ProfileGenerateArg->getOption().matches(
2878 options::OPT_fprofile_instr_generate_EQ))
2879 ProfileGenerateArg->render(Args, CmdArgs);
2880 else if (ProfileGenerateArg &&
2881 ProfileGenerateArg->getOption().matches(
2882 options::OPT_fprofile_generate_EQ)) {
2883 SmallString<128> Path(ProfileGenerateArg->getValue());
2884 llvm::sys::path::append(Path, "default.profraw");
2885 CmdArgs.push_back(
2886 Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
2887 } else
2888 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
2889
2890 if (ProfileUseArg &&
2891 ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
2892 ProfileUseArg->render(Args, CmdArgs);
2893 else if (ProfileUseArg &&
2894 (ProfileUseArg->getOption().matches(options::OPT_fprofile_use_EQ) ||
2895 ProfileUseArg->getOption().matches(
2896 options::OPT_fprofile_instr_use))) {
2897 SmallString<128> Path(
2898 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
2899 if (Path.empty() || llvm::sys::fs::is_directory(Path))
2900 llvm::sys::path::append(Path, "default.profdata");
2901 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
2902 }
2903
2904 if (Args.hasArg(options::OPT_ftest_coverage) ||
2905 Args.hasArg(options::OPT_coverage))
2906 CmdArgs.push_back("-femit-coverage-notes");
2907 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2908 false) ||
2909 Args.hasArg(options::OPT_coverage))
2910 CmdArgs.push_back("-femit-coverage-data");
2911
2912 if (Args.hasArg(options::OPT_fcoverage_mapping) && !ProfileGenerateArg)
2913 D.Diag(diag::err_drv_argument_only_allowed_with)
2914 << "-fcoverage-mapping"
2915 << "-fprofile-instr-generate";
2916
2917 if (Args.hasArg(options::OPT_fcoverage_mapping))
2918 CmdArgs.push_back("-fcoverage-mapping");
2919
2920 if (C.getArgs().hasArg(options::OPT_c) ||
2921 C.getArgs().hasArg(options::OPT_S)) {
2922 if (Output.isFilename()) {
2923 CmdArgs.push_back("-coverage-file");
2924 SmallString<128> CoverageFilename;
2925 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
2926 CoverageFilename = FinalOutput->getValue();
2927 } else {
2928 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
2929 }
2930 if (llvm::sys::path::is_relative(CoverageFilename)) {
2931 SmallString<128> Pwd;
2932 if (!llvm::sys::fs::current_path(Pwd)) {
2933 llvm::sys::path::append(Pwd, CoverageFilename);
2934 CoverageFilename.swap(Pwd);
2935 }
2936 }
2937 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
2938 }
2939 }
2940 }
2941
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const2942 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2943 const InputInfo &Output, const InputInfoList &Inputs,
2944 const ArgList &Args, const char *LinkingOutput) const {
2945 bool KernelOrKext =
2946 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
2947 const Driver &D = getToolChain().getDriver();
2948 ArgStringList CmdArgs;
2949
2950 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2951 bool IsWindowsCygnus =
2952 getToolChain().getTriple().isWindowsCygwinEnvironment();
2953 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2954
2955 // Check number of inputs for sanity. We need at least one input.
2956 assert(Inputs.size() >= 1 && "Must have at least one input.");
2957 const InputInfo &Input = Inputs[0];
2958 // CUDA compilation may have multiple inputs (source file + results of
2959 // device-side compilations). All other jobs are expected to have exactly one
2960 // input.
2961 bool IsCuda = types::isCuda(Input.getType());
2962 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
2963
2964 // Invoke ourselves in -cc1 mode.
2965 //
2966 // FIXME: Implement custom jobs for internal actions.
2967 CmdArgs.push_back("-cc1");
2968
2969 // Add the "effective" target triple.
2970 CmdArgs.push_back("-triple");
2971 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2972 CmdArgs.push_back(Args.MakeArgString(TripleStr));
2973
2974 const llvm::Triple TT(TripleStr);
2975 if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2976 TT.getArch() == llvm::Triple::thumb)) {
2977 unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2978 unsigned Version;
2979 TT.getArchName().substr(Offset).getAsInteger(10, Version);
2980 if (Version < 7)
2981 D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2982 << TripleStr;
2983 }
2984
2985 // Push all default warning arguments that are specific to
2986 // the given target. These come before user provided warning options
2987 // are provided.
2988 getToolChain().addClangWarningOptions(CmdArgs);
2989
2990 // Select the appropriate action.
2991 RewriteKind rewriteKind = RK_None;
2992
2993 if (isa<AnalyzeJobAction>(JA)) {
2994 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2995 CmdArgs.push_back("-analyze");
2996 } else if (isa<MigrateJobAction>(JA)) {
2997 CmdArgs.push_back("-migrate");
2998 } else if (isa<PreprocessJobAction>(JA)) {
2999 if (Output.getType() == types::TY_Dependencies)
3000 CmdArgs.push_back("-Eonly");
3001 else {
3002 CmdArgs.push_back("-E");
3003 if (Args.hasArg(options::OPT_rewrite_objc) &&
3004 !Args.hasArg(options::OPT_g_Group))
3005 CmdArgs.push_back("-P");
3006 }
3007 } else if (isa<AssembleJobAction>(JA)) {
3008 CmdArgs.push_back("-emit-obj");
3009
3010 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3011
3012 // Also ignore explicit -force_cpusubtype_ALL option.
3013 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3014 } else if (isa<PrecompileJobAction>(JA)) {
3015 // Use PCH if the user requested it.
3016 bool UsePCH = D.CCCUsePCH;
3017
3018 if (JA.getType() == types::TY_Nothing)
3019 CmdArgs.push_back("-fsyntax-only");
3020 else if (UsePCH)
3021 CmdArgs.push_back("-emit-pch");
3022 else
3023 CmdArgs.push_back("-emit-pth");
3024 } else if (isa<VerifyPCHJobAction>(JA)) {
3025 CmdArgs.push_back("-verify-pch");
3026 } else {
3027 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3028 "Invalid action for clang tool.");
3029
3030 if (JA.getType() == types::TY_LTO_IR || JA.getType() == types::TY_LTO_BC) {
3031 CmdArgs.push_back("-flto");
3032 }
3033 if (JA.getType() == types::TY_Nothing) {
3034 CmdArgs.push_back("-fsyntax-only");
3035 } else if (JA.getType() == types::TY_LLVM_IR ||
3036 JA.getType() == types::TY_LTO_IR) {
3037 CmdArgs.push_back("-emit-llvm");
3038 } else if (JA.getType() == types::TY_LLVM_BC ||
3039 JA.getType() == types::TY_LTO_BC) {
3040 CmdArgs.push_back("-emit-llvm-bc");
3041 } else if (JA.getType() == types::TY_PP_Asm) {
3042 CmdArgs.push_back("-S");
3043 } else if (JA.getType() == types::TY_AST) {
3044 CmdArgs.push_back("-emit-pch");
3045 } else if (JA.getType() == types::TY_ModuleFile) {
3046 CmdArgs.push_back("-module-file-info");
3047 } else if (JA.getType() == types::TY_RewrittenObjC) {
3048 CmdArgs.push_back("-rewrite-objc");
3049 rewriteKind = RK_NonFragile;
3050 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3051 CmdArgs.push_back("-rewrite-objc");
3052 rewriteKind = RK_Fragile;
3053 } else {
3054 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3055 }
3056
3057 // Preserve use-list order by default when emitting bitcode, so that
3058 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3059 // same result as running passes here. For LTO, we don't need to preserve
3060 // the use-list order, since serialization to bitcode is part of the flow.
3061 if (JA.getType() == types::TY_LLVM_BC)
3062 CmdArgs.push_back("-emit-llvm-uselists");
3063 }
3064
3065 // We normally speed up the clang process a bit by skipping destructors at
3066 // exit, but when we're generating diagnostics we can rely on some of the
3067 // cleanup.
3068 if (!C.isForDiagnostics())
3069 CmdArgs.push_back("-disable-free");
3070
3071 // Disable the verification pass in -asserts builds.
3072 #ifdef NDEBUG
3073 CmdArgs.push_back("-disable-llvm-verifier");
3074 #endif
3075
3076 // Set the main file name, so that debug info works even with
3077 // -save-temps.
3078 CmdArgs.push_back("-main-file-name");
3079 CmdArgs.push_back(getBaseInputName(Args, Input));
3080
3081 // Some flags which affect the language (via preprocessor
3082 // defines).
3083 if (Args.hasArg(options::OPT_static))
3084 CmdArgs.push_back("-static-define");
3085
3086 if (isa<AnalyzeJobAction>(JA)) {
3087 // Enable region store model by default.
3088 CmdArgs.push_back("-analyzer-store=region");
3089
3090 // Treat blocks as analysis entry points.
3091 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3092
3093 CmdArgs.push_back("-analyzer-eagerly-assume");
3094
3095 // Add default argument set.
3096 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3097 CmdArgs.push_back("-analyzer-checker=core");
3098
3099 if (!IsWindowsMSVC)
3100 CmdArgs.push_back("-analyzer-checker=unix");
3101
3102 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3103 CmdArgs.push_back("-analyzer-checker=osx");
3104
3105 CmdArgs.push_back("-analyzer-checker=deadcode");
3106
3107 if (types::isCXX(Input.getType()))
3108 CmdArgs.push_back("-analyzer-checker=cplusplus");
3109
3110 // Enable the following experimental checkers for testing.
3111 CmdArgs.push_back(
3112 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3113 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3114 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3115 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3116 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3117 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3118 }
3119
3120 // Set the output format. The default is plist, for (lame) historical
3121 // reasons.
3122 CmdArgs.push_back("-analyzer-output");
3123 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3124 CmdArgs.push_back(A->getValue());
3125 else
3126 CmdArgs.push_back("plist");
3127
3128 // Disable the presentation of standard compiler warnings when
3129 // using --analyze. We only want to show static analyzer diagnostics
3130 // or frontend errors.
3131 CmdArgs.push_back("-w");
3132
3133 // Add -Xanalyzer arguments when running as analyzer.
3134 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3135 }
3136
3137 CheckCodeGenerationOptions(D, Args);
3138
3139 bool PIE = getToolChain().isPIEDefault();
3140 bool PIC = PIE || getToolChain().isPICDefault();
3141 bool IsPICLevelTwo = PIC;
3142
3143 // Android-specific defaults for PIC/PIE
3144 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
3145 switch (getToolChain().getArch()) {
3146 case llvm::Triple::arm:
3147 case llvm::Triple::armeb:
3148 case llvm::Triple::thumb:
3149 case llvm::Triple::thumbeb:
3150 case llvm::Triple::aarch64:
3151 case llvm::Triple::mips:
3152 case llvm::Triple::mipsel:
3153 case llvm::Triple::mips64:
3154 case llvm::Triple::mips64el:
3155 PIC = true; // "-fpic"
3156 break;
3157
3158 case llvm::Triple::x86:
3159 case llvm::Triple::x86_64:
3160 PIC = true; // "-fPIC"
3161 IsPICLevelTwo = true;
3162 break;
3163
3164 default:
3165 break;
3166 }
3167 }
3168
3169 // OpenBSD-specific defaults for PIE
3170 if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
3171 switch (getToolChain().getArch()) {
3172 case llvm::Triple::mips64:
3173 case llvm::Triple::mips64el:
3174 case llvm::Triple::sparcel:
3175 case llvm::Triple::x86:
3176 case llvm::Triple::x86_64:
3177 IsPICLevelTwo = false; // "-fpie"
3178 break;
3179
3180 case llvm::Triple::ppc:
3181 case llvm::Triple::sparc:
3182 case llvm::Triple::sparcv9:
3183 IsPICLevelTwo = true; // "-fPIE"
3184 break;
3185
3186 default:
3187 break;
3188 }
3189 }
3190
3191 // For the PIC and PIE flag options, this logic is different from the
3192 // legacy logic in very old versions of GCC, as that logic was just
3193 // a bug no one had ever fixed. This logic is both more rational and
3194 // consistent with GCC's new logic now that the bugs are fixed. The last
3195 // argument relating to either PIC or PIE wins, and no other argument is
3196 // used. If the last argument is any flavor of the '-fno-...' arguments,
3197 // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
3198 // at the same level.
3199 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3200 options::OPT_fpic, options::OPT_fno_pic,
3201 options::OPT_fPIE, options::OPT_fno_PIE,
3202 options::OPT_fpie, options::OPT_fno_pie);
3203 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3204 // is forced, then neither PIC nor PIE flags will have no effect.
3205 if (!getToolChain().isPICDefaultForced()) {
3206 if (LastPICArg) {
3207 Option O = LastPICArg->getOption();
3208 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3209 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3210 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3211 PIC =
3212 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3213 IsPICLevelTwo =
3214 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3215 } else {
3216 PIE = PIC = false;
3217 }
3218 }
3219 }
3220
3221 // Introduce a Darwin-specific hack. If the default is PIC but the flags
3222 // specified while enabling PIC enabled level 1 PIC, just force it back to
3223 // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
3224 // informal testing).
3225 if (PIC && getToolChain().getTriple().isOSDarwin())
3226 IsPICLevelTwo |= getToolChain().isPICDefault();
3227
3228 // Note that these flags are trump-cards. Regardless of the order w.r.t. the
3229 // PIC or PIE options above, if these show up, PIC is disabled.
3230 llvm::Triple Triple(TripleStr);
3231 if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
3232 PIC = PIE = false;
3233 if (Args.hasArg(options::OPT_static))
3234 PIC = PIE = false;
3235
3236 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3237 // This is a very special mode. It trumps the other modes, almost no one
3238 // uses it, and it isn't even valid on any OS but Darwin.
3239 if (!getToolChain().getTriple().isOSDarwin())
3240 D.Diag(diag::err_drv_unsupported_opt_for_target)
3241 << A->getSpelling() << getToolChain().getTriple().str();
3242
3243 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3244
3245 CmdArgs.push_back("-mrelocation-model");
3246 CmdArgs.push_back("dynamic-no-pic");
3247
3248 // Only a forced PIC mode can cause the actual compile to have PIC defines
3249 // etc., no flags are sufficient. This behavior was selected to closely
3250 // match that of llvm-gcc and Apple GCC before that.
3251 if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
3252 CmdArgs.push_back("-pic-level");
3253 CmdArgs.push_back("2");
3254 }
3255 } else {
3256 // Currently, LLVM only knows about PIC vs. static; the PIE differences are
3257 // handled in Clang's IRGen by the -pie-level flag.
3258 CmdArgs.push_back("-mrelocation-model");
3259 CmdArgs.push_back(PIC ? "pic" : "static");
3260
3261 if (PIC) {
3262 CmdArgs.push_back("-pic-level");
3263 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3264 if (PIE) {
3265 CmdArgs.push_back("-pie-level");
3266 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3267 }
3268 }
3269 }
3270
3271 CmdArgs.push_back("-mthread-model");
3272 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3273 CmdArgs.push_back(A->getValue());
3274 else
3275 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3276
3277 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3278
3279 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3280 options::OPT_fno_merge_all_constants))
3281 CmdArgs.push_back("-fno-merge-all-constants");
3282
3283 // LLVM Code Generator Options.
3284
3285 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3286 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3287 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3288 options::OPT_frewrite_map_file_EQ)) {
3289 CmdArgs.push_back("-frewrite-map-file");
3290 CmdArgs.push_back(A->getValue());
3291 A->claim();
3292 }
3293 }
3294
3295 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3296 StringRef v = A->getValue();
3297 CmdArgs.push_back("-mllvm");
3298 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3299 A->claim();
3300 }
3301
3302 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3303 CmdArgs.push_back("-mregparm");
3304 CmdArgs.push_back(A->getValue());
3305 }
3306
3307 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3308 options::OPT_freg_struct_return)) {
3309 if (getToolChain().getArch() != llvm::Triple::x86) {
3310 D.Diag(diag::err_drv_unsupported_opt_for_target)
3311 << A->getSpelling() << getToolChain().getTriple().str();
3312 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3313 CmdArgs.push_back("-fpcc-struct-return");
3314 } else {
3315 assert(A->getOption().matches(options::OPT_freg_struct_return));
3316 CmdArgs.push_back("-freg-struct-return");
3317 }
3318 }
3319
3320 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3321 CmdArgs.push_back("-mrtd");
3322
3323 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3324 CmdArgs.push_back("-mdisable-fp-elim");
3325 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3326 options::OPT_fno_zero_initialized_in_bss))
3327 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3328
3329 bool OFastEnabled = isOptimizationLevelFast(Args);
3330 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3331 // enabled. This alias option is being used to simplify the hasFlag logic.
3332 OptSpecifier StrictAliasingAliasOption =
3333 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3334 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3335 // doesn't do any TBAA.
3336 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3337 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3338 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3339 CmdArgs.push_back("-relaxed-aliasing");
3340 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3341 options::OPT_fno_struct_path_tbaa))
3342 CmdArgs.push_back("-no-struct-path-tbaa");
3343 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3344 false))
3345 CmdArgs.push_back("-fstrict-enums");
3346 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3347 options::OPT_fno_optimize_sibling_calls))
3348 CmdArgs.push_back("-mdisable-tail-calls");
3349
3350 // Handle segmented stacks.
3351 if (Args.hasArg(options::OPT_fsplit_stack))
3352 CmdArgs.push_back("-split-stacks");
3353
3354 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3355 // This alias option is being used to simplify the getLastArg logic.
3356 OptSpecifier FastMathAliasOption =
3357 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3358
3359 // Handle various floating point optimization flags, mapping them to the
3360 // appropriate LLVM code generation flags. The pattern for all of these is to
3361 // default off the codegen optimizations, and if any flag enables them and no
3362 // flag disables them after the flag enabling them, enable the codegen
3363 // optimization. This is complicated by several "umbrella" flags.
3364 if (Arg *A = Args.getLastArg(
3365 options::OPT_ffast_math, FastMathAliasOption,
3366 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3367 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3368 options::OPT_fno_honor_infinities))
3369 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3370 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3371 A->getOption().getID() != options::OPT_fhonor_infinities)
3372 CmdArgs.push_back("-menable-no-infs");
3373 if (Arg *A = Args.getLastArg(
3374 options::OPT_ffast_math, FastMathAliasOption,
3375 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3376 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3377 options::OPT_fno_honor_nans))
3378 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3379 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3380 A->getOption().getID() != options::OPT_fhonor_nans)
3381 CmdArgs.push_back("-menable-no-nans");
3382
3383 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3384 bool MathErrno = getToolChain().IsMathErrnoDefault();
3385 if (Arg *A =
3386 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3387 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3388 options::OPT_fno_math_errno)) {
3389 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3390 // However, turning *off* -ffast_math merely restores the toolchain default
3391 // (which may be false).
3392 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3393 A->getOption().getID() == options::OPT_ffast_math ||
3394 A->getOption().getID() == options::OPT_Ofast)
3395 MathErrno = false;
3396 else if (A->getOption().getID() == options::OPT_fmath_errno)
3397 MathErrno = true;
3398 }
3399 if (MathErrno)
3400 CmdArgs.push_back("-fmath-errno");
3401
3402 // There are several flags which require disabling very specific
3403 // optimizations. Any of these being disabled forces us to turn off the
3404 // entire set of LLVM optimizations, so collect them through all the flag
3405 // madness.
3406 bool AssociativeMath = false;
3407 if (Arg *A = Args.getLastArg(
3408 options::OPT_ffast_math, FastMathAliasOption,
3409 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3410 options::OPT_fno_unsafe_math_optimizations,
3411 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3412 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3413 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3414 A->getOption().getID() != options::OPT_fno_associative_math)
3415 AssociativeMath = true;
3416 bool ReciprocalMath = false;
3417 if (Arg *A = Args.getLastArg(
3418 options::OPT_ffast_math, FastMathAliasOption,
3419 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3420 options::OPT_fno_unsafe_math_optimizations,
3421 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3422 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3423 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3424 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3425 ReciprocalMath = true;
3426 bool SignedZeros = true;
3427 if (Arg *A = Args.getLastArg(
3428 options::OPT_ffast_math, FastMathAliasOption,
3429 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3430 options::OPT_fno_unsafe_math_optimizations,
3431 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3432 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3433 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3434 A->getOption().getID() != options::OPT_fsigned_zeros)
3435 SignedZeros = false;
3436 bool TrappingMath = true;
3437 if (Arg *A = Args.getLastArg(
3438 options::OPT_ffast_math, FastMathAliasOption,
3439 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3440 options::OPT_fno_unsafe_math_optimizations,
3441 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3442 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3443 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3444 A->getOption().getID() != options::OPT_ftrapping_math)
3445 TrappingMath = false;
3446 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3447 !TrappingMath)
3448 CmdArgs.push_back("-menable-unsafe-fp-math");
3449
3450 if (!SignedZeros)
3451 CmdArgs.push_back("-fno-signed-zeros");
3452
3453 if (ReciprocalMath)
3454 CmdArgs.push_back("-freciprocal-math");
3455
3456 // Validate and pass through -fp-contract option.
3457 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3458 options::OPT_fno_fast_math,
3459 options::OPT_ffp_contract)) {
3460 if (A->getOption().getID() == options::OPT_ffp_contract) {
3461 StringRef Val = A->getValue();
3462 if (Val == "fast" || Val == "on" || Val == "off") {
3463 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3464 } else {
3465 D.Diag(diag::err_drv_unsupported_option_argument)
3466 << A->getOption().getName() << Val;
3467 }
3468 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3469 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3470 // If fast-math is set then set the fp-contract mode to fast.
3471 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3472 }
3473 }
3474
3475 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3476
3477 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3478 // and if we find them, tell the frontend to provide the appropriate
3479 // preprocessor macros. This is distinct from enabling any optimizations as
3480 // these options induce language changes which must survive serialization
3481 // and deserialization, etc.
3482 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3483 options::OPT_fno_fast_math))
3484 if (!A->getOption().matches(options::OPT_fno_fast_math))
3485 CmdArgs.push_back("-ffast-math");
3486 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3487 options::OPT_fno_fast_math))
3488 if (A->getOption().matches(options::OPT_ffinite_math_only))
3489 CmdArgs.push_back("-ffinite-math-only");
3490
3491 // Decide whether to use verbose asm. Verbose assembly is the default on
3492 // toolchains which have the integrated assembler on by default.
3493 bool IsIntegratedAssemblerDefault =
3494 getToolChain().IsIntegratedAssemblerDefault();
3495 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3496 IsIntegratedAssemblerDefault) ||
3497 Args.hasArg(options::OPT_dA))
3498 CmdArgs.push_back("-masm-verbose");
3499
3500 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3501 IsIntegratedAssemblerDefault))
3502 CmdArgs.push_back("-no-integrated-as");
3503
3504 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3505 CmdArgs.push_back("-mdebug-pass");
3506 CmdArgs.push_back("Structure");
3507 }
3508 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3509 CmdArgs.push_back("-mdebug-pass");
3510 CmdArgs.push_back("Arguments");
3511 }
3512
3513 // Enable -mconstructor-aliases except on darwin, where we have to
3514 // work around a linker bug; see <rdar://problem/7651567>.
3515 if (!getToolChain().getTriple().isOSDarwin())
3516 CmdArgs.push_back("-mconstructor-aliases");
3517
3518 // Darwin's kernel doesn't support guard variables; just die if we
3519 // try to use them.
3520 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3521 CmdArgs.push_back("-fforbid-guard-variables");
3522
3523 if (Args.hasArg(options::OPT_mms_bitfields)) {
3524 CmdArgs.push_back("-mms-bitfields");
3525 }
3526
3527 // This is a coarse approximation of what llvm-gcc actually does, both
3528 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3529 // complicated ways.
3530 bool AsynchronousUnwindTables =
3531 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3532 options::OPT_fno_asynchronous_unwind_tables,
3533 (getToolChain().IsUnwindTablesDefault() ||
3534 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3535 !KernelOrKext);
3536 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3537 AsynchronousUnwindTables))
3538 CmdArgs.push_back("-munwind-tables");
3539
3540 getToolChain().addClangTargetOptions(Args, CmdArgs);
3541
3542 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3543 CmdArgs.push_back("-mlimit-float-precision");
3544 CmdArgs.push_back(A->getValue());
3545 }
3546
3547 // FIXME: Handle -mtune=.
3548 (void)Args.hasArg(options::OPT_mtune_EQ);
3549
3550 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3551 CmdArgs.push_back("-mcode-model");
3552 CmdArgs.push_back(A->getValue());
3553 }
3554
3555 // Add the target cpu
3556 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3557 if (!CPU.empty()) {
3558 CmdArgs.push_back("-target-cpu");
3559 CmdArgs.push_back(Args.MakeArgString(CPU));
3560 }
3561
3562 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3563 CmdArgs.push_back("-mfpmath");
3564 CmdArgs.push_back(A->getValue());
3565 }
3566
3567 // Add the target features
3568 getTargetFeatures(D, Triple, Args, CmdArgs, false);
3569
3570 // Add target specific flags.
3571 switch (getToolChain().getArch()) {
3572 default:
3573 break;
3574
3575 case llvm::Triple::arm:
3576 case llvm::Triple::armeb:
3577 case llvm::Triple::thumb:
3578 case llvm::Triple::thumbeb:
3579 AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3580 break;
3581
3582 case llvm::Triple::aarch64:
3583 case llvm::Triple::aarch64_be:
3584 AddAArch64TargetArgs(Args, CmdArgs);
3585 break;
3586
3587 case llvm::Triple::mips:
3588 case llvm::Triple::mipsel:
3589 case llvm::Triple::mips64:
3590 case llvm::Triple::mips64el:
3591 AddMIPSTargetArgs(Args, CmdArgs);
3592 break;
3593
3594 case llvm::Triple::ppc:
3595 case llvm::Triple::ppc64:
3596 case llvm::Triple::ppc64le:
3597 AddPPCTargetArgs(Args, CmdArgs);
3598 break;
3599
3600 case llvm::Triple::sparc:
3601 case llvm::Triple::sparcel:
3602 case llvm::Triple::sparcv9:
3603 AddSparcTargetArgs(Args, CmdArgs);
3604 break;
3605
3606 case llvm::Triple::x86:
3607 case llvm::Triple::x86_64:
3608 AddX86TargetArgs(Args, CmdArgs);
3609 break;
3610
3611 case llvm::Triple::hexagon:
3612 AddHexagonTargetArgs(Args, CmdArgs);
3613 break;
3614 }
3615
3616 // Add clang-cl arguments.
3617 if (getToolChain().getDriver().IsCLMode())
3618 AddClangCLArgs(Args, CmdArgs);
3619
3620 // Pass the linker version in use.
3621 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3622 CmdArgs.push_back("-target-linker-version");
3623 CmdArgs.push_back(A->getValue());
3624 }
3625
3626 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3627 CmdArgs.push_back("-momit-leaf-frame-pointer");
3628
3629 // Explicitly error on some things we know we don't support and can't just
3630 // ignore.
3631 types::ID InputType = Input.getType();
3632 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3633 Arg *Unsupported;
3634 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
3635 getToolChain().getArch() == llvm::Triple::x86) {
3636 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3637 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3638 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3639 << Unsupported->getOption().getName();
3640 }
3641 }
3642
3643 Args.AddAllArgs(CmdArgs, options::OPT_v);
3644 Args.AddLastArg(CmdArgs, options::OPT_H);
3645 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3646 CmdArgs.push_back("-header-include-file");
3647 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3648 : "-");
3649 }
3650 Args.AddLastArg(CmdArgs, options::OPT_P);
3651 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3652
3653 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3654 CmdArgs.push_back("-diagnostic-log-file");
3655 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3656 : "-");
3657 }
3658
3659 // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3660 // are preserved, all other debug options are substituted with "-g".
3661 Args.ClaimAllArgs(options::OPT_g_Group);
3662 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3663 if (A->getOption().matches(options::OPT_gline_tables_only) ||
3664 A->getOption().matches(options::OPT_g1)) {
3665 // FIXME: we should support specifying dwarf version with
3666 // -gline-tables-only.
3667 CmdArgs.push_back("-gline-tables-only");
3668 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3669 const llvm::Triple &Triple = getToolChain().getTriple();
3670 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3671 Triple.getOS() == llvm::Triple::FreeBSD ||
3672 Triple.getOS() == llvm::Triple::Solaris)
3673 CmdArgs.push_back("-gdwarf-2");
3674 } else if (A->getOption().matches(options::OPT_gdwarf_2))
3675 CmdArgs.push_back("-gdwarf-2");
3676 else if (A->getOption().matches(options::OPT_gdwarf_3))
3677 CmdArgs.push_back("-gdwarf-3");
3678 else if (A->getOption().matches(options::OPT_gdwarf_4))
3679 CmdArgs.push_back("-gdwarf-4");
3680 else if (!A->getOption().matches(options::OPT_g0) &&
3681 !A->getOption().matches(options::OPT_ggdb0)) {
3682 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3683 const llvm::Triple &Triple = getToolChain().getTriple();
3684 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3685 Triple.getOS() == llvm::Triple::FreeBSD ||
3686 Triple.getOS() == llvm::Triple::Solaris)
3687 CmdArgs.push_back("-gdwarf-2");
3688 else
3689 CmdArgs.push_back("-g");
3690 }
3691 }
3692
3693 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3694 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3695 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3696 /*Default*/ true))
3697 CmdArgs.push_back("-dwarf-column-info");
3698
3699 // FIXME: Move backend command line options to the module.
3700 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3701 // splitting and extraction.
3702 // FIXME: Currently only works on Linux.
3703 if (getToolChain().getTriple().isOSLinux() &&
3704 Args.hasArg(options::OPT_gsplit_dwarf)) {
3705 CmdArgs.push_back("-g");
3706 CmdArgs.push_back("-backend-option");
3707 CmdArgs.push_back("-split-dwarf=Enable");
3708 }
3709
3710 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3711 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3712 CmdArgs.push_back("-backend-option");
3713 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3714 }
3715
3716 // -gdwarf-aranges turns on the emission of the aranges section in the
3717 // backend.
3718 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3719 CmdArgs.push_back("-backend-option");
3720 CmdArgs.push_back("-generate-arange-section");
3721 }
3722
3723 if (Args.hasFlag(options::OPT_fdebug_types_section,
3724 options::OPT_fno_debug_types_section, false)) {
3725 CmdArgs.push_back("-backend-option");
3726 CmdArgs.push_back("-generate-type-units");
3727 }
3728
3729 // CloudABI uses -ffunction-sections and -fdata-sections by default.
3730 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
3731
3732 if (Args.hasFlag(options::OPT_ffunction_sections,
3733 options::OPT_fno_function_sections, UseSeparateSections)) {
3734 CmdArgs.push_back("-ffunction-sections");
3735 }
3736
3737 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3738 UseSeparateSections)) {
3739 CmdArgs.push_back("-fdata-sections");
3740 }
3741
3742 if (!Args.hasFlag(options::OPT_funique_section_names,
3743 options::OPT_fno_unique_section_names, true))
3744 CmdArgs.push_back("-fno-unique-section-names");
3745
3746 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3747
3748 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3749
3750 // Pass options for controlling the default header search paths.
3751 if (Args.hasArg(options::OPT_nostdinc)) {
3752 CmdArgs.push_back("-nostdsysteminc");
3753 CmdArgs.push_back("-nobuiltininc");
3754 } else {
3755 if (Args.hasArg(options::OPT_nostdlibinc))
3756 CmdArgs.push_back("-nostdsysteminc");
3757 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3758 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3759 }
3760
3761 // Pass the path to compiler resource files.
3762 CmdArgs.push_back("-resource-dir");
3763 CmdArgs.push_back(D.ResourceDir.c_str());
3764
3765 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3766
3767 bool ARCMTEnabled = false;
3768 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3769 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3770 options::OPT_ccc_arcmt_modify,
3771 options::OPT_ccc_arcmt_migrate)) {
3772 ARCMTEnabled = true;
3773 switch (A->getOption().getID()) {
3774 default:
3775 llvm_unreachable("missed a case");
3776 case options::OPT_ccc_arcmt_check:
3777 CmdArgs.push_back("-arcmt-check");
3778 break;
3779 case options::OPT_ccc_arcmt_modify:
3780 CmdArgs.push_back("-arcmt-modify");
3781 break;
3782 case options::OPT_ccc_arcmt_migrate:
3783 CmdArgs.push_back("-arcmt-migrate");
3784 CmdArgs.push_back("-mt-migrate-directory");
3785 CmdArgs.push_back(A->getValue());
3786
3787 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3788 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3789 break;
3790 }
3791 }
3792 } else {
3793 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3794 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3795 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3796 }
3797
3798 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3799 if (ARCMTEnabled) {
3800 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
3801 << "-ccc-arcmt-migrate";
3802 }
3803 CmdArgs.push_back("-mt-migrate-directory");
3804 CmdArgs.push_back(A->getValue());
3805
3806 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3807 options::OPT_objcmt_migrate_subscripting,
3808 options::OPT_objcmt_migrate_property)) {
3809 // None specified, means enable them all.
3810 CmdArgs.push_back("-objcmt-migrate-literals");
3811 CmdArgs.push_back("-objcmt-migrate-subscripting");
3812 CmdArgs.push_back("-objcmt-migrate-property");
3813 } else {
3814 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3815 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3816 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3817 }
3818 } else {
3819 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3820 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3821 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3822 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3823 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3824 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3825 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3826 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3827 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3828 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3829 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3830 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3831 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3832 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3833 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3834 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3835 }
3836
3837 // Add preprocessing options like -I, -D, etc. if we are using the
3838 // preprocessor.
3839 //
3840 // FIXME: Support -fpreprocessed
3841 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3842 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3843
3844 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3845 // that "The compiler can only warn and ignore the option if not recognized".
3846 // When building with ccache, it will pass -D options to clang even on
3847 // preprocessed inputs and configure concludes that -fPIC is not supported.
3848 Args.ClaimAllArgs(options::OPT_D);
3849
3850 // Manually translate -O4 to -O3; let clang reject others.
3851 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3852 if (A->getOption().matches(options::OPT_O4)) {
3853 CmdArgs.push_back("-O3");
3854 D.Diag(diag::warn_O4_is_O3);
3855 } else {
3856 A->render(Args, CmdArgs);
3857 }
3858 }
3859
3860 // Warn about ignored options to clang.
3861 for (const Arg *A :
3862 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3863 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3864 }
3865
3866 claimNoWarnArgs(Args);
3867
3868 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3869 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3870 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3871 CmdArgs.push_back("-pedantic");
3872 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3873 Args.AddLastArg(CmdArgs, options::OPT_w);
3874
3875 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3876 // (-ansi is equivalent to -std=c89 or -std=c++98).
3877 //
3878 // If a std is supplied, only add -trigraphs if it follows the
3879 // option.
3880 bool ImplyVCPPCXXVer = false;
3881 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3882 if (Std->getOption().matches(options::OPT_ansi))
3883 if (types::isCXX(InputType))
3884 CmdArgs.push_back("-std=c++98");
3885 else
3886 CmdArgs.push_back("-std=c89");
3887 else
3888 Std->render(Args, CmdArgs);
3889
3890 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3891 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3892 options::OPT_ftrigraphs,
3893 options::OPT_fno_trigraphs))
3894 if (A != Std)
3895 A->render(Args, CmdArgs);
3896 } else {
3897 // Honor -std-default.
3898 //
3899 // FIXME: Clang doesn't correctly handle -std= when the input language
3900 // doesn't match. For the time being just ignore this for C++ inputs;
3901 // eventually we want to do all the standard defaulting here instead of
3902 // splitting it between the driver and clang -cc1.
3903 if (!types::isCXX(InputType))
3904 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3905 /*Joined=*/true);
3906 else if (IsWindowsMSVC)
3907 ImplyVCPPCXXVer = true;
3908
3909 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3910 options::OPT_fno_trigraphs);
3911 }
3912
3913 // GCC's behavior for -Wwrite-strings is a bit strange:
3914 // * In C, this "warning flag" changes the types of string literals from
3915 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3916 // for the discarded qualifier.
3917 // * In C++, this is just a normal warning flag.
3918 //
3919 // Implementing this warning correctly in C is hard, so we follow GCC's
3920 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3921 // a non-const char* in C, rather than using this crude hack.
3922 if (!types::isCXX(InputType)) {
3923 // FIXME: This should behave just like a warning flag, and thus should also
3924 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3925 Arg *WriteStrings =
3926 Args.getLastArg(options::OPT_Wwrite_strings,
3927 options::OPT_Wno_write_strings, options::OPT_w);
3928 if (WriteStrings &&
3929 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3930 CmdArgs.push_back("-fconst-strings");
3931 }
3932
3933 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3934 // during C++ compilation, which it is by default. GCC keeps this define even
3935 // in the presence of '-w', match this behavior bug-for-bug.
3936 if (types::isCXX(InputType) &&
3937 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3938 true)) {
3939 CmdArgs.push_back("-fdeprecated-macro");
3940 }
3941
3942 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3943 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3944 if (Asm->getOption().matches(options::OPT_fasm))
3945 CmdArgs.push_back("-fgnu-keywords");
3946 else
3947 CmdArgs.push_back("-fno-gnu-keywords");
3948 }
3949
3950 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3951 CmdArgs.push_back("-fno-dwarf-directory-asm");
3952
3953 if (ShouldDisableAutolink(Args, getToolChain()))
3954 CmdArgs.push_back("-fno-autolink");
3955
3956 // Add in -fdebug-compilation-dir if necessary.
3957 addDebugCompDirArg(Args, CmdArgs);
3958
3959 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3960 options::OPT_ftemplate_depth_EQ)) {
3961 CmdArgs.push_back("-ftemplate-depth");
3962 CmdArgs.push_back(A->getValue());
3963 }
3964
3965 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3966 CmdArgs.push_back("-foperator-arrow-depth");
3967 CmdArgs.push_back(A->getValue());
3968 }
3969
3970 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3971 CmdArgs.push_back("-fconstexpr-depth");
3972 CmdArgs.push_back(A->getValue());
3973 }
3974
3975 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3976 CmdArgs.push_back("-fconstexpr-steps");
3977 CmdArgs.push_back(A->getValue());
3978 }
3979
3980 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3981 CmdArgs.push_back("-fbracket-depth");
3982 CmdArgs.push_back(A->getValue());
3983 }
3984
3985 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3986 options::OPT_Wlarge_by_value_copy_def)) {
3987 if (A->getNumValues()) {
3988 StringRef bytes = A->getValue();
3989 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3990 } else
3991 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3992 }
3993
3994 if (Args.hasArg(options::OPT_relocatable_pch))
3995 CmdArgs.push_back("-relocatable-pch");
3996
3997 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3998 CmdArgs.push_back("-fconstant-string-class");
3999 CmdArgs.push_back(A->getValue());
4000 }
4001
4002 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4003 CmdArgs.push_back("-ftabstop");
4004 CmdArgs.push_back(A->getValue());
4005 }
4006
4007 CmdArgs.push_back("-ferror-limit");
4008 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4009 CmdArgs.push_back(A->getValue());
4010 else
4011 CmdArgs.push_back("19");
4012
4013 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4014 CmdArgs.push_back("-fmacro-backtrace-limit");
4015 CmdArgs.push_back(A->getValue());
4016 }
4017
4018 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4019 CmdArgs.push_back("-ftemplate-backtrace-limit");
4020 CmdArgs.push_back(A->getValue());
4021 }
4022
4023 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4024 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4025 CmdArgs.push_back(A->getValue());
4026 }
4027
4028 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4029 CmdArgs.push_back("-fspell-checking-limit");
4030 CmdArgs.push_back(A->getValue());
4031 }
4032
4033 // Pass -fmessage-length=.
4034 CmdArgs.push_back("-fmessage-length");
4035 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4036 CmdArgs.push_back(A->getValue());
4037 } else {
4038 // If -fmessage-length=N was not specified, determine whether this is a
4039 // terminal and, if so, implicitly define -fmessage-length appropriately.
4040 unsigned N = llvm::sys::Process::StandardErrColumns();
4041 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4042 }
4043
4044 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4045 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4046 options::OPT_fvisibility_ms_compat)) {
4047 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4048 CmdArgs.push_back("-fvisibility");
4049 CmdArgs.push_back(A->getValue());
4050 } else {
4051 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4052 CmdArgs.push_back("-fvisibility");
4053 CmdArgs.push_back("hidden");
4054 CmdArgs.push_back("-ftype-visibility");
4055 CmdArgs.push_back("default");
4056 }
4057 }
4058
4059 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4060
4061 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4062
4063 // -fhosted is default.
4064 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4065 KernelOrKext)
4066 CmdArgs.push_back("-ffreestanding");
4067
4068 // Forward -f (flag) options which we can pass directly.
4069 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4070 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4071 Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
4072 Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
4073 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4074 // AltiVec-like language extensions aren't relevant for assembling.
4075 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4076 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4077 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4078 }
4079 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4080 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4081
4082 // Forward flags for OpenMP
4083 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4084 options::OPT_fno_openmp, false))
4085 switch (getOpenMPRuntime(getToolChain(), Args)) {
4086 case OMPRT_OMP:
4087 case OMPRT_IOMP5:
4088 // Clang can generate useful OpenMP code for these two runtime libraries.
4089 CmdArgs.push_back("-fopenmp");
4090
4091 // If no option regarding the use of TLS in OpenMP codegeneration is
4092 // given, decide a default based on the target. Otherwise rely on the
4093 // options and pass the right information to the frontend.
4094 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4095 options::OPT_fnoopenmp_use_tls,
4096 getToolChain().getArch() == llvm::Triple::ppc ||
4097 getToolChain().getArch() == llvm::Triple::ppc64 ||
4098 getToolChain().getArch() == llvm::Triple::ppc64le))
4099 CmdArgs.push_back("-fnoopenmp-use-tls");
4100 break;
4101 default:
4102 // By default, if Clang doesn't know how to generate useful OpenMP code
4103 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4104 // down to the actual compilation.
4105 // FIXME: It would be better to have a mode which *only* omits IR
4106 // generation based on the OpenMP support so that we get consistent
4107 // semantic analysis, etc.
4108 break;
4109 }
4110
4111 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4112 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4113
4114 // Report an error for -faltivec on anything other than PowerPC.
4115 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4116 const llvm::Triple::ArchType Arch = getToolChain().getArch();
4117 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4118 Arch == llvm::Triple::ppc64le))
4119 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4120 << "ppc/ppc64/ppc64le";
4121 }
4122
4123 // -fzvector is incompatible with -faltivec.
4124 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4125 if (Args.hasArg(options::OPT_faltivec))
4126 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4127 << "-faltivec";
4128
4129 if (getToolChain().SupportsProfiling())
4130 Args.AddLastArg(CmdArgs, options::OPT_pg);
4131
4132 // -flax-vector-conversions is default.
4133 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4134 options::OPT_fno_lax_vector_conversions))
4135 CmdArgs.push_back("-fno-lax-vector-conversions");
4136
4137 if (Args.getLastArg(options::OPT_fapple_kext))
4138 CmdArgs.push_back("-fapple-kext");
4139
4140 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4141 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4142 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4143 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4144 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4145
4146 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4147 CmdArgs.push_back("-ftrapv-handler");
4148 CmdArgs.push_back(A->getValue());
4149 }
4150
4151 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4152
4153 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4154 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4155 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4156 if (A->getOption().matches(options::OPT_fwrapv))
4157 CmdArgs.push_back("-fwrapv");
4158 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4159 options::OPT_fno_strict_overflow)) {
4160 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4161 CmdArgs.push_back("-fwrapv");
4162 }
4163
4164 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4165 options::OPT_fno_reroll_loops))
4166 if (A->getOption().matches(options::OPT_freroll_loops))
4167 CmdArgs.push_back("-freroll-loops");
4168
4169 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4170 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4171 options::OPT_fno_unroll_loops);
4172
4173 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4174
4175 // -stack-protector=0 is default.
4176 unsigned StackProtectorLevel = 0;
4177 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4178 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4179 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4180 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4181 Args.ClaimAllArgs(options::OPT_fstack_protector);
4182 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4183 options::OPT_fstack_protector_all,
4184 options::OPT_fstack_protector_strong,
4185 options::OPT_fstack_protector)) {
4186 if (A->getOption().matches(options::OPT_fstack_protector)) {
4187 StackProtectorLevel = std::max<unsigned>(
4188 LangOptions::SSPOn,
4189 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4190 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4191 StackProtectorLevel = LangOptions::SSPStrong;
4192 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4193 StackProtectorLevel = LangOptions::SSPReq;
4194 } else {
4195 StackProtectorLevel =
4196 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4197 }
4198 if (StackProtectorLevel) {
4199 CmdArgs.push_back("-stack-protector");
4200 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4201 }
4202
4203 // --param ssp-buffer-size=
4204 for (const Arg *A : Args.filtered(options::OPT__param)) {
4205 StringRef Str(A->getValue());
4206 if (Str.startswith("ssp-buffer-size=")) {
4207 if (StackProtectorLevel) {
4208 CmdArgs.push_back("-stack-protector-buffer-size");
4209 // FIXME: Verify the argument is a valid integer.
4210 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4211 }
4212 A->claim();
4213 }
4214 }
4215
4216 // Translate -mstackrealign
4217 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4218 false)) {
4219 CmdArgs.push_back("-backend-option");
4220 CmdArgs.push_back("-force-align-stack");
4221 }
4222 if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
4223 false)) {
4224 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4225 }
4226
4227 if (Args.hasArg(options::OPT_mstack_alignment)) {
4228 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4229 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4230 }
4231
4232 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4233 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4234
4235 if (!Size.empty())
4236 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4237 else
4238 CmdArgs.push_back("-mstack-probe-size=0");
4239 }
4240
4241 if (getToolChain().getArch() == llvm::Triple::aarch64 ||
4242 getToolChain().getArch() == llvm::Triple::aarch64_be)
4243 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4244
4245 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4246 options::OPT_mno_restrict_it)) {
4247 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4248 CmdArgs.push_back("-backend-option");
4249 CmdArgs.push_back("-arm-restrict-it");
4250 } else {
4251 CmdArgs.push_back("-backend-option");
4252 CmdArgs.push_back("-arm-no-restrict-it");
4253 }
4254 } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
4255 TT.getArch() == llvm::Triple::thumb)) {
4256 // Windows on ARM expects restricted IT blocks
4257 CmdArgs.push_back("-backend-option");
4258 CmdArgs.push_back("-arm-restrict-it");
4259 }
4260
4261 // Forward -f options with positive and negative forms; we translate
4262 // these by hand.
4263 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4264 StringRef fname = A->getValue();
4265 if (!llvm::sys::fs::exists(fname))
4266 D.Diag(diag::err_drv_no_such_file) << fname;
4267 else
4268 A->render(Args, CmdArgs);
4269 }
4270
4271 if (Args.hasArg(options::OPT_mkernel)) {
4272 if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
4273 CmdArgs.push_back("-fapple-kext");
4274 if (!Args.hasArg(options::OPT_fbuiltin))
4275 CmdArgs.push_back("-fno-builtin");
4276 Args.ClaimAllArgs(options::OPT_fno_builtin);
4277 }
4278 // -fbuiltin is default.
4279 else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
4280 CmdArgs.push_back("-fno-builtin");
4281
4282 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4283 options::OPT_fno_assume_sane_operator_new))
4284 CmdArgs.push_back("-fno-assume-sane-operator-new");
4285
4286 // -fblocks=0 is default.
4287 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4288 getToolChain().IsBlocksDefault()) ||
4289 (Args.hasArg(options::OPT_fgnu_runtime) &&
4290 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4291 !Args.hasArg(options::OPT_fno_blocks))) {
4292 CmdArgs.push_back("-fblocks");
4293
4294 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4295 !getToolChain().hasBlocksRuntime())
4296 CmdArgs.push_back("-fblocks-runtime-optional");
4297 }
4298
4299 // -fmodules enables the use of precompiled modules (off by default).
4300 // Users can pass -fno-cxx-modules to turn off modules support for
4301 // C++/Objective-C++ programs.
4302 bool HaveModules = false;
4303 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4304 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4305 options::OPT_fno_cxx_modules, true);
4306 if (AllowedInCXX || !types::isCXX(InputType)) {
4307 CmdArgs.push_back("-fmodules");
4308 HaveModules = true;
4309 }
4310 }
4311
4312 // -fmodule-maps enables implicit reading of module map files. By default,
4313 // this is enabled if we are using precompiled modules.
4314 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4315 options::OPT_fno_implicit_module_maps, HaveModules)) {
4316 CmdArgs.push_back("-fimplicit-module-maps");
4317 }
4318
4319 // -fmodules-decluse checks that modules used are declared so (off by
4320 // default).
4321 if (Args.hasFlag(options::OPT_fmodules_decluse,
4322 options::OPT_fno_modules_decluse, false)) {
4323 CmdArgs.push_back("-fmodules-decluse");
4324 }
4325
4326 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4327 // all #included headers are part of modules.
4328 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4329 options::OPT_fno_modules_strict_decluse, false)) {
4330 CmdArgs.push_back("-fmodules-strict-decluse");
4331 }
4332
4333 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4334 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4335 options::OPT_fno_implicit_modules)) {
4336 CmdArgs.push_back("-fno-implicit-modules");
4337 }
4338
4339 // -fmodule-name specifies the module that is currently being built (or
4340 // used for header checking by -fmodule-maps).
4341 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4342
4343 // -fmodule-map-file can be used to specify files containing module
4344 // definitions.
4345 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4346
4347 // -fmodule-file can be used to specify files containing precompiled modules.
4348 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4349
4350 // -fmodule-cache-path specifies where our implicitly-built module files
4351 // should be written.
4352 SmallString<128> Path;
4353 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4354 Path = A->getValue();
4355 if (HaveModules) {
4356 if (C.isForDiagnostics()) {
4357 // When generating crash reports, we want to emit the modules along with
4358 // the reproduction sources, so we ignore any provided module path.
4359 Path = Output.getFilename();
4360 llvm::sys::path::replace_extension(Path, ".cache");
4361 llvm::sys::path::append(Path, "modules");
4362 } else if (Path.empty()) {
4363 // No module path was provided: use the default.
4364 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4365 llvm::sys::path::append(Path, "org.llvm.clang.");
4366 appendUserToPath(Path);
4367 llvm::sys::path::append(Path, "ModuleCache");
4368 }
4369 const char Arg[] = "-fmodules-cache-path=";
4370 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4371 CmdArgs.push_back(Args.MakeArgString(Path));
4372 }
4373
4374 // When building modules and generating crashdumps, we need to dump a module
4375 // dependency VFS alongside the output.
4376 if (HaveModules && C.isForDiagnostics()) {
4377 SmallString<128> VFSDir(Output.getFilename());
4378 llvm::sys::path::replace_extension(VFSDir, ".cache");
4379 // Add the cache directory as a temp so the crash diagnostics pick it up.
4380 C.addTempFile(Args.MakeArgString(VFSDir));
4381
4382 llvm::sys::path::append(VFSDir, "vfs");
4383 CmdArgs.push_back("-module-dependency-dir");
4384 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4385 }
4386
4387 if (HaveModules)
4388 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4389
4390 // Pass through all -fmodules-ignore-macro arguments.
4391 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4392 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4393 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4394
4395 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4396
4397 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4398 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4399 D.Diag(diag::err_drv_argument_not_allowed_with)
4400 << A->getAsString(Args) << "-fbuild-session-timestamp";
4401
4402 llvm::sys::fs::file_status Status;
4403 if (llvm::sys::fs::status(A->getValue(), Status))
4404 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4405 CmdArgs.push_back(Args.MakeArgString(
4406 "-fbuild-session-timestamp=" +
4407 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4408 }
4409
4410 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4411 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4412 options::OPT_fbuild_session_file))
4413 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4414
4415 Args.AddLastArg(CmdArgs,
4416 options::OPT_fmodules_validate_once_per_build_session);
4417 }
4418
4419 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4420
4421 // -faccess-control is default.
4422 if (Args.hasFlag(options::OPT_fno_access_control,
4423 options::OPT_faccess_control, false))
4424 CmdArgs.push_back("-fno-access-control");
4425
4426 // -felide-constructors is the default.
4427 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4428 options::OPT_felide_constructors, false))
4429 CmdArgs.push_back("-fno-elide-constructors");
4430
4431 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4432
4433 if (KernelOrKext || (types::isCXX(InputType) &&
4434 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4435 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4436 CmdArgs.push_back("-fno-rtti");
4437
4438 // -fshort-enums=0 is default for all architectures except Hexagon.
4439 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4440 getToolChain().getArch() == llvm::Triple::hexagon))
4441 CmdArgs.push_back("-fshort-enums");
4442
4443 // -fsigned-char is default.
4444 if (Arg *A = Args.getLastArg(
4445 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4446 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4447 if (A->getOption().matches(options::OPT_funsigned_char) ||
4448 A->getOption().matches(options::OPT_fno_signed_char)) {
4449 CmdArgs.push_back("-fno-signed-char");
4450 }
4451 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4452 CmdArgs.push_back("-fno-signed-char");
4453 }
4454
4455 // -fuse-cxa-atexit is default.
4456 if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
4457 options::OPT_fno_use_cxa_atexit,
4458 !IsWindowsCygnus && !IsWindowsGNU &&
4459 getToolChain().getArch() != llvm::Triple::hexagon &&
4460 getToolChain().getArch() != llvm::Triple::xcore) ||
4461 KernelOrKext)
4462 CmdArgs.push_back("-fno-use-cxa-atexit");
4463
4464 // -fms-extensions=0 is default.
4465 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4466 IsWindowsMSVC))
4467 CmdArgs.push_back("-fms-extensions");
4468
4469 // -fno-use-line-directives is default.
4470 if (Args.hasFlag(options::OPT_fuse_line_directives,
4471 options::OPT_fno_use_line_directives, false))
4472 CmdArgs.push_back("-fuse-line-directives");
4473
4474 // -fms-compatibility=0 is default.
4475 if (Args.hasFlag(options::OPT_fms_compatibility,
4476 options::OPT_fno_ms_compatibility,
4477 (IsWindowsMSVC &&
4478 Args.hasFlag(options::OPT_fms_extensions,
4479 options::OPT_fno_ms_extensions, true))))
4480 CmdArgs.push_back("-fms-compatibility");
4481
4482 // -fms-compatibility-version=18.00 is default.
4483 VersionTuple MSVT = visualstudio::getMSVCVersion(
4484 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4485 if (!MSVT.empty())
4486 CmdArgs.push_back(
4487 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4488
4489 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4490 if (ImplyVCPPCXXVer) {
4491 if (IsMSVC2015Compatible)
4492 CmdArgs.push_back("-std=c++14");
4493 else
4494 CmdArgs.push_back("-std=c++11");
4495 }
4496
4497 // -fno-borland-extensions is default.
4498 if (Args.hasFlag(options::OPT_fborland_extensions,
4499 options::OPT_fno_borland_extensions, false))
4500 CmdArgs.push_back("-fborland-extensions");
4501
4502 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4503 // than 19.
4504 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4505 options::OPT_fno_threadsafe_statics,
4506 !IsWindowsMSVC || IsMSVC2015Compatible))
4507 CmdArgs.push_back("-fno-threadsafe-statics");
4508
4509 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4510 // needs it.
4511 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4512 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4513 CmdArgs.push_back("-fdelayed-template-parsing");
4514
4515 // -fgnu-keywords default varies depending on language; only pass if
4516 // specified.
4517 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4518 options::OPT_fno_gnu_keywords))
4519 A->render(Args, CmdArgs);
4520
4521 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4522 false))
4523 CmdArgs.push_back("-fgnu89-inline");
4524
4525 if (Args.hasArg(options::OPT_fno_inline))
4526 CmdArgs.push_back("-fno-inline");
4527
4528 if (Args.hasArg(options::OPT_fno_inline_functions))
4529 CmdArgs.push_back("-fno-inline-functions");
4530
4531 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4532
4533 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
4534 // legacy is the default. Except for deployment taget of 10.5,
4535 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
4536 // gets ignored silently.
4537 if (objcRuntime.isNonFragile()) {
4538 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4539 options::OPT_fno_objc_legacy_dispatch,
4540 objcRuntime.isLegacyDispatchDefaultForArch(
4541 getToolChain().getArch()))) {
4542 if (getToolChain().UseObjCMixedDispatch())
4543 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4544 else
4545 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4546 }
4547 }
4548
4549 // When ObjectiveC legacy runtime is in effect on MacOSX,
4550 // turn on the option to do Array/Dictionary subscripting
4551 // by default.
4552 if (getToolChain().getArch() == llvm::Triple::x86 &&
4553 getToolChain().getTriple().isMacOSX() &&
4554 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
4555 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
4556 objcRuntime.isNeXTFamily())
4557 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4558
4559 // -fencode-extended-block-signature=1 is default.
4560 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
4561 CmdArgs.push_back("-fencode-extended-block-signature");
4562 }
4563
4564 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4565 // NOTE: This logic is duplicated in ToolChains.cpp.
4566 bool ARC = isObjCAutoRefCount(Args);
4567 if (ARC) {
4568 getToolChain().CheckObjCARC();
4569
4570 CmdArgs.push_back("-fobjc-arc");
4571
4572 // FIXME: It seems like this entire block, and several around it should be
4573 // wrapped in isObjC, but for now we just use it here as this is where it
4574 // was being used previously.
4575 if (types::isCXX(InputType) && types::isObjC(InputType)) {
4576 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4577 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4578 else
4579 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4580 }
4581
4582 // Allow the user to enable full exceptions code emission.
4583 // We define off for Objective-CC, on for Objective-C++.
4584 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4585 options::OPT_fno_objc_arc_exceptions,
4586 /*default*/ types::isCXX(InputType)))
4587 CmdArgs.push_back("-fobjc-arc-exceptions");
4588 }
4589
4590 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4591 // rewriter.
4592 if (rewriteKind != RK_None)
4593 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4594
4595 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4596 // takes precedence.
4597 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4598 if (!GCArg)
4599 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4600 if (GCArg) {
4601 if (ARC) {
4602 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
4603 } else if (getToolChain().SupportsObjCGC()) {
4604 GCArg->render(Args, CmdArgs);
4605 } else {
4606 // FIXME: We should move this to a hard error.
4607 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
4608 }
4609 }
4610
4611 if (Args.hasFlag(options::OPT_fapplication_extension,
4612 options::OPT_fno_application_extension, false))
4613 CmdArgs.push_back("-fapplication-extension");
4614
4615 // Handle GCC-style exception args.
4616 if (!C.getDriver().IsCLMode())
4617 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
4618 CmdArgs);
4619
4620 if (getToolChain().UseSjLjExceptions())
4621 CmdArgs.push_back("-fsjlj-exceptions");
4622
4623 // C++ "sane" operator new.
4624 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4625 options::OPT_fno_assume_sane_operator_new))
4626 CmdArgs.push_back("-fno-assume-sane-operator-new");
4627
4628 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4629 // most platforms.
4630 if (Args.hasFlag(options::OPT_fsized_deallocation,
4631 options::OPT_fno_sized_deallocation, false))
4632 CmdArgs.push_back("-fsized-deallocation");
4633
4634 // -fconstant-cfstrings is default, and may be subject to argument translation
4635 // on Darwin.
4636 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4637 options::OPT_fno_constant_cfstrings) ||
4638 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4639 options::OPT_mno_constant_cfstrings))
4640 CmdArgs.push_back("-fno-constant-cfstrings");
4641
4642 // -fshort-wchar default varies depending on platform; only
4643 // pass if specified.
4644 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4645 options::OPT_fno_short_wchar))
4646 A->render(Args, CmdArgs);
4647
4648 // -fno-pascal-strings is default, only pass non-default.
4649 if (Args.hasFlag(options::OPT_fpascal_strings,
4650 options::OPT_fno_pascal_strings, false))
4651 CmdArgs.push_back("-fpascal-strings");
4652
4653 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4654 // -fno-pack-struct doesn't apply to -fpack-struct=.
4655 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4656 std::string PackStructStr = "-fpack-struct=";
4657 PackStructStr += A->getValue();
4658 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4659 } else if (Args.hasFlag(options::OPT_fpack_struct,
4660 options::OPT_fno_pack_struct, false)) {
4661 CmdArgs.push_back("-fpack-struct=1");
4662 }
4663
4664 // Handle -fmax-type-align=N and -fno-type-align
4665 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4666 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4667 if (!SkipMaxTypeAlign) {
4668 std::string MaxTypeAlignStr = "-fmax-type-align=";
4669 MaxTypeAlignStr += A->getValue();
4670 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4671 }
4672 } else if (getToolChain().getTriple().isOSDarwin()) {
4673 if (!SkipMaxTypeAlign) {
4674 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4675 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4676 }
4677 }
4678
4679 if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4680 if (!Args.hasArg(options::OPT_fcommon))
4681 CmdArgs.push_back("-fno-common");
4682 Args.ClaimAllArgs(options::OPT_fno_common);
4683 }
4684
4685 // -fcommon is default, only pass non-default.
4686 else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4687 CmdArgs.push_back("-fno-common");
4688
4689 // -fsigned-bitfields is default, and clang doesn't yet support
4690 // -funsigned-bitfields.
4691 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4692 options::OPT_funsigned_bitfields))
4693 D.Diag(diag::warn_drv_clang_unsupported)
4694 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4695
4696 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4697 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4698 D.Diag(diag::err_drv_clang_unsupported)
4699 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4700
4701 // -finput_charset=UTF-8 is default. Reject others
4702 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4703 StringRef value = inputCharset->getValue();
4704 if (value != "UTF-8")
4705 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4706 << value;
4707 }
4708
4709 // -fexec_charset=UTF-8 is default. Reject others
4710 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4711 StringRef value = execCharset->getValue();
4712 if (value != "UTF-8")
4713 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4714 << value;
4715 }
4716
4717 // -fcaret-diagnostics is default.
4718 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4719 options::OPT_fno_caret_diagnostics, true))
4720 CmdArgs.push_back("-fno-caret-diagnostics");
4721
4722 // -fdiagnostics-fixit-info is default, only pass non-default.
4723 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4724 options::OPT_fno_diagnostics_fixit_info))
4725 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4726
4727 // Enable -fdiagnostics-show-option by default.
4728 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4729 options::OPT_fno_diagnostics_show_option))
4730 CmdArgs.push_back("-fdiagnostics-show-option");
4731
4732 if (const Arg *A =
4733 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4734 CmdArgs.push_back("-fdiagnostics-show-category");
4735 CmdArgs.push_back(A->getValue());
4736 }
4737
4738 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4739 CmdArgs.push_back("-fdiagnostics-format");
4740 CmdArgs.push_back(A->getValue());
4741 }
4742
4743 if (Arg *A = Args.getLastArg(
4744 options::OPT_fdiagnostics_show_note_include_stack,
4745 options::OPT_fno_diagnostics_show_note_include_stack)) {
4746 if (A->getOption().matches(
4747 options::OPT_fdiagnostics_show_note_include_stack))
4748 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4749 else
4750 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4751 }
4752
4753 // Color diagnostics are the default, unless the terminal doesn't support
4754 // them.
4755 // Support both clang's -f[no-]color-diagnostics and gcc's
4756 // -f[no-]diagnostics-colors[=never|always|auto].
4757 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4758 for (const auto &Arg : Args) {
4759 const Option &O = Arg->getOption();
4760 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4761 !O.matches(options::OPT_fdiagnostics_color) &&
4762 !O.matches(options::OPT_fno_color_diagnostics) &&
4763 !O.matches(options::OPT_fno_diagnostics_color) &&
4764 !O.matches(options::OPT_fdiagnostics_color_EQ))
4765 continue;
4766
4767 Arg->claim();
4768 if (O.matches(options::OPT_fcolor_diagnostics) ||
4769 O.matches(options::OPT_fdiagnostics_color)) {
4770 ShowColors = Colors_On;
4771 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4772 O.matches(options::OPT_fno_diagnostics_color)) {
4773 ShowColors = Colors_Off;
4774 } else {
4775 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4776 StringRef value(Arg->getValue());
4777 if (value == "always")
4778 ShowColors = Colors_On;
4779 else if (value == "never")
4780 ShowColors = Colors_Off;
4781 else if (value == "auto")
4782 ShowColors = Colors_Auto;
4783 else
4784 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4785 << ("-fdiagnostics-color=" + value).str();
4786 }
4787 }
4788 if (ShowColors == Colors_On ||
4789 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4790 CmdArgs.push_back("-fcolor-diagnostics");
4791
4792 if (Args.hasArg(options::OPT_fansi_escape_codes))
4793 CmdArgs.push_back("-fansi-escape-codes");
4794
4795 if (!Args.hasFlag(options::OPT_fshow_source_location,
4796 options::OPT_fno_show_source_location))
4797 CmdArgs.push_back("-fno-show-source-location");
4798
4799 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4800 true))
4801 CmdArgs.push_back("-fno-show-column");
4802
4803 if (!Args.hasFlag(options::OPT_fspell_checking,
4804 options::OPT_fno_spell_checking))
4805 CmdArgs.push_back("-fno-spell-checking");
4806
4807 // -fno-asm-blocks is default.
4808 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4809 false))
4810 CmdArgs.push_back("-fasm-blocks");
4811
4812 // -fgnu-inline-asm is default.
4813 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4814 options::OPT_fno_gnu_inline_asm, true))
4815 CmdArgs.push_back("-fno-gnu-inline-asm");
4816
4817 // Enable vectorization per default according to the optimization level
4818 // selected. For optimization levels that want vectorization we use the alias
4819 // option to simplify the hasFlag logic.
4820 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4821 OptSpecifier VectorizeAliasOption =
4822 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4823 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4824 options::OPT_fno_vectorize, EnableVec))
4825 CmdArgs.push_back("-vectorize-loops");
4826
4827 // -fslp-vectorize is enabled based on the optimization level selected.
4828 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4829 OptSpecifier SLPVectAliasOption =
4830 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4831 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4832 options::OPT_fno_slp_vectorize, EnableSLPVec))
4833 CmdArgs.push_back("-vectorize-slp");
4834
4835 // -fno-slp-vectorize-aggressive is default.
4836 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4837 options::OPT_fno_slp_vectorize_aggressive, false))
4838 CmdArgs.push_back("-vectorize-slp-aggressive");
4839
4840 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4841 A->render(Args, CmdArgs);
4842
4843 // -fdollars-in-identifiers default varies depending on platform and
4844 // language; only pass if specified.
4845 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4846 options::OPT_fno_dollars_in_identifiers)) {
4847 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4848 CmdArgs.push_back("-fdollars-in-identifiers");
4849 else
4850 CmdArgs.push_back("-fno-dollars-in-identifiers");
4851 }
4852
4853 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4854 // practical purposes.
4855 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4856 options::OPT_fno_unit_at_a_time)) {
4857 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4858 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4859 }
4860
4861 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4862 options::OPT_fno_apple_pragma_pack, false))
4863 CmdArgs.push_back("-fapple-pragma-pack");
4864
4865 // le32-specific flags:
4866 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4867 // by default.
4868 if (getToolChain().getArch() == llvm::Triple::le32) {
4869 CmdArgs.push_back("-fno-math-builtin");
4870 }
4871
4872 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4873 //
4874 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4875 #if 0
4876 if (getToolChain().getTriple().isOSDarwin() &&
4877 (getToolChain().getArch() == llvm::Triple::arm ||
4878 getToolChain().getArch() == llvm::Triple::thumb)) {
4879 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4880 CmdArgs.push_back("-fno-builtin-strcat");
4881 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4882 CmdArgs.push_back("-fno-builtin-strcpy");
4883 }
4884 #endif
4885
4886 // Enable rewrite includes if the user's asked for it or if we're generating
4887 // diagnostics.
4888 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4889 // nice to enable this when doing a crashdump for modules as well.
4890 if (Args.hasFlag(options::OPT_frewrite_includes,
4891 options::OPT_fno_rewrite_includes, false) ||
4892 (C.isForDiagnostics() && !HaveModules))
4893 CmdArgs.push_back("-frewrite-includes");
4894
4895 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4896 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4897 options::OPT_traditional_cpp)) {
4898 if (isa<PreprocessJobAction>(JA))
4899 CmdArgs.push_back("-traditional-cpp");
4900 else
4901 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4902 }
4903
4904 Args.AddLastArg(CmdArgs, options::OPT_dM);
4905 Args.AddLastArg(CmdArgs, options::OPT_dD);
4906
4907 // Handle serialized diagnostics.
4908 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4909 CmdArgs.push_back("-serialize-diagnostic-file");
4910 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4911 }
4912
4913 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4914 CmdArgs.push_back("-fretain-comments-from-system-headers");
4915
4916 // Forward -fcomment-block-commands to -cc1.
4917 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4918 // Forward -fparse-all-comments to -cc1.
4919 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4920
4921 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4922 // parser.
4923 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4924 bool OptDisabled = false;
4925 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4926 A->claim();
4927
4928 // We translate this by hand to the -cc1 argument, since nightly test uses
4929 // it and developers have been trained to spell it with -mllvm.
4930 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4931 CmdArgs.push_back("-disable-llvm-optzns");
4932 OptDisabled = true;
4933 } else
4934 A->render(Args, CmdArgs);
4935 }
4936
4937 // With -save-temps, we want to save the unoptimized bitcode output from the
4938 // CompileJobAction, so disable optimizations if they are not already
4939 // disabled.
4940 if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
4941 isa<CompileJobAction>(JA))
4942 CmdArgs.push_back("-disable-llvm-optzns");
4943
4944 if (Output.getType() == types::TY_Dependencies) {
4945 // Handled with other dependency code.
4946 } else if (Output.isFilename()) {
4947 CmdArgs.push_back("-o");
4948 CmdArgs.push_back(Output.getFilename());
4949 } else {
4950 assert(Output.isNothing() && "Invalid output.");
4951 }
4952
4953 addDashXForInput(Args, Input, CmdArgs);
4954
4955 if (Input.isFilename())
4956 CmdArgs.push_back(Input.getFilename());
4957 else
4958 Input.getInputArg().renderAsInput(Args, CmdArgs);
4959
4960 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4961
4962 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4963
4964 // Optionally embed the -cc1 level arguments into the debug info, for build
4965 // analysis.
4966 if (getToolChain().UseDwarfDebugFlags()) {
4967 ArgStringList OriginalArgs;
4968 for (const auto &Arg : Args)
4969 Arg->render(Args, OriginalArgs);
4970
4971 SmallString<256> Flags;
4972 Flags += Exec;
4973 for (const char *OriginalArg : OriginalArgs) {
4974 SmallString<128> EscapedArg;
4975 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4976 Flags += " ";
4977 Flags += EscapedArg;
4978 }
4979 CmdArgs.push_back("-dwarf-debug-flags");
4980 CmdArgs.push_back(Args.MakeArgString(Flags));
4981 }
4982
4983 // Add the split debug info name to the command lines here so we
4984 // can propagate it to the backend.
4985 bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4986 getToolChain().getTriple().isOSLinux() &&
4987 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4988 isa<BackendJobAction>(JA));
4989 const char *SplitDwarfOut;
4990 if (SplitDwarf) {
4991 CmdArgs.push_back("-split-dwarf-file");
4992 SplitDwarfOut = SplitDebugName(Args, Input);
4993 CmdArgs.push_back(SplitDwarfOut);
4994 }
4995
4996 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4997 // Include them with -fcuda-include-gpubinary.
4998 if (IsCuda && Inputs.size() > 1)
4999 for (InputInfoList::const_iterator it = std::next(Inputs.begin()),
5000 ie = Inputs.end();
5001 it != ie; ++it) {
5002 CmdArgs.push_back("-fcuda-include-gpubinary");
5003 CmdArgs.push_back(it->getFilename());
5004 }
5005
5006 // Finally add the compile command to the compilation.
5007 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5008 Output.getType() == types::TY_Object &&
5009 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5010 auto CLCommand =
5011 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5012 C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
5013 std::move(CLCommand)));
5014 } else {
5015 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5016 }
5017
5018 // Handle the debug info splitting at object creation time if we're
5019 // creating an object.
5020 // TODO: Currently only works on linux with newer objcopy.
5021 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5022 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5023
5024 if (Arg *A = Args.getLastArg(options::OPT_pg))
5025 if (Args.hasArg(options::OPT_fomit_frame_pointer))
5026 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5027 << A->getAsString(Args);
5028
5029 // Claim some arguments which clang supports automatically.
5030
5031 // -fpch-preprocess is used with gcc to add a special marker in the output to
5032 // include the PCH file. Clang's PTH solution is completely transparent, so we
5033 // do not need to deal with it at all.
5034 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5035
5036 // Claim some arguments which clang doesn't support, but we don't
5037 // care to warn the user about.
5038 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5039 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5040
5041 // Disable warnings for clang -E -emit-llvm foo.c
5042 Args.ClaimAllArgs(options::OPT_emit_llvm);
5043 }
5044
5045 /// Add options related to the Objective-C runtime/ABI.
5046 ///
5047 /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,ArgStringList & cmdArgs,RewriteKind rewriteKind) const5048 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5049 ArgStringList &cmdArgs,
5050 RewriteKind rewriteKind) const {
5051 // Look for the controlling runtime option.
5052 Arg *runtimeArg =
5053 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5054 options::OPT_fobjc_runtime_EQ);
5055
5056 // Just forward -fobjc-runtime= to the frontend. This supercedes
5057 // options about fragility.
5058 if (runtimeArg &&
5059 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5060 ObjCRuntime runtime;
5061 StringRef value = runtimeArg->getValue();
5062 if (runtime.tryParse(value)) {
5063 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5064 << value;
5065 }
5066
5067 runtimeArg->render(args, cmdArgs);
5068 return runtime;
5069 }
5070
5071 // Otherwise, we'll need the ABI "version". Version numbers are
5072 // slightly confusing for historical reasons:
5073 // 1 - Traditional "fragile" ABI
5074 // 2 - Non-fragile ABI, version 1
5075 // 3 - Non-fragile ABI, version 2
5076 unsigned objcABIVersion = 1;
5077 // If -fobjc-abi-version= is present, use that to set the version.
5078 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5079 StringRef value = abiArg->getValue();
5080 if (value == "1")
5081 objcABIVersion = 1;
5082 else if (value == "2")
5083 objcABIVersion = 2;
5084 else if (value == "3")
5085 objcABIVersion = 3;
5086 else
5087 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5088 } else {
5089 // Otherwise, determine if we are using the non-fragile ABI.
5090 bool nonFragileABIIsDefault =
5091 (rewriteKind == RK_NonFragile ||
5092 (rewriteKind == RK_None &&
5093 getToolChain().IsObjCNonFragileABIDefault()));
5094 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5095 options::OPT_fno_objc_nonfragile_abi,
5096 nonFragileABIIsDefault)) {
5097 // Determine the non-fragile ABI version to use.
5098 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5099 unsigned nonFragileABIVersion = 1;
5100 #else
5101 unsigned nonFragileABIVersion = 2;
5102 #endif
5103
5104 if (Arg *abiArg =
5105 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5106 StringRef value = abiArg->getValue();
5107 if (value == "1")
5108 nonFragileABIVersion = 1;
5109 else if (value == "2")
5110 nonFragileABIVersion = 2;
5111 else
5112 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5113 << value;
5114 }
5115
5116 objcABIVersion = 1 + nonFragileABIVersion;
5117 } else {
5118 objcABIVersion = 1;
5119 }
5120 }
5121
5122 // We don't actually care about the ABI version other than whether
5123 // it's non-fragile.
5124 bool isNonFragile = objcABIVersion != 1;
5125
5126 // If we have no runtime argument, ask the toolchain for its default runtime.
5127 // However, the rewriter only really supports the Mac runtime, so assume that.
5128 ObjCRuntime runtime;
5129 if (!runtimeArg) {
5130 switch (rewriteKind) {
5131 case RK_None:
5132 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5133 break;
5134 case RK_Fragile:
5135 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5136 break;
5137 case RK_NonFragile:
5138 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5139 break;
5140 }
5141
5142 // -fnext-runtime
5143 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5144 // On Darwin, make this use the default behavior for the toolchain.
5145 if (getToolChain().getTriple().isOSDarwin()) {
5146 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5147
5148 // Otherwise, build for a generic macosx port.
5149 } else {
5150 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5151 }
5152
5153 // -fgnu-runtime
5154 } else {
5155 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5156 // Legacy behaviour is to target the gnustep runtime if we are i
5157 // non-fragile mode or the GCC runtime in fragile mode.
5158 if (isNonFragile)
5159 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5160 else
5161 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5162 }
5163
5164 cmdArgs.push_back(
5165 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5166 return runtime;
5167 }
5168
maybeConsumeDash(const std::string & EH,size_t & I)5169 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5170 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5171 I += HaveDash;
5172 return !HaveDash;
5173 }
5174
5175 struct EHFlags {
EHFlagsEHFlags5176 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5177 bool Synch;
5178 bool Asynch;
5179 bool NoExceptC;
5180 };
5181
5182 /// /EH controls whether to run destructor cleanups when exceptions are
5183 /// thrown. There are three modifiers:
5184 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5185 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5186 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5187 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5188 /// modifier is an optimization, so we ignore it for now.
5189 /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args)5190 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5191 EHFlags EH;
5192
5193 std::vector<std::string> EHArgs =
5194 Args.getAllArgValues(options::OPT__SLASH_EH);
5195 for (auto EHVal : EHArgs) {
5196 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5197 switch (EHVal[I]) {
5198 case 'a':
5199 EH.Asynch = maybeConsumeDash(EHVal, I);
5200 continue;
5201 case 'c':
5202 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5203 continue;
5204 case 's':
5205 EH.Synch = maybeConsumeDash(EHVal, I);
5206 continue;
5207 default:
5208 break;
5209 }
5210 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5211 break;
5212 }
5213 }
5214
5215 // FIXME: Disable C++ EH completely, until it becomes more reliable. Users
5216 // can use -Xclang to manually enable C++ EH until then.
5217 EH = EHFlags();
5218
5219 return EH;
5220 }
5221
AddClangCLArgs(const ArgList & Args,ArgStringList & CmdArgs) const5222 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
5223 unsigned RTOptionID = options::OPT__SLASH_MT;
5224
5225 if (Args.hasArg(options::OPT__SLASH_LDd))
5226 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5227 // but defining _DEBUG is sticky.
5228 RTOptionID = options::OPT__SLASH_MTd;
5229
5230 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5231 RTOptionID = A->getOption().getID();
5232
5233 switch (RTOptionID) {
5234 case options::OPT__SLASH_MD:
5235 if (Args.hasArg(options::OPT__SLASH_LDd))
5236 CmdArgs.push_back("-D_DEBUG");
5237 CmdArgs.push_back("-D_MT");
5238 CmdArgs.push_back("-D_DLL");
5239 CmdArgs.push_back("--dependent-lib=msvcrt");
5240 break;
5241 case options::OPT__SLASH_MDd:
5242 CmdArgs.push_back("-D_DEBUG");
5243 CmdArgs.push_back("-D_MT");
5244 CmdArgs.push_back("-D_DLL");
5245 CmdArgs.push_back("--dependent-lib=msvcrtd");
5246 break;
5247 case options::OPT__SLASH_MT:
5248 if (Args.hasArg(options::OPT__SLASH_LDd))
5249 CmdArgs.push_back("-D_DEBUG");
5250 CmdArgs.push_back("-D_MT");
5251 CmdArgs.push_back("--dependent-lib=libcmt");
5252 break;
5253 case options::OPT__SLASH_MTd:
5254 CmdArgs.push_back("-D_DEBUG");
5255 CmdArgs.push_back("-D_MT");
5256 CmdArgs.push_back("--dependent-lib=libcmtd");
5257 break;
5258 default:
5259 llvm_unreachable("Unexpected option ID.");
5260 }
5261
5262 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5263 // users want. The /Za flag to cl.exe turns this off, but it's not
5264 // implemented in clang.
5265 CmdArgs.push_back("--dependent-lib=oldnames");
5266
5267 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5268 // would produce interleaved output, so ignore /showIncludes in such cases.
5269 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5270 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5271 A->render(Args, CmdArgs);
5272
5273 // This controls whether or not we emit RTTI data for polymorphic types.
5274 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5275 /*default=*/false))
5276 CmdArgs.push_back("-fno-rtti-data");
5277
5278 const Driver &D = getToolChain().getDriver();
5279 EHFlags EH = parseClangCLEHFlags(D, Args);
5280 // FIXME: Do something with NoExceptC.
5281 if (EH.Synch || EH.Asynch) {
5282 CmdArgs.push_back("-fcxx-exceptions");
5283 CmdArgs.push_back("-fexceptions");
5284 }
5285
5286 // /EP should expand to -E -P.
5287 if (Args.hasArg(options::OPT__SLASH_EP)) {
5288 CmdArgs.push_back("-E");
5289 CmdArgs.push_back("-P");
5290 }
5291
5292 unsigned VolatileOptionID;
5293 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5294 getToolChain().getArch() == llvm::Triple::x86)
5295 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5296 else
5297 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5298
5299 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5300 VolatileOptionID = A->getOption().getID();
5301
5302 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5303 CmdArgs.push_back("-fms-volatile");
5304
5305 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5306 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5307 if (MostGeneralArg && BestCaseArg)
5308 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5309 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5310
5311 if (MostGeneralArg) {
5312 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5313 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5314 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5315
5316 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5317 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5318 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5319 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5320 << FirstConflict->getAsString(Args)
5321 << SecondConflict->getAsString(Args);
5322
5323 if (SingleArg)
5324 CmdArgs.push_back("-fms-memptr-rep=single");
5325 else if (MultipleArg)
5326 CmdArgs.push_back("-fms-memptr-rep=multiple");
5327 else
5328 CmdArgs.push_back("-fms-memptr-rep=virtual");
5329 }
5330
5331 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5332 A->render(Args, CmdArgs);
5333
5334 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5335 CmdArgs.push_back("-fdiagnostics-format");
5336 if (Args.hasArg(options::OPT__SLASH_fallback))
5337 CmdArgs.push_back("msvc-fallback");
5338 else
5339 CmdArgs.push_back("msvc");
5340 }
5341 }
5342
getCLFallback() const5343 visualstudio::Compiler *Clang::getCLFallback() const {
5344 if (!CLFallback)
5345 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5346 return CLFallback.get();
5347 }
5348
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const5349 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5350 ArgStringList &CmdArgs) const {
5351 StringRef CPUName;
5352 StringRef ABIName;
5353 const llvm::Triple &Triple = getToolChain().getTriple();
5354 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5355
5356 CmdArgs.push_back("-target-abi");
5357 CmdArgs.push_back(ABIName.data());
5358 }
5359
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const5360 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5361 const InputInfo &Output, const InputInfoList &Inputs,
5362 const ArgList &Args,
5363 const char *LinkingOutput) const {
5364 ArgStringList CmdArgs;
5365
5366 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5367 const InputInfo &Input = Inputs[0];
5368
5369 // Don't warn about "clang -w -c foo.s"
5370 Args.ClaimAllArgs(options::OPT_w);
5371 // and "clang -emit-llvm -c foo.s"
5372 Args.ClaimAllArgs(options::OPT_emit_llvm);
5373
5374 claimNoWarnArgs(Args);
5375
5376 // Invoke ourselves in -cc1as mode.
5377 //
5378 // FIXME: Implement custom jobs for internal actions.
5379 CmdArgs.push_back("-cc1as");
5380
5381 // Add the "effective" target triple.
5382 CmdArgs.push_back("-triple");
5383 std::string TripleStr =
5384 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5385 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5386
5387 // Set the output mode, we currently only expect to be used as a real
5388 // assembler.
5389 CmdArgs.push_back("-filetype");
5390 CmdArgs.push_back("obj");
5391
5392 // Set the main file name, so that debug info works even with
5393 // -save-temps or preprocessed assembly.
5394 CmdArgs.push_back("-main-file-name");
5395 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5396
5397 // Add the target cpu
5398 const llvm::Triple Triple(TripleStr);
5399 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5400 if (!CPU.empty()) {
5401 CmdArgs.push_back("-target-cpu");
5402 CmdArgs.push_back(Args.MakeArgString(CPU));
5403 }
5404
5405 // Add the target features
5406 const Driver &D = getToolChain().getDriver();
5407 getTargetFeatures(D, Triple, Args, CmdArgs, true);
5408
5409 // Ignore explicit -force_cpusubtype_ALL option.
5410 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5411
5412 // Pass along any -I options so we get proper .include search paths.
5413 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5414
5415 // Determine the original source input.
5416 const Action *SourceAction = &JA;
5417 while (SourceAction->getKind() != Action::InputClass) {
5418 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5419 SourceAction = SourceAction->getInputs()[0];
5420 }
5421
5422 // Forward -g and handle debug info related flags, assuming we are dealing
5423 // with an actual assembly file.
5424 if (SourceAction->getType() == types::TY_Asm ||
5425 SourceAction->getType() == types::TY_PP_Asm) {
5426 Args.ClaimAllArgs(options::OPT_g_Group);
5427 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
5428 if (!A->getOption().matches(options::OPT_g0))
5429 CmdArgs.push_back("-g");
5430
5431 if (Args.hasArg(options::OPT_gdwarf_2))
5432 CmdArgs.push_back("-gdwarf-2");
5433 if (Args.hasArg(options::OPT_gdwarf_3))
5434 CmdArgs.push_back("-gdwarf-3");
5435 if (Args.hasArg(options::OPT_gdwarf_4))
5436 CmdArgs.push_back("-gdwarf-4");
5437
5438 // Add the -fdebug-compilation-dir flag if needed.
5439 addDebugCompDirArg(Args, CmdArgs);
5440
5441 // Set the AT_producer to the clang version when using the integrated
5442 // assembler on assembly source files.
5443 CmdArgs.push_back("-dwarf-debug-producer");
5444 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5445 }
5446
5447 // Optionally embed the -cc1as level arguments into the debug info, for build
5448 // analysis.
5449 if (getToolChain().UseDwarfDebugFlags()) {
5450 ArgStringList OriginalArgs;
5451 for (const auto &Arg : Args)
5452 Arg->render(Args, OriginalArgs);
5453
5454 SmallString<256> Flags;
5455 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5456 Flags += Exec;
5457 for (const char *OriginalArg : OriginalArgs) {
5458 SmallString<128> EscapedArg;
5459 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5460 Flags += " ";
5461 Flags += EscapedArg;
5462 }
5463 CmdArgs.push_back("-dwarf-debug-flags");
5464 CmdArgs.push_back(Args.MakeArgString(Flags));
5465 }
5466
5467 // FIXME: Add -static support, once we have it.
5468
5469 // Add target specific flags.
5470 switch (getToolChain().getArch()) {
5471 default:
5472 break;
5473
5474 case llvm::Triple::mips:
5475 case llvm::Triple::mipsel:
5476 case llvm::Triple::mips64:
5477 case llvm::Triple::mips64el:
5478 AddMIPSTargetArgs(Args, CmdArgs);
5479 break;
5480 }
5481
5482 // Consume all the warning flags. Usually this would be handled more
5483 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5484 // doesn't handle that so rather than warning about unused flags that are
5485 // actually used, we'll lie by omission instead.
5486 // FIXME: Stop lying and consume only the appropriate driver flags
5487 for (const Arg *A : Args.filtered(options::OPT_W_Group))
5488 A->claim();
5489
5490 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5491 getToolChain().getDriver());
5492
5493 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5494
5495 assert(Output.isFilename() && "Unexpected lipo output.");
5496 CmdArgs.push_back("-o");
5497 CmdArgs.push_back(Output.getFilename());
5498
5499 assert(Input.isFilename() && "Invalid input.");
5500 CmdArgs.push_back(Input.getFilename());
5501
5502 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5503 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5504
5505 // Handle the debug info splitting at object creation time if we're
5506 // creating an object.
5507 // TODO: Currently only works on linux with newer objcopy.
5508 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5509 getToolChain().getTriple().isOSLinux())
5510 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5511 SplitDebugName(Args, Input));
5512 }
5513
anchor()5514 void GnuTool::anchor() {}
5515
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const5516 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
5517 const InputInfo &Output,
5518 const InputInfoList &Inputs, const ArgList &Args,
5519 const char *LinkingOutput) const {
5520 const Driver &D = getToolChain().getDriver();
5521 ArgStringList CmdArgs;
5522
5523 for (const auto &A : Args) {
5524 if (forwardToGCC(A->getOption())) {
5525 // Don't forward any -g arguments to assembly steps.
5526 if (isa<AssembleJobAction>(JA) &&
5527 A->getOption().matches(options::OPT_g_Group))
5528 continue;
5529
5530 // Don't forward any -W arguments to assembly and link steps.
5531 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
5532 A->getOption().matches(options::OPT_W_Group))
5533 continue;
5534
5535 // It is unfortunate that we have to claim here, as this means
5536 // we will basically never report anything interesting for
5537 // platforms using a generic gcc, even if we are just using gcc
5538 // to get to the assembler.
5539 A->claim();
5540 A->render(Args, CmdArgs);
5541 }
5542 }
5543
5544 RenderExtraToolArgs(JA, CmdArgs);
5545
5546 // If using a driver driver, force the arch.
5547 if (getToolChain().getTriple().isOSDarwin()) {
5548 CmdArgs.push_back("-arch");
5549 CmdArgs.push_back(
5550 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
5551 }
5552
5553 // Try to force gcc to match the tool chain we want, if we recognize
5554 // the arch.
5555 //
5556 // FIXME: The triple class should directly provide the information we want
5557 // here.
5558 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5559 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
5560 CmdArgs.push_back("-m32");
5561 else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
5562 Arch == llvm::Triple::ppc64le)
5563 CmdArgs.push_back("-m64");
5564
5565 if (Output.isFilename()) {
5566 CmdArgs.push_back("-o");
5567 CmdArgs.push_back(Output.getFilename());
5568 } else {
5569 assert(Output.isNothing() && "Unexpected output");
5570 CmdArgs.push_back("-fsyntax-only");
5571 }
5572
5573 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5574
5575 // Only pass -x if gcc will understand it; otherwise hope gcc
5576 // understands the suffix correctly. The main use case this would go
5577 // wrong in is for linker inputs if they happened to have an odd
5578 // suffix; really the only way to get this to happen is a command
5579 // like '-x foobar a.c' which will treat a.c like a linker input.
5580 //
5581 // FIXME: For the linker case specifically, can we safely convert
5582 // inputs into '-Wl,' options?
5583 for (const auto &II : Inputs) {
5584 // Don't try to pass LLVM or AST inputs to a generic gcc.
5585 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5586 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5587 D.Diag(diag::err_drv_no_linker_llvm_support)
5588 << getToolChain().getTripleString();
5589 else if (II.getType() == types::TY_AST)
5590 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
5591 else if (II.getType() == types::TY_ModuleFile)
5592 D.Diag(diag::err_drv_no_module_support)
5593 << getToolChain().getTripleString();
5594
5595 if (types::canTypeBeUserSpecified(II.getType())) {
5596 CmdArgs.push_back("-x");
5597 CmdArgs.push_back(types::getTypeName(II.getType()));
5598 }
5599
5600 if (II.isFilename())
5601 CmdArgs.push_back(II.getFilename());
5602 else {
5603 const Arg &A = II.getInputArg();
5604
5605 // Reverse translate some rewritten options.
5606 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
5607 CmdArgs.push_back("-lstdc++");
5608 continue;
5609 }
5610
5611 // Don't render as input, we need gcc to do the translations.
5612 A.render(Args, CmdArgs);
5613 }
5614 }
5615
5616 const std::string customGCCName = D.getCCCGenericGCCName();
5617 const char *GCCName;
5618 if (!customGCCName.empty())
5619 GCCName = customGCCName.c_str();
5620 else if (D.CCCIsCXX()) {
5621 GCCName = "g++";
5622 } else
5623 GCCName = "gcc";
5624
5625 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5626 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5627 }
5628
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const5629 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
5630 ArgStringList &CmdArgs) const {
5631 CmdArgs.push_back("-E");
5632 }
5633
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const5634 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
5635 ArgStringList &CmdArgs) const {
5636 const Driver &D = getToolChain().getDriver();
5637
5638 switch (JA.getType()) {
5639 // If -flto, etc. are present then make sure not to force assembly output.
5640 case types::TY_LLVM_IR:
5641 case types::TY_LTO_IR:
5642 case types::TY_LLVM_BC:
5643 case types::TY_LTO_BC:
5644 CmdArgs.push_back("-c");
5645 break;
5646 case types::TY_PP_Asm:
5647 CmdArgs.push_back("-S");
5648 break;
5649 case types::TY_Nothing:
5650 CmdArgs.push_back("-fsyntax-only");
5651 break;
5652 default:
5653 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
5654 }
5655 }
5656
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const5657 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
5658 ArgStringList &CmdArgs) const {
5659 // The types are (hopefully) good enough.
5660 }
5661
5662 // Hexagon tools start.
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const5663 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
5664 ArgStringList &CmdArgs) const {}
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const5665 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
5666 const InputInfo &Output,
5667 const InputInfoList &Inputs,
5668 const ArgList &Args,
5669 const char *LinkingOutput) const {
5670 claimNoWarnArgs(Args);
5671
5672 const Driver &D = getToolChain().getDriver();
5673 ArgStringList CmdArgs;
5674
5675 std::string MarchString = "-march=";
5676 MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5677 CmdArgs.push_back(Args.MakeArgString(MarchString));
5678
5679 RenderExtraToolArgs(JA, CmdArgs);
5680
5681 if (Output.isFilename()) {
5682 CmdArgs.push_back("-o");
5683 CmdArgs.push_back(Output.getFilename());
5684 } else {
5685 assert(Output.isNothing() && "Unexpected output");
5686 CmdArgs.push_back("-fsyntax-only");
5687 }
5688
5689 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args))
5690 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5691
5692 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5693
5694 // Only pass -x if gcc will understand it; otherwise hope gcc
5695 // understands the suffix correctly. The main use case this would go
5696 // wrong in is for linker inputs if they happened to have an odd
5697 // suffix; really the only way to get this to happen is a command
5698 // like '-x foobar a.c' which will treat a.c like a linker input.
5699 //
5700 // FIXME: For the linker case specifically, can we safely convert
5701 // inputs into '-Wl,' options?
5702 for (const auto &II : Inputs) {
5703 // Don't try to pass LLVM or AST inputs to a generic gcc.
5704 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5705 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5706 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5707 << getToolChain().getTripleString();
5708 else if (II.getType() == types::TY_AST)
5709 D.Diag(clang::diag::err_drv_no_ast_support)
5710 << getToolChain().getTripleString();
5711 else if (II.getType() == types::TY_ModuleFile)
5712 D.Diag(diag::err_drv_no_module_support)
5713 << getToolChain().getTripleString();
5714
5715 if (II.isFilename())
5716 CmdArgs.push_back(II.getFilename());
5717 else
5718 // Don't render as input, we need gcc to do the translations.
5719 // FIXME: Pranav: What is this ?
5720 II.getInputArg().render(Args, CmdArgs);
5721 }
5722
5723 const char *GCCName = "hexagon-as";
5724 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5725 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5726 }
5727
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const5728 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
5729 ArgStringList &CmdArgs) const {
5730 // The types are (hopefully) good enough.
5731 }
5732
constructHexagonLinkArgs(Compilation & C,const JobAction & JA,const toolchains::Hexagon_TC & ToolChain,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const char * LinkingOutput)5733 static void constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
5734 const toolchains::Hexagon_TC &ToolChain,
5735 const InputInfo &Output,
5736 const InputInfoList &Inputs,
5737 const ArgList &Args,
5738 ArgStringList &CmdArgs,
5739 const char *LinkingOutput) {
5740
5741 const Driver &D = ToolChain.getDriver();
5742
5743 //----------------------------------------------------------------------------
5744 //
5745 //----------------------------------------------------------------------------
5746 bool hasStaticArg = Args.hasArg(options::OPT_static);
5747 bool buildingLib = Args.hasArg(options::OPT_shared);
5748 bool buildPIE = Args.hasArg(options::OPT_pie);
5749 bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5750 bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5751 bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5752 bool useG0 = false;
5753 bool useShared = buildingLib && !hasStaticArg;
5754
5755 //----------------------------------------------------------------------------
5756 // Silence warnings for various options
5757 //----------------------------------------------------------------------------
5758
5759 Args.ClaimAllArgs(options::OPT_g_Group);
5760 Args.ClaimAllArgs(options::OPT_emit_llvm);
5761 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5762 // handled somewhere else.
5763 Args.ClaimAllArgs(options::OPT_static_libgcc);
5764
5765 //----------------------------------------------------------------------------
5766 //
5767 //----------------------------------------------------------------------------
5768 for (const auto &Opt : ToolChain.ExtraOpts)
5769 CmdArgs.push_back(Opt.c_str());
5770
5771 std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5772 CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5773
5774 if (buildingLib) {
5775 CmdArgs.push_back("-shared");
5776 CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5777 // hexagon-gcc does
5778 }
5779
5780 if (hasStaticArg)
5781 CmdArgs.push_back("-static");
5782
5783 if (buildPIE && !buildingLib)
5784 CmdArgs.push_back("-pie");
5785
5786 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
5787 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5788 useG0 = toolchains::Hexagon_TC::UsesG0(v);
5789 }
5790
5791 //----------------------------------------------------------------------------
5792 //
5793 //----------------------------------------------------------------------------
5794 CmdArgs.push_back("-o");
5795 CmdArgs.push_back(Output.getFilename());
5796
5797 const std::string MarchSuffix = "/" + MarchString;
5798 const std::string G0Suffix = "/G0";
5799 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5800 const std::string RootDir =
5801 toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
5802 const std::string StartFilesDir =
5803 RootDir + "hexagon/lib" + (useG0 ? MarchG0Suffix : MarchSuffix);
5804
5805 //----------------------------------------------------------------------------
5806 // moslib
5807 //----------------------------------------------------------------------------
5808 std::vector<std::string> oslibs;
5809 bool hasStandalone = false;
5810
5811 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
5812 A->claim();
5813 oslibs.emplace_back(A->getValue());
5814 hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5815 }
5816 if (oslibs.empty()) {
5817 oslibs.push_back("standalone");
5818 hasStandalone = true;
5819 }
5820
5821 //----------------------------------------------------------------------------
5822 // Start Files
5823 //----------------------------------------------------------------------------
5824 if (incStdLib && incStartFiles) {
5825
5826 if (!buildingLib) {
5827 if (hasStandalone) {
5828 CmdArgs.push_back(
5829 Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5830 }
5831 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5832 }
5833 std::string initObj = useShared ? "/initS.o" : "/init.o";
5834 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5835 }
5836
5837 //----------------------------------------------------------------------------
5838 // Library Search Paths
5839 //----------------------------------------------------------------------------
5840 const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5841 for (const auto &LibPath : LibPaths)
5842 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5843
5844 //----------------------------------------------------------------------------
5845 //
5846 //----------------------------------------------------------------------------
5847 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5848 Args.AddAllArgs(CmdArgs, options::OPT_e);
5849 Args.AddAllArgs(CmdArgs, options::OPT_s);
5850 Args.AddAllArgs(CmdArgs, options::OPT_t);
5851 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5852
5853 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5854
5855 //----------------------------------------------------------------------------
5856 // Libraries
5857 //----------------------------------------------------------------------------
5858 if (incStdLib && incDefLibs) {
5859 if (D.CCCIsCXX()) {
5860 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5861 CmdArgs.push_back("-lm");
5862 }
5863
5864 CmdArgs.push_back("--start-group");
5865
5866 if (!buildingLib) {
5867 for (const std::string &Lib : oslibs)
5868 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
5869 CmdArgs.push_back("-lc");
5870 }
5871 CmdArgs.push_back("-lgcc");
5872
5873 CmdArgs.push_back("--end-group");
5874 }
5875
5876 //----------------------------------------------------------------------------
5877 // End files
5878 //----------------------------------------------------------------------------
5879 if (incStdLib && incStartFiles) {
5880 std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5881 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5882 }
5883 }
5884
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const5885 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
5886 const InputInfo &Output,
5887 const InputInfoList &Inputs,
5888 const ArgList &Args,
5889 const char *LinkingOutput) const {
5890
5891 const toolchains::Hexagon_TC &ToolChain =
5892 static_cast<const toolchains::Hexagon_TC &>(getToolChain());
5893
5894 ArgStringList CmdArgs;
5895 constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
5896 LinkingOutput);
5897
5898 std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5899 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
5900 CmdArgs));
5901 }
5902 // Hexagon tools end.
5903
getARMArch(StringRef Arch,const llvm::Triple & Triple)5904 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
5905 std::string MArch;
5906 if (!Arch.empty())
5907 MArch = Arch;
5908 else
5909 MArch = Triple.getArchName();
5910 MArch = StringRef(MArch).lower();
5911
5912 // Handle -march=native.
5913 if (MArch == "native") {
5914 std::string CPU = llvm::sys::getHostCPUName();
5915 if (CPU != "generic") {
5916 // Translate the native cpu into the architecture suffix for that CPU.
5917 const char *Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch);
5918 // If there is no valid architecture suffix for this CPU we don't know how
5919 // to handle it, so return no architecture.
5920 if (strcmp(Suffix, "") == 0)
5921 MArch = "";
5922 else
5923 MArch = std::string("arm") + Suffix;
5924 }
5925 }
5926
5927 return MArch;
5928 }
5929 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
getARMCPUForMArch(StringRef Arch,const llvm::Triple & Triple)5930 const char *arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
5931 std::string MArch = getARMArch(Arch, Triple);
5932 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
5933 // here means an -march=native that we can't handle, so instead return no CPU.
5934 if (MArch.empty())
5935 return "";
5936
5937 // We need to return an empty string here on invalid MArch values as the
5938 // various places that call this function can't cope with a null result.
5939 const char *result = Triple.getARMCPUForArch(MArch);
5940 if (result)
5941 return result;
5942 else
5943 return "";
5944 }
5945
5946 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
getARMTargetCPU(StringRef CPU,StringRef Arch,const llvm::Triple & Triple)5947 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
5948 const llvm::Triple &Triple) {
5949 // FIXME: Warn on inconsistent use of -mcpu and -march.
5950 // If we have -mcpu=, use that.
5951 if (!CPU.empty()) {
5952 std::string MCPU = StringRef(CPU).lower();
5953 // Handle -mcpu=native.
5954 if (MCPU == "native")
5955 return llvm::sys::getHostCPUName();
5956 else
5957 return MCPU;
5958 }
5959
5960 return getARMCPUForMArch(Arch, Triple);
5961 }
5962
5963 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5964 /// CPU (or Arch, if CPU is generic).
5965 // FIXME: This is redundant with -mcpu, why does LLVM use this.
getLLVMArchSuffixForARM(StringRef CPU,StringRef Arch)5966 const char *arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch) {
5967 if (CPU == "generic" &&
5968 llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_ARMV8_1A)
5969 return "v8.1a";
5970
5971 unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
5972 if (ArchKind == llvm::ARM::AK_INVALID)
5973 return "";
5974 return llvm::ARMTargetParser::getSubArch(ArchKind);
5975 }
5976
appendEBLinkFlags(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple)5977 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
5978 const llvm::Triple &Triple) {
5979 if (Args.hasArg(options::OPT_r))
5980 return;
5981
5982 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
5983 // to generate BE-8 executables.
5984 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
5985 CmdArgs.push_back("--be8");
5986 }
5987
getSupportedNanEncoding(StringRef & CPU)5988 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
5989 return (NanEncoding)llvm::StringSwitch<int>(CPU)
5990 .Case("mips1", NanLegacy)
5991 .Case("mips2", NanLegacy)
5992 .Case("mips3", NanLegacy)
5993 .Case("mips4", NanLegacy)
5994 .Case("mips5", NanLegacy)
5995 .Case("mips32", NanLegacy)
5996 .Case("mips32r2", NanLegacy)
5997 .Case("mips32r3", NanLegacy | Nan2008)
5998 .Case("mips32r5", NanLegacy | Nan2008)
5999 .Case("mips32r6", Nan2008)
6000 .Case("mips64", NanLegacy)
6001 .Case("mips64r2", NanLegacy)
6002 .Case("mips64r3", NanLegacy | Nan2008)
6003 .Case("mips64r5", NanLegacy | Nan2008)
6004 .Case("mips64r6", Nan2008)
6005 .Default(NanLegacy);
6006 }
6007
hasMipsAbiArg(const ArgList & Args,const char * Value)6008 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6009 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6010 return A && (A->getValue() == StringRef(Value));
6011 }
6012
isUCLibc(const ArgList & Args)6013 bool mips::isUCLibc(const ArgList &Args) {
6014 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6015 return A && A->getOption().matches(options::OPT_muclibc);
6016 }
6017
isNaN2008(const ArgList & Args,const llvm::Triple & Triple)6018 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6019 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6020 return llvm::StringSwitch<bool>(NaNArg->getValue())
6021 .Case("2008", true)
6022 .Case("legacy", false)
6023 .Default(false);
6024
6025 // NaN2008 is the default for MIPS32r6/MIPS64r6.
6026 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6027 .Cases("mips32r6", "mips64r6", true)
6028 .Default(false);
6029
6030 return false;
6031 }
6032
isFPXXDefault(const llvm::Triple & Triple,StringRef CPUName,StringRef ABIName,StringRef FloatABI)6033 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6034 StringRef ABIName, StringRef FloatABI) {
6035 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6036 Triple.getVendor() != llvm::Triple::MipsTechnologies)
6037 return false;
6038
6039 if (ABIName != "32")
6040 return false;
6041
6042 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6043 // present.
6044 if (FloatABI == "soft")
6045 return false;
6046
6047 return llvm::StringSwitch<bool>(CPUName)
6048 .Cases("mips2", "mips3", "mips4", "mips5", true)
6049 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6050 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6051 .Default(false);
6052 }
6053
shouldUseFPXX(const ArgList & Args,const llvm::Triple & Triple,StringRef CPUName,StringRef ABIName,StringRef FloatABI)6054 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6055 StringRef CPUName, StringRef ABIName,
6056 StringRef FloatABI) {
6057 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6058
6059 // FPXX shouldn't be used if -msingle-float is present.
6060 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6061 options::OPT_mdouble_float))
6062 if (A->getOption().matches(options::OPT_msingle_float))
6063 UseFPXX = false;
6064
6065 return UseFPXX;
6066 }
6067
getArchTypeForMachOArchName(StringRef Str)6068 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6069 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6070 // archs which Darwin doesn't use.
6071
6072 // The matching this routine does is fairly pointless, since it is neither the
6073 // complete architecture list, nor a reasonable subset. The problem is that
6074 // historically the driver driver accepts this and also ties its -march=
6075 // handling to the architecture name, so we need to be careful before removing
6076 // support for it.
6077
6078 // This code must be kept in sync with Clang's Darwin specific argument
6079 // translation.
6080
6081 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6082 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6083 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6084 .Case("ppc64", llvm::Triple::ppc64)
6085 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6086 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6087 llvm::Triple::x86)
6088 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6089 // This is derived from the driver driver.
6090 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6091 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6092 .Cases("armv7s", "xscale", llvm::Triple::arm)
6093 .Case("arm64", llvm::Triple::aarch64)
6094 .Case("r600", llvm::Triple::r600)
6095 .Case("amdgcn", llvm::Triple::amdgcn)
6096 .Case("nvptx", llvm::Triple::nvptx)
6097 .Case("nvptx64", llvm::Triple::nvptx64)
6098 .Case("amdil", llvm::Triple::amdil)
6099 .Case("spir", llvm::Triple::spir)
6100 .Default(llvm::Triple::UnknownArch);
6101 }
6102
setTripleTypeForMachOArchName(llvm::Triple & T,StringRef Str)6103 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6104 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6105 T.setArch(Arch);
6106
6107 if (Str == "x86_64h")
6108 T.setArchName(Str);
6109 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6110 T.setOS(llvm::Triple::UnknownOS);
6111 T.setObjectFormat(llvm::Triple::MachO);
6112 }
6113 }
6114
getBaseInputName(const ArgList & Args,const InputInfo & Input)6115 const char *Clang::getBaseInputName(const ArgList &Args,
6116 const InputInfo &Input) {
6117 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6118 }
6119
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)6120 const char *Clang::getBaseInputStem(const ArgList &Args,
6121 const InputInfoList &Inputs) {
6122 const char *Str = getBaseInputName(Args, Inputs[0]);
6123
6124 if (const char *End = strrchr(Str, '.'))
6125 return Args.MakeArgString(std::string(Str, End));
6126
6127 return Str;
6128 }
6129
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)6130 const char *Clang::getDependencyFileName(const ArgList &Args,
6131 const InputInfoList &Inputs) {
6132 // FIXME: Think about this more.
6133 std::string Res;
6134
6135 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6136 std::string Str(OutputOpt->getValue());
6137 Res = Str.substr(0, Str.rfind('.'));
6138 } else {
6139 Res = getBaseInputStem(Args, Inputs);
6140 }
6141 return Args.MakeArgString(Res + ".d");
6142 }
6143
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6144 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6145 const InputInfo &Output,
6146 const InputInfoList &Inputs,
6147 const ArgList &Args,
6148 const char *LinkingOutput) const {
6149 const ToolChain &ToolChain = getToolChain();
6150 const Driver &D = ToolChain.getDriver();
6151 ArgStringList CmdArgs;
6152
6153 // Silence warning for "clang -g foo.o -o foo"
6154 Args.ClaimAllArgs(options::OPT_g_Group);
6155 // and "clang -emit-llvm foo.o -o foo"
6156 Args.ClaimAllArgs(options::OPT_emit_llvm);
6157 // and for "clang -w foo.o -o foo". Other warning options are already
6158 // handled somewhere else.
6159 Args.ClaimAllArgs(options::OPT_w);
6160
6161 if (!D.SysRoot.empty())
6162 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6163
6164 // CloudABI only supports static linkage.
6165 CmdArgs.push_back("-Bstatic");
6166 CmdArgs.push_back("--eh-frame-hdr");
6167 CmdArgs.push_back("--gc-sections");
6168
6169 if (Output.isFilename()) {
6170 CmdArgs.push_back("-o");
6171 CmdArgs.push_back(Output.getFilename());
6172 } else {
6173 assert(Output.isNothing() && "Invalid output.");
6174 }
6175
6176 if (!Args.hasArg(options::OPT_nostdlib) &&
6177 !Args.hasArg(options::OPT_nostartfiles)) {
6178 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6179 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6180 }
6181
6182 Args.AddAllArgs(CmdArgs, options::OPT_L);
6183 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
6184 for (const auto &Path : Paths)
6185 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6186 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6187 Args.AddAllArgs(CmdArgs, options::OPT_e);
6188 Args.AddAllArgs(CmdArgs, options::OPT_s);
6189 Args.AddAllArgs(CmdArgs, options::OPT_t);
6190 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6191 Args.AddAllArgs(CmdArgs, options::OPT_r);
6192
6193 if (D.IsUsingLTO(Args))
6194 AddGoldPlugin(ToolChain, Args, CmdArgs);
6195
6196 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6197
6198 if (!Args.hasArg(options::OPT_nostdlib) &&
6199 !Args.hasArg(options::OPT_nodefaultlibs)) {
6200 if (D.CCCIsCXX())
6201 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6202 CmdArgs.push_back("-lc");
6203 CmdArgs.push_back("-lcompiler_rt");
6204 }
6205
6206 if (!Args.hasArg(options::OPT_nostdlib) &&
6207 !Args.hasArg(options::OPT_nostartfiles))
6208 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6209
6210 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6211 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6212 }
6213
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6214 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6215 const InputInfo &Output,
6216 const InputInfoList &Inputs,
6217 const ArgList &Args,
6218 const char *LinkingOutput) const {
6219 ArgStringList CmdArgs;
6220
6221 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6222 const InputInfo &Input = Inputs[0];
6223
6224 // Determine the original source input.
6225 const Action *SourceAction = &JA;
6226 while (SourceAction->getKind() != Action::InputClass) {
6227 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6228 SourceAction = SourceAction->getInputs()[0];
6229 }
6230
6231 // If -fno_integrated_as is used add -Q to the darwin assember driver to make
6232 // sure it runs its system assembler not clang's integrated assembler.
6233 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6234 // FIXME: at run-time detect assembler capabilities or rely on version
6235 // information forwarded by -target-assembler-version (future)
6236 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6237 const llvm::Triple &T(getToolChain().getTriple());
6238 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6239 CmdArgs.push_back("-Q");
6240 }
6241
6242 // Forward -g, assuming we are dealing with an actual assembly file.
6243 if (SourceAction->getType() == types::TY_Asm ||
6244 SourceAction->getType() == types::TY_PP_Asm) {
6245 if (Args.hasArg(options::OPT_gstabs))
6246 CmdArgs.push_back("--gstabs");
6247 else if (Args.hasArg(options::OPT_g_Group))
6248 CmdArgs.push_back("-g");
6249 }
6250
6251 // Derived from asm spec.
6252 AddMachOArch(Args, CmdArgs);
6253
6254 // Use -force_cpusubtype_ALL on x86 by default.
6255 if (getToolChain().getArch() == llvm::Triple::x86 ||
6256 getToolChain().getArch() == llvm::Triple::x86_64 ||
6257 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6258 CmdArgs.push_back("-force_cpusubtype_ALL");
6259
6260 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6261 (((Args.hasArg(options::OPT_mkernel) ||
6262 Args.hasArg(options::OPT_fapple_kext)) &&
6263 getMachOToolChain().isKernelStatic()) ||
6264 Args.hasArg(options::OPT_static)))
6265 CmdArgs.push_back("-static");
6266
6267 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6268
6269 assert(Output.isFilename() && "Unexpected lipo output.");
6270 CmdArgs.push_back("-o");
6271 CmdArgs.push_back(Output.getFilename());
6272
6273 assert(Input.isFilename() && "Invalid input.");
6274 CmdArgs.push_back(Input.getFilename());
6275
6276 // asm_final spec is empty.
6277
6278 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6279 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6280 }
6281
anchor()6282 void darwin::MachOTool::anchor() {}
6283
AddMachOArch(const ArgList & Args,ArgStringList & CmdArgs) const6284 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6285 ArgStringList &CmdArgs) const {
6286 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6287
6288 // Derived from darwin_arch spec.
6289 CmdArgs.push_back("-arch");
6290 CmdArgs.push_back(Args.MakeArgString(ArchName));
6291
6292 // FIXME: Is this needed anymore?
6293 if (ArchName == "arm")
6294 CmdArgs.push_back("-force_cpusubtype_ALL");
6295 }
6296
NeedsTempPath(const InputInfoList & Inputs) const6297 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6298 // We only need to generate a temp path for LTO if we aren't compiling object
6299 // files. When compiling source files, we run 'dsymutil' after linking. We
6300 // don't run 'dsymutil' when compiling object files.
6301 for (const auto &Input : Inputs)
6302 if (Input.getType() != types::TY_Object)
6303 return true;
6304
6305 return false;
6306 }
6307
AddLinkArgs(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const InputInfoList & Inputs) const6308 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6309 ArgStringList &CmdArgs,
6310 const InputInfoList &Inputs) const {
6311 const Driver &D = getToolChain().getDriver();
6312 const toolchains::MachO &MachOTC = getMachOToolChain();
6313
6314 unsigned Version[3] = {0, 0, 0};
6315 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6316 bool HadExtra;
6317 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6318 Version[2], HadExtra) ||
6319 HadExtra)
6320 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6321 }
6322
6323 // Newer linkers support -demangle. Pass it if supported and not disabled by
6324 // the user.
6325 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6326 CmdArgs.push_back("-demangle");
6327
6328 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6329 CmdArgs.push_back("-export_dynamic");
6330
6331 // If we are using App Extension restrictions, pass a flag to the linker
6332 // telling it that the compiled code has been audited.
6333 if (Args.hasFlag(options::OPT_fapplication_extension,
6334 options::OPT_fno_application_extension, false))
6335 CmdArgs.push_back("-application_extension");
6336
6337 // If we are using LTO, then automatically create a temporary file path for
6338 // the linker to use, so that it's lifetime will extend past a possible
6339 // dsymutil step.
6340 if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
6341 const char *TmpPath = C.getArgs().MakeArgString(
6342 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6343 C.addTempFile(TmpPath);
6344 CmdArgs.push_back("-object_path_lto");
6345 CmdArgs.push_back(TmpPath);
6346 }
6347
6348 // Derived from the "link" spec.
6349 Args.AddAllArgs(CmdArgs, options::OPT_static);
6350 if (!Args.hasArg(options::OPT_static))
6351 CmdArgs.push_back("-dynamic");
6352 if (Args.hasArg(options::OPT_fgnu_runtime)) {
6353 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6354 // here. How do we wish to handle such things?
6355 }
6356
6357 if (!Args.hasArg(options::OPT_dynamiclib)) {
6358 AddMachOArch(Args, CmdArgs);
6359 // FIXME: Why do this only on this path?
6360 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6361
6362 Args.AddLastArg(CmdArgs, options::OPT_bundle);
6363 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6364 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6365
6366 Arg *A;
6367 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6368 (A = Args.getLastArg(options::OPT_current__version)) ||
6369 (A = Args.getLastArg(options::OPT_install__name)))
6370 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
6371 << "-dynamiclib";
6372
6373 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
6374 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
6375 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
6376 } else {
6377 CmdArgs.push_back("-dylib");
6378
6379 Arg *A;
6380 if ((A = Args.getLastArg(options::OPT_bundle)) ||
6381 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
6382 (A = Args.getLastArg(options::OPT_client__name)) ||
6383 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
6384 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
6385 (A = Args.getLastArg(options::OPT_private__bundle)))
6386 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
6387 << "-dynamiclib";
6388
6389 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
6390 "-dylib_compatibility_version");
6391 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
6392 "-dylib_current_version");
6393
6394 AddMachOArch(Args, CmdArgs);
6395
6396 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
6397 "-dylib_install_name");
6398 }
6399
6400 Args.AddLastArg(CmdArgs, options::OPT_all__load);
6401 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
6402 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
6403 if (MachOTC.isTargetIOSBased())
6404 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
6405 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
6406 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
6407 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
6408 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
6409 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
6410 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
6411 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
6412 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
6413 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
6414 Args.AddAllArgs(CmdArgs, options::OPT_init);
6415
6416 // Add the deployment target.
6417 MachOTC.addMinVersionArgs(Args, CmdArgs);
6418
6419 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
6420 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
6421 Args.AddLastArg(CmdArgs, options::OPT_single__module);
6422 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
6423 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
6424
6425 if (const Arg *A =
6426 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
6427 options::OPT_fno_pie, options::OPT_fno_PIE)) {
6428 if (A->getOption().matches(options::OPT_fpie) ||
6429 A->getOption().matches(options::OPT_fPIE))
6430 CmdArgs.push_back("-pie");
6431 else
6432 CmdArgs.push_back("-no_pie");
6433 }
6434
6435 Args.AddLastArg(CmdArgs, options::OPT_prebind);
6436 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
6437 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
6438 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
6439 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
6440 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
6441 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
6442 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
6443 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
6444 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
6445 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
6446 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
6447 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
6448 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
6449 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
6450 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
6451
6452 // Give --sysroot= preference, over the Apple specific behavior to also use
6453 // --isysroot as the syslibroot.
6454 StringRef sysroot = C.getSysRoot();
6455 if (sysroot != "") {
6456 CmdArgs.push_back("-syslibroot");
6457 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
6458 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
6459 CmdArgs.push_back("-syslibroot");
6460 CmdArgs.push_back(A->getValue());
6461 }
6462
6463 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
6464 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
6465 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
6466 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
6467 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
6468 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
6469 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
6470 Args.AddAllArgs(CmdArgs, options::OPT_y);
6471 Args.AddLastArg(CmdArgs, options::OPT_w);
6472 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
6473 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
6474 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
6475 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
6476 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
6477 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
6478 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
6479 Args.AddLastArg(CmdArgs, options::OPT_whyload);
6480 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
6481 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
6482 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
6483 Args.AddLastArg(CmdArgs, options::OPT_Mach);
6484 }
6485
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6486 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6487 const InputInfo &Output,
6488 const InputInfoList &Inputs,
6489 const ArgList &Args,
6490 const char *LinkingOutput) const {
6491 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
6492
6493 // If the number of arguments surpasses the system limits, we will encode the
6494 // input files in a separate file, shortening the command line. To this end,
6495 // build a list of input file names that can be passed via a file with the
6496 // -filelist linker option.
6497 llvm::opt::ArgStringList InputFileList;
6498
6499 // The logic here is derived from gcc's behavior; most of which
6500 // comes from specs (starting with link_command). Consult gcc for
6501 // more information.
6502 ArgStringList CmdArgs;
6503
6504 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
6505 if (Args.hasArg(options::OPT_ccc_arcmt_check,
6506 options::OPT_ccc_arcmt_migrate)) {
6507 for (const auto &Arg : Args)
6508 Arg->claim();
6509 const char *Exec =
6510 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
6511 CmdArgs.push_back(Output.getFilename());
6512 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6513 return;
6514 }
6515
6516 // I'm not sure why this particular decomposition exists in gcc, but
6517 // we follow suite for ease of comparison.
6518 AddLinkArgs(C, Args, CmdArgs, Inputs);
6519
6520 Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
6521 Args.AddAllArgs(CmdArgs, options::OPT_s);
6522 Args.AddAllArgs(CmdArgs, options::OPT_t);
6523 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6524 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
6525 Args.AddLastArg(CmdArgs, options::OPT_e);
6526 Args.AddAllArgs(CmdArgs, options::OPT_r);
6527
6528 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
6529 // members of static archive libraries which implement Objective-C classes or
6530 // categories.
6531 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
6532 CmdArgs.push_back("-ObjC");
6533
6534 CmdArgs.push_back("-o");
6535 CmdArgs.push_back(Output.getFilename());
6536
6537 if (!Args.hasArg(options::OPT_nostdlib) &&
6538 !Args.hasArg(options::OPT_nostartfiles))
6539 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
6540
6541 // SafeStack requires its own runtime libraries
6542 // These libraries should be linked first, to make sure the
6543 // __safestack_init constructor executes before everything else
6544 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
6545 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
6546 "libclang_rt.safestack_osx.a",
6547 /*AlwaysLink=*/true);
6548 }
6549
6550 Args.AddAllArgs(CmdArgs, options::OPT_L);
6551
6552 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6553 // Build the input file for -filelist (list of linker input files) in case we
6554 // need it later
6555 for (const auto &II : Inputs) {
6556 if (!II.isFilename()) {
6557 // This is a linker input argument.
6558 // We cannot mix input arguments and file names in a -filelist input, thus
6559 // we prematurely stop our list (remaining files shall be passed as
6560 // arguments).
6561 if (InputFileList.size() > 0)
6562 break;
6563
6564 continue;
6565 }
6566
6567 InputFileList.push_back(II.getFilename());
6568 }
6569
6570 if (!Args.hasArg(options::OPT_nostdlib) &&
6571 !Args.hasArg(options::OPT_nodefaultlibs))
6572 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
6573
6574 if (isObjCRuntimeLinked(Args) && !Args.hasArg(options::OPT_nostdlib) &&
6575 !Args.hasArg(options::OPT_nodefaultlibs)) {
6576 // We use arclite library for both ARC and subscripting support.
6577 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
6578
6579 CmdArgs.push_back("-framework");
6580 CmdArgs.push_back("Foundation");
6581 // Link libobj.
6582 CmdArgs.push_back("-lobjc");
6583 }
6584
6585 if (LinkingOutput) {
6586 CmdArgs.push_back("-arch_multiple");
6587 CmdArgs.push_back("-final_output");
6588 CmdArgs.push_back(LinkingOutput);
6589 }
6590
6591 if (Args.hasArg(options::OPT_fnested_functions))
6592 CmdArgs.push_back("-allow_stack_execute");
6593
6594 // TODO: It would be nice to use addProfileRT() here, but darwin's compiler-rt
6595 // paths are different enough from other toolchains that this needs a fair
6596 // amount of refactoring done first.
6597 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
6598
6599 if (!Args.hasArg(options::OPT_nostdlib) &&
6600 !Args.hasArg(options::OPT_nodefaultlibs)) {
6601 if (getToolChain().getDriver().CCCIsCXX())
6602 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6603
6604 // link_ssp spec is empty.
6605
6606 // Let the tool chain choose which runtime library to link.
6607 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
6608 }
6609
6610 if (!Args.hasArg(options::OPT_nostdlib) &&
6611 !Args.hasArg(options::OPT_nostartfiles)) {
6612 // endfile_spec is empty.
6613 }
6614
6615 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6616 Args.AddAllArgs(CmdArgs, options::OPT_F);
6617
6618 // -iframework should be forwarded as -F.
6619 for (const Arg *A : Args.filtered(options::OPT_iframework))
6620 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
6621
6622 if (!Args.hasArg(options::OPT_nostdlib) &&
6623 !Args.hasArg(options::OPT_nodefaultlibs)) {
6624 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6625 if (A->getValue() == StringRef("Accelerate")) {
6626 CmdArgs.push_back("-framework");
6627 CmdArgs.push_back("Accelerate");
6628 }
6629 }
6630 }
6631
6632 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6633 std::unique_ptr<Command> Cmd =
6634 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
6635 Cmd->setInputFileList(std::move(InputFileList));
6636 C.addCommand(std::move(Cmd));
6637 }
6638
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6639 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
6640 const InputInfo &Output,
6641 const InputInfoList &Inputs,
6642 const ArgList &Args,
6643 const char *LinkingOutput) const {
6644 ArgStringList CmdArgs;
6645
6646 CmdArgs.push_back("-create");
6647 assert(Output.isFilename() && "Unexpected lipo output.");
6648
6649 CmdArgs.push_back("-output");
6650 CmdArgs.push_back(Output.getFilename());
6651
6652 for (const auto &II : Inputs) {
6653 assert(II.isFilename() && "Unexpected lipo input.");
6654 CmdArgs.push_back(II.getFilename());
6655 }
6656
6657 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
6658 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6659 }
6660
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6661 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
6662 const InputInfo &Output,
6663 const InputInfoList &Inputs,
6664 const ArgList &Args,
6665 const char *LinkingOutput) const {
6666 ArgStringList CmdArgs;
6667
6668 CmdArgs.push_back("-o");
6669 CmdArgs.push_back(Output.getFilename());
6670
6671 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6672 const InputInfo &Input = Inputs[0];
6673 assert(Input.isFilename() && "Unexpected dsymutil input.");
6674 CmdArgs.push_back(Input.getFilename());
6675
6676 const char *Exec =
6677 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
6678 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6679 }
6680
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6681 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
6682 const InputInfo &Output,
6683 const InputInfoList &Inputs,
6684 const ArgList &Args,
6685 const char *LinkingOutput) const {
6686 ArgStringList CmdArgs;
6687 CmdArgs.push_back("--verify");
6688 CmdArgs.push_back("--debug-info");
6689 CmdArgs.push_back("--eh-frame");
6690 CmdArgs.push_back("--quiet");
6691
6692 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6693 const InputInfo &Input = Inputs[0];
6694 assert(Input.isFilename() && "Unexpected verify input");
6695
6696 // Grabbing the output of the earlier dsymutil run.
6697 CmdArgs.push_back(Input.getFilename());
6698
6699 const char *Exec =
6700 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
6701 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6702 }
6703
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6704 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6705 const InputInfo &Output,
6706 const InputInfoList &Inputs,
6707 const ArgList &Args,
6708 const char *LinkingOutput) const {
6709 claimNoWarnArgs(Args);
6710 ArgStringList CmdArgs;
6711
6712 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6713
6714 CmdArgs.push_back("-o");
6715 CmdArgs.push_back(Output.getFilename());
6716
6717 for (const auto &II : Inputs)
6718 CmdArgs.push_back(II.getFilename());
6719
6720 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6721 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6722 }
6723
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6724 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6725 const InputInfo &Output,
6726 const InputInfoList &Inputs,
6727 const ArgList &Args,
6728 const char *LinkingOutput) const {
6729 // FIXME: Find a real GCC, don't hard-code versions here
6730 std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
6731 const llvm::Triple &T = getToolChain().getTriple();
6732 std::string LibPath = "/usr/lib/";
6733 const llvm::Triple::ArchType Arch = T.getArch();
6734 switch (Arch) {
6735 case llvm::Triple::x86:
6736 GCCLibPath +=
6737 ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
6738 break;
6739 case llvm::Triple::x86_64:
6740 GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
6741 GCCLibPath += "/4.5.2/amd64/";
6742 LibPath += "amd64/";
6743 break;
6744 default:
6745 llvm_unreachable("Unsupported architecture");
6746 }
6747
6748 ArgStringList CmdArgs;
6749
6750 // Demangle C++ names in errors
6751 CmdArgs.push_back("-C");
6752
6753 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6754 (!Args.hasArg(options::OPT_shared))) {
6755 CmdArgs.push_back("-e");
6756 CmdArgs.push_back("_start");
6757 }
6758
6759 if (Args.hasArg(options::OPT_static)) {
6760 CmdArgs.push_back("-Bstatic");
6761 CmdArgs.push_back("-dn");
6762 } else {
6763 CmdArgs.push_back("-Bdynamic");
6764 if (Args.hasArg(options::OPT_shared)) {
6765 CmdArgs.push_back("-shared");
6766 } else {
6767 CmdArgs.push_back("--dynamic-linker");
6768 CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
6769 }
6770 }
6771
6772 if (Output.isFilename()) {
6773 CmdArgs.push_back("-o");
6774 CmdArgs.push_back(Output.getFilename());
6775 } else {
6776 assert(Output.isNothing() && "Invalid output.");
6777 }
6778
6779 if (!Args.hasArg(options::OPT_nostdlib) &&
6780 !Args.hasArg(options::OPT_nostartfiles)) {
6781 if (!Args.hasArg(options::OPT_shared)) {
6782 CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
6783 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6784 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6785 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6786 } else {
6787 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6788 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6789 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6790 }
6791 if (getToolChain().getDriver().CCCIsCXX())
6792 CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
6793 }
6794
6795 CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
6796
6797 Args.AddAllArgs(CmdArgs, options::OPT_L);
6798 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6799 Args.AddAllArgs(CmdArgs, options::OPT_e);
6800 Args.AddAllArgs(CmdArgs, options::OPT_r);
6801
6802 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6803
6804 if (!Args.hasArg(options::OPT_nostdlib) &&
6805 !Args.hasArg(options::OPT_nodefaultlibs)) {
6806 if (getToolChain().getDriver().CCCIsCXX())
6807 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6808 CmdArgs.push_back("-lgcc_s");
6809 if (!Args.hasArg(options::OPT_shared)) {
6810 CmdArgs.push_back("-lgcc");
6811 CmdArgs.push_back("-lc");
6812 CmdArgs.push_back("-lm");
6813 }
6814 }
6815
6816 if (!Args.hasArg(options::OPT_nostdlib) &&
6817 !Args.hasArg(options::OPT_nostartfiles)) {
6818 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
6819 }
6820 CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
6821
6822 addProfileRT(getToolChain(), Args, CmdArgs);
6823
6824 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6825 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6826 }
6827
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6828 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6829 const InputInfo &Output,
6830 const InputInfoList &Inputs,
6831 const ArgList &Args,
6832 const char *LinkingOutput) const {
6833 claimNoWarnArgs(Args);
6834 ArgStringList CmdArgs;
6835 bool NeedsKPIC = false;
6836
6837 switch (getToolChain().getArch()) {
6838 case llvm::Triple::x86:
6839 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6840 // instruct as in the base system to assemble 32-bit code.
6841 CmdArgs.push_back("--32");
6842 break;
6843
6844 case llvm::Triple::ppc:
6845 CmdArgs.push_back("-mppc");
6846 CmdArgs.push_back("-many");
6847 break;
6848
6849 case llvm::Triple::sparc:
6850 case llvm::Triple::sparcel:
6851 CmdArgs.push_back("-32");
6852 NeedsKPIC = true;
6853 break;
6854
6855 case llvm::Triple::sparcv9:
6856 CmdArgs.push_back("-64");
6857 CmdArgs.push_back("-Av9a");
6858 NeedsKPIC = true;
6859 break;
6860
6861 case llvm::Triple::mips64:
6862 case llvm::Triple::mips64el: {
6863 StringRef CPUName;
6864 StringRef ABIName;
6865 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6866
6867 CmdArgs.push_back("-mabi");
6868 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6869
6870 if (getToolChain().getArch() == llvm::Triple::mips64)
6871 CmdArgs.push_back("-EB");
6872 else
6873 CmdArgs.push_back("-EL");
6874
6875 NeedsKPIC = true;
6876 break;
6877 }
6878
6879 default:
6880 break;
6881 }
6882
6883 if (NeedsKPIC)
6884 addAssemblerKPIC(Args, CmdArgs);
6885
6886 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6887
6888 CmdArgs.push_back("-o");
6889 CmdArgs.push_back(Output.getFilename());
6890
6891 for (const auto &II : Inputs)
6892 CmdArgs.push_back(II.getFilename());
6893
6894 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6895 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6896 }
6897
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6898 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6899 const InputInfo &Output,
6900 const InputInfoList &Inputs,
6901 const ArgList &Args,
6902 const char *LinkingOutput) const {
6903 const Driver &D = getToolChain().getDriver();
6904 ArgStringList CmdArgs;
6905
6906 // Silence warning for "clang -g foo.o -o foo"
6907 Args.ClaimAllArgs(options::OPT_g_Group);
6908 // and "clang -emit-llvm foo.o -o foo"
6909 Args.ClaimAllArgs(options::OPT_emit_llvm);
6910 // and for "clang -w foo.o -o foo". Other warning options are already
6911 // handled somewhere else.
6912 Args.ClaimAllArgs(options::OPT_w);
6913
6914 if (getToolChain().getArch() == llvm::Triple::mips64)
6915 CmdArgs.push_back("-EB");
6916 else if (getToolChain().getArch() == llvm::Triple::mips64el)
6917 CmdArgs.push_back("-EL");
6918
6919 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6920 (!Args.hasArg(options::OPT_shared))) {
6921 CmdArgs.push_back("-e");
6922 CmdArgs.push_back("__start");
6923 }
6924
6925 if (Args.hasArg(options::OPT_static)) {
6926 CmdArgs.push_back("-Bstatic");
6927 } else {
6928 if (Args.hasArg(options::OPT_rdynamic))
6929 CmdArgs.push_back("-export-dynamic");
6930 CmdArgs.push_back("--eh-frame-hdr");
6931 CmdArgs.push_back("-Bdynamic");
6932 if (Args.hasArg(options::OPT_shared)) {
6933 CmdArgs.push_back("-shared");
6934 } else {
6935 CmdArgs.push_back("-dynamic-linker");
6936 CmdArgs.push_back("/usr/libexec/ld.so");
6937 }
6938 }
6939
6940 if (Args.hasArg(options::OPT_nopie))
6941 CmdArgs.push_back("-nopie");
6942
6943 if (Output.isFilename()) {
6944 CmdArgs.push_back("-o");
6945 CmdArgs.push_back(Output.getFilename());
6946 } else {
6947 assert(Output.isNothing() && "Invalid output.");
6948 }
6949
6950 if (!Args.hasArg(options::OPT_nostdlib) &&
6951 !Args.hasArg(options::OPT_nostartfiles)) {
6952 if (!Args.hasArg(options::OPT_shared)) {
6953 if (Args.hasArg(options::OPT_pg))
6954 CmdArgs.push_back(
6955 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
6956 else
6957 CmdArgs.push_back(
6958 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
6959 CmdArgs.push_back(
6960 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6961 } else {
6962 CmdArgs.push_back(
6963 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6964 }
6965 }
6966
6967 std::string Triple = getToolChain().getTripleString();
6968 if (Triple.substr(0, 6) == "x86_64")
6969 Triple.replace(0, 6, "amd64");
6970 CmdArgs.push_back(
6971 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
6972
6973 Args.AddAllArgs(CmdArgs, options::OPT_L);
6974 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6975 Args.AddAllArgs(CmdArgs, options::OPT_e);
6976 Args.AddAllArgs(CmdArgs, options::OPT_s);
6977 Args.AddAllArgs(CmdArgs, options::OPT_t);
6978 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6979 Args.AddAllArgs(CmdArgs, options::OPT_r);
6980
6981 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6982
6983 if (!Args.hasArg(options::OPT_nostdlib) &&
6984 !Args.hasArg(options::OPT_nodefaultlibs)) {
6985 if (D.CCCIsCXX()) {
6986 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6987 if (Args.hasArg(options::OPT_pg))
6988 CmdArgs.push_back("-lm_p");
6989 else
6990 CmdArgs.push_back("-lm");
6991 }
6992
6993 // FIXME: For some reason GCC passes -lgcc before adding
6994 // the default system libraries. Just mimic this for now.
6995 CmdArgs.push_back("-lgcc");
6996
6997 if (Args.hasArg(options::OPT_pthread)) {
6998 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
6999 CmdArgs.push_back("-lpthread_p");
7000 else
7001 CmdArgs.push_back("-lpthread");
7002 }
7003
7004 if (!Args.hasArg(options::OPT_shared)) {
7005 if (Args.hasArg(options::OPT_pg))
7006 CmdArgs.push_back("-lc_p");
7007 else
7008 CmdArgs.push_back("-lc");
7009 }
7010
7011 CmdArgs.push_back("-lgcc");
7012 }
7013
7014 if (!Args.hasArg(options::OPT_nostdlib) &&
7015 !Args.hasArg(options::OPT_nostartfiles)) {
7016 if (!Args.hasArg(options::OPT_shared))
7017 CmdArgs.push_back(
7018 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7019 else
7020 CmdArgs.push_back(
7021 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7022 }
7023
7024 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7025 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7026 }
7027
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7028 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7029 const InputInfo &Output,
7030 const InputInfoList &Inputs,
7031 const ArgList &Args,
7032 const char *LinkingOutput) const {
7033 claimNoWarnArgs(Args);
7034 ArgStringList CmdArgs;
7035
7036 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7037
7038 CmdArgs.push_back("-o");
7039 CmdArgs.push_back(Output.getFilename());
7040
7041 for (const auto &II : Inputs)
7042 CmdArgs.push_back(II.getFilename());
7043
7044 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7045 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7046 }
7047
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7048 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7049 const InputInfo &Output,
7050 const InputInfoList &Inputs,
7051 const ArgList &Args,
7052 const char *LinkingOutput) const {
7053 const Driver &D = getToolChain().getDriver();
7054 ArgStringList CmdArgs;
7055
7056 if ((!Args.hasArg(options::OPT_nostdlib)) &&
7057 (!Args.hasArg(options::OPT_shared))) {
7058 CmdArgs.push_back("-e");
7059 CmdArgs.push_back("__start");
7060 }
7061
7062 if (Args.hasArg(options::OPT_static)) {
7063 CmdArgs.push_back("-Bstatic");
7064 } else {
7065 if (Args.hasArg(options::OPT_rdynamic))
7066 CmdArgs.push_back("-export-dynamic");
7067 CmdArgs.push_back("--eh-frame-hdr");
7068 CmdArgs.push_back("-Bdynamic");
7069 if (Args.hasArg(options::OPT_shared)) {
7070 CmdArgs.push_back("-shared");
7071 } else {
7072 CmdArgs.push_back("-dynamic-linker");
7073 CmdArgs.push_back("/usr/libexec/ld.so");
7074 }
7075 }
7076
7077 if (Output.isFilename()) {
7078 CmdArgs.push_back("-o");
7079 CmdArgs.push_back(Output.getFilename());
7080 } else {
7081 assert(Output.isNothing() && "Invalid output.");
7082 }
7083
7084 if (!Args.hasArg(options::OPT_nostdlib) &&
7085 !Args.hasArg(options::OPT_nostartfiles)) {
7086 if (!Args.hasArg(options::OPT_shared)) {
7087 if (Args.hasArg(options::OPT_pg))
7088 CmdArgs.push_back(
7089 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7090 else
7091 CmdArgs.push_back(
7092 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7093 CmdArgs.push_back(
7094 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7095 } else {
7096 CmdArgs.push_back(
7097 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7098 }
7099 }
7100
7101 Args.AddAllArgs(CmdArgs, options::OPT_L);
7102 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7103 Args.AddAllArgs(CmdArgs, options::OPT_e);
7104
7105 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7106
7107 if (!Args.hasArg(options::OPT_nostdlib) &&
7108 !Args.hasArg(options::OPT_nodefaultlibs)) {
7109 if (D.CCCIsCXX()) {
7110 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7111 if (Args.hasArg(options::OPT_pg))
7112 CmdArgs.push_back("-lm_p");
7113 else
7114 CmdArgs.push_back("-lm");
7115 }
7116
7117 if (Args.hasArg(options::OPT_pthread)) {
7118 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7119 CmdArgs.push_back("-lpthread_p");
7120 else
7121 CmdArgs.push_back("-lpthread");
7122 }
7123
7124 if (!Args.hasArg(options::OPT_shared)) {
7125 if (Args.hasArg(options::OPT_pg))
7126 CmdArgs.push_back("-lc_p");
7127 else
7128 CmdArgs.push_back("-lc");
7129 }
7130
7131 StringRef MyArch;
7132 switch (getToolChain().getArch()) {
7133 case llvm::Triple::arm:
7134 MyArch = "arm";
7135 break;
7136 case llvm::Triple::x86:
7137 MyArch = "i386";
7138 break;
7139 case llvm::Triple::x86_64:
7140 MyArch = "amd64";
7141 break;
7142 default:
7143 llvm_unreachable("Unsupported architecture");
7144 }
7145 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7146 }
7147
7148 if (!Args.hasArg(options::OPT_nostdlib) &&
7149 !Args.hasArg(options::OPT_nostartfiles)) {
7150 if (!Args.hasArg(options::OPT_shared))
7151 CmdArgs.push_back(
7152 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7153 else
7154 CmdArgs.push_back(
7155 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7156 }
7157
7158 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7159 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7160 }
7161
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7162 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7163 const InputInfo &Output,
7164 const InputInfoList &Inputs,
7165 const ArgList &Args,
7166 const char *LinkingOutput) const {
7167 claimNoWarnArgs(Args);
7168 ArgStringList CmdArgs;
7169
7170 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7171 // instruct as in the base system to assemble 32-bit code.
7172 if (getToolChain().getArch() == llvm::Triple::x86)
7173 CmdArgs.push_back("--32");
7174 else if (getToolChain().getArch() == llvm::Triple::ppc)
7175 CmdArgs.push_back("-a32");
7176 else if (getToolChain().getArch() == llvm::Triple::mips ||
7177 getToolChain().getArch() == llvm::Triple::mipsel ||
7178 getToolChain().getArch() == llvm::Triple::mips64 ||
7179 getToolChain().getArch() == llvm::Triple::mips64el) {
7180 StringRef CPUName;
7181 StringRef ABIName;
7182 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7183
7184 CmdArgs.push_back("-march");
7185 CmdArgs.push_back(CPUName.data());
7186
7187 CmdArgs.push_back("-mabi");
7188 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7189
7190 if (getToolChain().getArch() == llvm::Triple::mips ||
7191 getToolChain().getArch() == llvm::Triple::mips64)
7192 CmdArgs.push_back("-EB");
7193 else
7194 CmdArgs.push_back("-EL");
7195
7196 addAssemblerKPIC(Args, CmdArgs);
7197 } else if (getToolChain().getArch() == llvm::Triple::arm ||
7198 getToolChain().getArch() == llvm::Triple::armeb ||
7199 getToolChain().getArch() == llvm::Triple::thumb ||
7200 getToolChain().getArch() == llvm::Triple::thumbeb) {
7201 const Driver &D = getToolChain().getDriver();
7202 const llvm::Triple &Triple = getToolChain().getTriple();
7203 StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
7204
7205 if (FloatABI == "hard") {
7206 CmdArgs.push_back("-mfpu=vfp");
7207 } else {
7208 CmdArgs.push_back("-mfpu=softvfp");
7209 }
7210
7211 switch (getToolChain().getTriple().getEnvironment()) {
7212 case llvm::Triple::GNUEABIHF:
7213 case llvm::Triple::GNUEABI:
7214 case llvm::Triple::EABI:
7215 CmdArgs.push_back("-meabi=5");
7216 break;
7217
7218 default:
7219 CmdArgs.push_back("-matpcs");
7220 }
7221 } else if (getToolChain().getArch() == llvm::Triple::sparc ||
7222 getToolChain().getArch() == llvm::Triple::sparcel ||
7223 getToolChain().getArch() == llvm::Triple::sparcv9) {
7224 if (getToolChain().getArch() == llvm::Triple::sparc)
7225 CmdArgs.push_back("-Av8plusa");
7226 else
7227 CmdArgs.push_back("-Av9a");
7228
7229 addAssemblerKPIC(Args, CmdArgs);
7230 }
7231
7232 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7233
7234 CmdArgs.push_back("-o");
7235 CmdArgs.push_back(Output.getFilename());
7236
7237 for (const auto &II : Inputs)
7238 CmdArgs.push_back(II.getFilename());
7239
7240 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7241 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7242 }
7243
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7244 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7245 const InputInfo &Output,
7246 const InputInfoList &Inputs,
7247 const ArgList &Args,
7248 const char *LinkingOutput) const {
7249 const toolchains::FreeBSD &ToolChain =
7250 static_cast<const toolchains::FreeBSD &>(getToolChain());
7251 const Driver &D = ToolChain.getDriver();
7252 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7253 const bool IsPIE =
7254 !Args.hasArg(options::OPT_shared) &&
7255 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7256 ArgStringList CmdArgs;
7257
7258 // Silence warning for "clang -g foo.o -o foo"
7259 Args.ClaimAllArgs(options::OPT_g_Group);
7260 // and "clang -emit-llvm foo.o -o foo"
7261 Args.ClaimAllArgs(options::OPT_emit_llvm);
7262 // and for "clang -w foo.o -o foo". Other warning options are already
7263 // handled somewhere else.
7264 Args.ClaimAllArgs(options::OPT_w);
7265
7266 if (!D.SysRoot.empty())
7267 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7268
7269 if (IsPIE)
7270 CmdArgs.push_back("-pie");
7271
7272 if (Args.hasArg(options::OPT_static)) {
7273 CmdArgs.push_back("-Bstatic");
7274 } else {
7275 if (Args.hasArg(options::OPT_rdynamic))
7276 CmdArgs.push_back("-export-dynamic");
7277 CmdArgs.push_back("--eh-frame-hdr");
7278 if (Args.hasArg(options::OPT_shared)) {
7279 CmdArgs.push_back("-Bshareable");
7280 } else {
7281 CmdArgs.push_back("-dynamic-linker");
7282 CmdArgs.push_back("/libexec/ld-elf.so.1");
7283 }
7284 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7285 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7286 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7287 CmdArgs.push_back("--hash-style=both");
7288 }
7289 }
7290 CmdArgs.push_back("--enable-new-dtags");
7291 }
7292
7293 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7294 // instruct ld in the base system to link 32-bit code.
7295 if (Arch == llvm::Triple::x86) {
7296 CmdArgs.push_back("-m");
7297 CmdArgs.push_back("elf_i386_fbsd");
7298 }
7299
7300 if (Arch == llvm::Triple::ppc) {
7301 CmdArgs.push_back("-m");
7302 CmdArgs.push_back("elf32ppc_fbsd");
7303 }
7304
7305 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7306 if (ToolChain.getArch() == llvm::Triple::mips ||
7307 ToolChain.getArch() == llvm::Triple::mipsel ||
7308 ToolChain.getArch() == llvm::Triple::mips64 ||
7309 ToolChain.getArch() == llvm::Triple::mips64el) {
7310 StringRef v = A->getValue();
7311 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7312 A->claim();
7313 }
7314 }
7315
7316 if (Output.isFilename()) {
7317 CmdArgs.push_back("-o");
7318 CmdArgs.push_back(Output.getFilename());
7319 } else {
7320 assert(Output.isNothing() && "Invalid output.");
7321 }
7322
7323 if (!Args.hasArg(options::OPT_nostdlib) &&
7324 !Args.hasArg(options::OPT_nostartfiles)) {
7325 const char *crt1 = nullptr;
7326 if (!Args.hasArg(options::OPT_shared)) {
7327 if (Args.hasArg(options::OPT_pg))
7328 crt1 = "gcrt1.o";
7329 else if (IsPIE)
7330 crt1 = "Scrt1.o";
7331 else
7332 crt1 = "crt1.o";
7333 }
7334 if (crt1)
7335 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7336
7337 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7338
7339 const char *crtbegin = nullptr;
7340 if (Args.hasArg(options::OPT_static))
7341 crtbegin = "crtbeginT.o";
7342 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7343 crtbegin = "crtbeginS.o";
7344 else
7345 crtbegin = "crtbegin.o";
7346
7347 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7348 }
7349
7350 Args.AddAllArgs(CmdArgs, options::OPT_L);
7351 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
7352 for (const auto &Path : Paths)
7353 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7354 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7355 Args.AddAllArgs(CmdArgs, options::OPT_e);
7356 Args.AddAllArgs(CmdArgs, options::OPT_s);
7357 Args.AddAllArgs(CmdArgs, options::OPT_t);
7358 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7359 Args.AddAllArgs(CmdArgs, options::OPT_r);
7360
7361 if (D.IsUsingLTO(Args))
7362 AddGoldPlugin(ToolChain, Args, CmdArgs);
7363
7364 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7365 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7366
7367 if (!Args.hasArg(options::OPT_nostdlib) &&
7368 !Args.hasArg(options::OPT_nodefaultlibs)) {
7369 addOpenMPRuntime(CmdArgs, ToolChain, Args);
7370 if (D.CCCIsCXX()) {
7371 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7372 if (Args.hasArg(options::OPT_pg))
7373 CmdArgs.push_back("-lm_p");
7374 else
7375 CmdArgs.push_back("-lm");
7376 }
7377 if (NeedsSanitizerDeps)
7378 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7379 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7380 // the default system libraries. Just mimic this for now.
7381 if (Args.hasArg(options::OPT_pg))
7382 CmdArgs.push_back("-lgcc_p");
7383 else
7384 CmdArgs.push_back("-lgcc");
7385 if (Args.hasArg(options::OPT_static)) {
7386 CmdArgs.push_back("-lgcc_eh");
7387 } else if (Args.hasArg(options::OPT_pg)) {
7388 CmdArgs.push_back("-lgcc_eh_p");
7389 } else {
7390 CmdArgs.push_back("--as-needed");
7391 CmdArgs.push_back("-lgcc_s");
7392 CmdArgs.push_back("--no-as-needed");
7393 }
7394
7395 if (Args.hasArg(options::OPT_pthread)) {
7396 if (Args.hasArg(options::OPT_pg))
7397 CmdArgs.push_back("-lpthread_p");
7398 else
7399 CmdArgs.push_back("-lpthread");
7400 }
7401
7402 if (Args.hasArg(options::OPT_pg)) {
7403 if (Args.hasArg(options::OPT_shared))
7404 CmdArgs.push_back("-lc");
7405 else
7406 CmdArgs.push_back("-lc_p");
7407 CmdArgs.push_back("-lgcc_p");
7408 } else {
7409 CmdArgs.push_back("-lc");
7410 CmdArgs.push_back("-lgcc");
7411 }
7412
7413 if (Args.hasArg(options::OPT_static)) {
7414 CmdArgs.push_back("-lgcc_eh");
7415 } else if (Args.hasArg(options::OPT_pg)) {
7416 CmdArgs.push_back("-lgcc_eh_p");
7417 } else {
7418 CmdArgs.push_back("--as-needed");
7419 CmdArgs.push_back("-lgcc_s");
7420 CmdArgs.push_back("--no-as-needed");
7421 }
7422 }
7423
7424 if (!Args.hasArg(options::OPT_nostdlib) &&
7425 !Args.hasArg(options::OPT_nostartfiles)) {
7426 if (Args.hasArg(options::OPT_shared) || IsPIE)
7427 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
7428 else
7429 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7430 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7431 }
7432
7433 addProfileRT(ToolChain, Args, CmdArgs);
7434
7435 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7436 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7437 }
7438
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7439 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7440 const InputInfo &Output,
7441 const InputInfoList &Inputs,
7442 const ArgList &Args,
7443 const char *LinkingOutput) const {
7444 claimNoWarnArgs(Args);
7445 ArgStringList CmdArgs;
7446
7447 // GNU as needs different flags for creating the correct output format
7448 // on architectures with different ABIs or optional feature sets.
7449 switch (getToolChain().getArch()) {
7450 case llvm::Triple::x86:
7451 CmdArgs.push_back("--32");
7452 break;
7453 case llvm::Triple::arm:
7454 case llvm::Triple::armeb:
7455 case llvm::Triple::thumb:
7456 case llvm::Triple::thumbeb: {
7457 StringRef MArch, MCPU;
7458 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
7459 std::string Arch =
7460 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
7461 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
7462 break;
7463 }
7464
7465 case llvm::Triple::mips:
7466 case llvm::Triple::mipsel:
7467 case llvm::Triple::mips64:
7468 case llvm::Triple::mips64el: {
7469 StringRef CPUName;
7470 StringRef ABIName;
7471 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7472
7473 CmdArgs.push_back("-march");
7474 CmdArgs.push_back(CPUName.data());
7475
7476 CmdArgs.push_back("-mabi");
7477 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7478
7479 if (getToolChain().getArch() == llvm::Triple::mips ||
7480 getToolChain().getArch() == llvm::Triple::mips64)
7481 CmdArgs.push_back("-EB");
7482 else
7483 CmdArgs.push_back("-EL");
7484
7485 addAssemblerKPIC(Args, CmdArgs);
7486 break;
7487 }
7488
7489 case llvm::Triple::sparc:
7490 case llvm::Triple::sparcel:
7491 CmdArgs.push_back("-32");
7492 addAssemblerKPIC(Args, CmdArgs);
7493 break;
7494
7495 case llvm::Triple::sparcv9:
7496 CmdArgs.push_back("-64");
7497 CmdArgs.push_back("-Av9");
7498 addAssemblerKPIC(Args, CmdArgs);
7499 break;
7500
7501 default:
7502 break;
7503 }
7504
7505 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7506
7507 CmdArgs.push_back("-o");
7508 CmdArgs.push_back(Output.getFilename());
7509
7510 for (const auto &II : Inputs)
7511 CmdArgs.push_back(II.getFilename());
7512
7513 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
7514 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7515 }
7516
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7517 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7518 const InputInfo &Output,
7519 const InputInfoList &Inputs,
7520 const ArgList &Args,
7521 const char *LinkingOutput) const {
7522 const Driver &D = getToolChain().getDriver();
7523 ArgStringList CmdArgs;
7524
7525 if (!D.SysRoot.empty())
7526 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7527
7528 CmdArgs.push_back("--eh-frame-hdr");
7529 if (Args.hasArg(options::OPT_static)) {
7530 CmdArgs.push_back("-Bstatic");
7531 } else {
7532 if (Args.hasArg(options::OPT_rdynamic))
7533 CmdArgs.push_back("-export-dynamic");
7534 if (Args.hasArg(options::OPT_shared)) {
7535 CmdArgs.push_back("-Bshareable");
7536 } else {
7537 CmdArgs.push_back("-dynamic-linker");
7538 CmdArgs.push_back("/libexec/ld.elf_so");
7539 }
7540 }
7541
7542 // Many NetBSD architectures support more than one ABI.
7543 // Determine the correct emulation for ld.
7544 switch (getToolChain().getArch()) {
7545 case llvm::Triple::x86:
7546 CmdArgs.push_back("-m");
7547 CmdArgs.push_back("elf_i386");
7548 break;
7549 case llvm::Triple::arm:
7550 case llvm::Triple::thumb:
7551 CmdArgs.push_back("-m");
7552 switch (getToolChain().getTriple().getEnvironment()) {
7553 case llvm::Triple::EABI:
7554 case llvm::Triple::GNUEABI:
7555 CmdArgs.push_back("armelf_nbsd_eabi");
7556 break;
7557 case llvm::Triple::EABIHF:
7558 case llvm::Triple::GNUEABIHF:
7559 CmdArgs.push_back("armelf_nbsd_eabihf");
7560 break;
7561 default:
7562 CmdArgs.push_back("armelf_nbsd");
7563 break;
7564 }
7565 break;
7566 case llvm::Triple::armeb:
7567 case llvm::Triple::thumbeb:
7568 arm::appendEBLinkFlags(
7569 Args, CmdArgs,
7570 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7571 CmdArgs.push_back("-m");
7572 switch (getToolChain().getTriple().getEnvironment()) {
7573 case llvm::Triple::EABI:
7574 case llvm::Triple::GNUEABI:
7575 CmdArgs.push_back("armelfb_nbsd_eabi");
7576 break;
7577 case llvm::Triple::EABIHF:
7578 case llvm::Triple::GNUEABIHF:
7579 CmdArgs.push_back("armelfb_nbsd_eabihf");
7580 break;
7581 default:
7582 CmdArgs.push_back("armelfb_nbsd");
7583 break;
7584 }
7585 break;
7586 case llvm::Triple::mips64:
7587 case llvm::Triple::mips64el:
7588 if (mips::hasMipsAbiArg(Args, "32")) {
7589 CmdArgs.push_back("-m");
7590 if (getToolChain().getArch() == llvm::Triple::mips64)
7591 CmdArgs.push_back("elf32btsmip");
7592 else
7593 CmdArgs.push_back("elf32ltsmip");
7594 } else if (mips::hasMipsAbiArg(Args, "64")) {
7595 CmdArgs.push_back("-m");
7596 if (getToolChain().getArch() == llvm::Triple::mips64)
7597 CmdArgs.push_back("elf64btsmip");
7598 else
7599 CmdArgs.push_back("elf64ltsmip");
7600 }
7601 break;
7602 case llvm::Triple::ppc:
7603 CmdArgs.push_back("-m");
7604 CmdArgs.push_back("elf32ppc_nbsd");
7605 break;
7606
7607 case llvm::Triple::ppc64:
7608 case llvm::Triple::ppc64le:
7609 CmdArgs.push_back("-m");
7610 CmdArgs.push_back("elf64ppc");
7611 break;
7612
7613 case llvm::Triple::sparc:
7614 CmdArgs.push_back("-m");
7615 CmdArgs.push_back("elf32_sparc");
7616 break;
7617
7618 case llvm::Triple::sparcv9:
7619 CmdArgs.push_back("-m");
7620 CmdArgs.push_back("elf64_sparc");
7621 break;
7622
7623 default:
7624 break;
7625 }
7626
7627 if (Output.isFilename()) {
7628 CmdArgs.push_back("-o");
7629 CmdArgs.push_back(Output.getFilename());
7630 } else {
7631 assert(Output.isNothing() && "Invalid output.");
7632 }
7633
7634 if (!Args.hasArg(options::OPT_nostdlib) &&
7635 !Args.hasArg(options::OPT_nostartfiles)) {
7636 if (!Args.hasArg(options::OPT_shared)) {
7637 CmdArgs.push_back(
7638 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7639 CmdArgs.push_back(
7640 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7641 CmdArgs.push_back(
7642 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7643 } else {
7644 CmdArgs.push_back(
7645 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7646 CmdArgs.push_back(
7647 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7648 }
7649 }
7650
7651 Args.AddAllArgs(CmdArgs, options::OPT_L);
7652 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7653 Args.AddAllArgs(CmdArgs, options::OPT_e);
7654 Args.AddAllArgs(CmdArgs, options::OPT_s);
7655 Args.AddAllArgs(CmdArgs, options::OPT_t);
7656 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7657 Args.AddAllArgs(CmdArgs, options::OPT_r);
7658
7659 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7660
7661 unsigned Major, Minor, Micro;
7662 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
7663 bool useLibgcc = true;
7664 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
7665 switch (getToolChain().getArch()) {
7666 case llvm::Triple::aarch64:
7667 case llvm::Triple::arm:
7668 case llvm::Triple::armeb:
7669 case llvm::Triple::thumb:
7670 case llvm::Triple::thumbeb:
7671 case llvm::Triple::ppc:
7672 case llvm::Triple::ppc64:
7673 case llvm::Triple::ppc64le:
7674 case llvm::Triple::x86:
7675 case llvm::Triple::x86_64:
7676 useLibgcc = false;
7677 break;
7678 default:
7679 break;
7680 }
7681 }
7682
7683 if (!Args.hasArg(options::OPT_nostdlib) &&
7684 !Args.hasArg(options::OPT_nodefaultlibs)) {
7685 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7686 if (D.CCCIsCXX()) {
7687 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7688 CmdArgs.push_back("-lm");
7689 }
7690 if (Args.hasArg(options::OPT_pthread))
7691 CmdArgs.push_back("-lpthread");
7692 CmdArgs.push_back("-lc");
7693
7694 if (useLibgcc) {
7695 if (Args.hasArg(options::OPT_static)) {
7696 // libgcc_eh depends on libc, so resolve as much as possible,
7697 // pull in any new requirements from libc and then get the rest
7698 // of libgcc.
7699 CmdArgs.push_back("-lgcc_eh");
7700 CmdArgs.push_back("-lc");
7701 CmdArgs.push_back("-lgcc");
7702 } else {
7703 CmdArgs.push_back("-lgcc");
7704 CmdArgs.push_back("--as-needed");
7705 CmdArgs.push_back("-lgcc_s");
7706 CmdArgs.push_back("--no-as-needed");
7707 }
7708 }
7709 }
7710
7711 if (!Args.hasArg(options::OPT_nostdlib) &&
7712 !Args.hasArg(options::OPT_nostartfiles)) {
7713 if (!Args.hasArg(options::OPT_shared))
7714 CmdArgs.push_back(
7715 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7716 else
7717 CmdArgs.push_back(
7718 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7719 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7720 }
7721
7722 addProfileRT(getToolChain(), Args, CmdArgs);
7723
7724 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7725 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7726 }
7727
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7728 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7729 const InputInfo &Output,
7730 const InputInfoList &Inputs,
7731 const ArgList &Args,
7732 const char *LinkingOutput) const {
7733 claimNoWarnArgs(Args);
7734
7735 ArgStringList CmdArgs;
7736 bool NeedsKPIC = false;
7737
7738 switch (getToolChain().getArch()) {
7739 default:
7740 break;
7741 // Add --32/--64 to make sure we get the format we want.
7742 // This is incomplete
7743 case llvm::Triple::x86:
7744 CmdArgs.push_back("--32");
7745 break;
7746 case llvm::Triple::x86_64:
7747 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
7748 CmdArgs.push_back("--x32");
7749 else
7750 CmdArgs.push_back("--64");
7751 break;
7752 case llvm::Triple::ppc:
7753 CmdArgs.push_back("-a32");
7754 CmdArgs.push_back("-mppc");
7755 CmdArgs.push_back("-many");
7756 break;
7757 case llvm::Triple::ppc64:
7758 CmdArgs.push_back("-a64");
7759 CmdArgs.push_back("-mppc64");
7760 CmdArgs.push_back("-many");
7761 break;
7762 case llvm::Triple::ppc64le:
7763 CmdArgs.push_back("-a64");
7764 CmdArgs.push_back("-mppc64");
7765 CmdArgs.push_back("-many");
7766 CmdArgs.push_back("-mlittle-endian");
7767 break;
7768 case llvm::Triple::sparc:
7769 case llvm::Triple::sparcel:
7770 CmdArgs.push_back("-32");
7771 CmdArgs.push_back("-Av8plusa");
7772 NeedsKPIC = true;
7773 break;
7774 case llvm::Triple::sparcv9:
7775 CmdArgs.push_back("-64");
7776 CmdArgs.push_back("-Av9a");
7777 NeedsKPIC = true;
7778 break;
7779 case llvm::Triple::arm:
7780 case llvm::Triple::armeb:
7781 case llvm::Triple::thumb:
7782 case llvm::Triple::thumbeb: {
7783 const llvm::Triple &Triple = getToolChain().getTriple();
7784 switch (Triple.getSubArch()) {
7785 case llvm::Triple::ARMSubArch_v7:
7786 CmdArgs.push_back("-mfpu=neon");
7787 break;
7788 case llvm::Triple::ARMSubArch_v8:
7789 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7790 break;
7791 default:
7792 break;
7793 }
7794
7795 StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7796 getToolChain().getDriver(), Args,
7797 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7798 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7799
7800 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7801
7802 // FIXME: remove krait check when GNU tools support krait cpu
7803 // for now replace it with -march=armv7-a to avoid a lower
7804 // march from being picked in the absence of a cpu flag.
7805 Arg *A;
7806 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7807 StringRef(A->getValue()).lower() == "krait")
7808 CmdArgs.push_back("-march=armv7-a");
7809 else
7810 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7811 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7812 break;
7813 }
7814 case llvm::Triple::mips:
7815 case llvm::Triple::mipsel:
7816 case llvm::Triple::mips64:
7817 case llvm::Triple::mips64el: {
7818 StringRef CPUName;
7819 StringRef ABIName;
7820 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7821 ABIName = getGnuCompatibleMipsABIName(ABIName);
7822
7823 CmdArgs.push_back("-march");
7824 CmdArgs.push_back(CPUName.data());
7825
7826 CmdArgs.push_back("-mabi");
7827 CmdArgs.push_back(ABIName.data());
7828
7829 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7830 // or -mshared (not implemented) is in effect.
7831 bool IsPicOrPie = false;
7832 if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7833 options::OPT_fpic, options::OPT_fno_pic,
7834 options::OPT_fPIE, options::OPT_fno_PIE,
7835 options::OPT_fpie, options::OPT_fno_pie)) {
7836 if (A->getOption().matches(options::OPT_fPIC) ||
7837 A->getOption().matches(options::OPT_fpic) ||
7838 A->getOption().matches(options::OPT_fPIE) ||
7839 A->getOption().matches(options::OPT_fpie))
7840 IsPicOrPie = true;
7841 }
7842 if (!IsPicOrPie)
7843 CmdArgs.push_back("-mno-shared");
7844
7845 // LLVM doesn't support -mplt yet and acts as if it is always given.
7846 // However, -mplt has no effect with the N64 ABI.
7847 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7848
7849 if (getToolChain().getArch() == llvm::Triple::mips ||
7850 getToolChain().getArch() == llvm::Triple::mips64)
7851 CmdArgs.push_back("-EB");
7852 else
7853 CmdArgs.push_back("-EL");
7854
7855 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7856 if (StringRef(A->getValue()) == "2008")
7857 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7858 }
7859
7860 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7861 StringRef MIPSFloatABI = getMipsFloatABI(getToolChain().getDriver(), Args);
7862 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7863 options::OPT_mfp64)) {
7864 A->claim();
7865 A->render(Args, CmdArgs);
7866 } else if (mips::shouldUseFPXX(Args, getToolChain().getTriple(), CPUName,
7867 ABIName, MIPSFloatABI))
7868 CmdArgs.push_back("-mfpxx");
7869
7870 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7871 // -mno-mips16 is actually -no-mips16.
7872 if (Arg *A =
7873 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
7874 if (A->getOption().matches(options::OPT_mips16)) {
7875 A->claim();
7876 A->render(Args, CmdArgs);
7877 } else {
7878 A->claim();
7879 CmdArgs.push_back("-no-mips16");
7880 }
7881 }
7882
7883 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7884 options::OPT_mno_micromips);
7885 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7886 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7887
7888 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7889 // Do not use AddLastArg because not all versions of MIPS assembler
7890 // support -mmsa / -mno-msa options.
7891 if (A->getOption().matches(options::OPT_mmsa))
7892 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7893 }
7894
7895 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7896 options::OPT_msoft_float);
7897
7898 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
7899 options::OPT_msingle_float);
7900
7901 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7902 options::OPT_mno_odd_spreg);
7903
7904 NeedsKPIC = true;
7905 break;
7906 }
7907 case llvm::Triple::systemz: {
7908 // Always pass an -march option, since our default of z10 is later
7909 // than the GNU assembler's default.
7910 StringRef CPUName = getSystemZTargetCPU(Args);
7911 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7912 break;
7913 }
7914 }
7915
7916 if (NeedsKPIC)
7917 addAssemblerKPIC(Args, CmdArgs);
7918
7919 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7920
7921 CmdArgs.push_back("-o");
7922 CmdArgs.push_back(Output.getFilename());
7923
7924 for (const auto &II : Inputs)
7925 CmdArgs.push_back(II.getFilename());
7926
7927 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7928 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7929
7930 // Handle the debug info splitting at object creation time if we're
7931 // creating an object.
7932 // TODO: Currently only works on linux with newer objcopy.
7933 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7934 getToolChain().getTriple().isOSLinux())
7935 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7936 SplitDebugName(Args, Inputs[0]));
7937 }
7938
AddLibgcc(const llvm::Triple & Triple,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)7939 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7940 ArgStringList &CmdArgs, const ArgList &Args) {
7941 bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7942 bool isCygMing = Triple.isOSCygMing();
7943 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7944 Args.hasArg(options::OPT_static);
7945 if (!D.CCCIsCXX())
7946 CmdArgs.push_back("-lgcc");
7947
7948 if (StaticLibgcc || isAndroid) {
7949 if (D.CCCIsCXX())
7950 CmdArgs.push_back("-lgcc");
7951 } else {
7952 if (!D.CCCIsCXX() && !isCygMing)
7953 CmdArgs.push_back("--as-needed");
7954 CmdArgs.push_back("-lgcc_s");
7955 if (!D.CCCIsCXX() && !isCygMing)
7956 CmdArgs.push_back("--no-as-needed");
7957 }
7958
7959 if (StaticLibgcc && !isAndroid)
7960 CmdArgs.push_back("-lgcc_eh");
7961 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7962 CmdArgs.push_back("-lgcc");
7963
7964 // According to Android ABI, we have to link with libdl if we are
7965 // linking with non-static libgcc.
7966 //
7967 // NOTE: This fixes a link error on Android MIPS as well. The non-static
7968 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7969 if (isAndroid && !StaticLibgcc)
7970 CmdArgs.push_back("-ldl");
7971 }
7972
getLinuxDynamicLinker(const ArgList & Args,const toolchains::Linux & ToolChain)7973 static std::string getLinuxDynamicLinker(const ArgList &Args,
7974 const toolchains::Linux &ToolChain) {
7975 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7976
7977 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7978 if (ToolChain.getTriple().isArch64Bit())
7979 return "/system/bin/linker64";
7980 else
7981 return "/system/bin/linker";
7982 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
7983 Arch == llvm::Triple::sparcel)
7984 return "/lib/ld-linux.so.2";
7985 else if (Arch == llvm::Triple::aarch64)
7986 return "/lib/ld-linux-aarch64.so.1";
7987 else if (Arch == llvm::Triple::aarch64_be)
7988 return "/lib/ld-linux-aarch64_be.so.1";
7989 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
7990 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
7991 tools::arm::getARMFloatABI(ToolChain.getDriver(), Args, ToolChain.getTriple()) == "hard")
7992 return "/lib/ld-linux-armhf.so.3";
7993 else
7994 return "/lib/ld-linux.so.3";
7995 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
7996 // TODO: check which dynamic linker name.
7997 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
7998 tools::arm::getARMFloatABI(ToolChain.getDriver(), Args, ToolChain.getTriple()) == "hard")
7999 return "/lib/ld-linux-armhf.so.3";
8000 else
8001 return "/lib/ld-linux.so.3";
8002 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8003 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8004 StringRef CPUName;
8005 StringRef ABIName;
8006 mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
8007 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8008
8009 StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
8010 .Case("o32", "/lib")
8011 .Case("n32", "/lib32")
8012 .Case("n64", "/lib64")
8013 .Default("/lib");
8014 StringRef LibName;
8015 if (mips::isUCLibc(Args))
8016 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8017 else
8018 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8019
8020 return (LibDir + "/" + LibName).str();
8021 } else if (Arch == llvm::Triple::ppc)
8022 return "/lib/ld.so.1";
8023 else if (Arch == llvm::Triple::ppc64) {
8024 if (ppc::hasPPCAbiArg(Args, "elfv2"))
8025 return "/lib64/ld64.so.2";
8026 return "/lib64/ld64.so.1";
8027 } else if (Arch == llvm::Triple::ppc64le) {
8028 if (ppc::hasPPCAbiArg(Args, "elfv1"))
8029 return "/lib64/ld64.so.1";
8030 return "/lib64/ld64.so.2";
8031 } else if (Arch == llvm::Triple::systemz)
8032 return "/lib64/ld64.so.1";
8033 else if (Arch == llvm::Triple::sparcv9)
8034 return "/lib64/ld-linux.so.2";
8035 else if (Arch == llvm::Triple::x86_64 &&
8036 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8037 return "/libx32/ld-linux-x32.so.2";
8038 else
8039 return "/lib64/ld-linux-x86-64.so.2";
8040 }
8041
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)8042 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8043 ArgStringList &CmdArgs, const ArgList &Args) {
8044 // Make use of compiler-rt if --rtlib option is used
8045 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8046
8047 switch (RLT) {
8048 case ToolChain::RLT_CompilerRT:
8049 switch (TC.getTriple().getOS()) {
8050 default:
8051 llvm_unreachable("unsupported OS");
8052 case llvm::Triple::Win32:
8053 case llvm::Triple::Linux:
8054 addClangRT(TC, Args, CmdArgs);
8055 break;
8056 }
8057 break;
8058 case ToolChain::RLT_Libgcc:
8059 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8060 break;
8061 }
8062 }
8063
getLDMOption(const llvm::Triple & T,const ArgList & Args)8064 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8065 switch (T.getArch()) {
8066 case llvm::Triple::x86:
8067 return "elf_i386";
8068 case llvm::Triple::aarch64:
8069 return "aarch64linux";
8070 case llvm::Triple::aarch64_be:
8071 return "aarch64_be_linux";
8072 case llvm::Triple::arm:
8073 case llvm::Triple::thumb:
8074 return "armelf_linux_eabi";
8075 case llvm::Triple::armeb:
8076 case llvm::Triple::thumbeb:
8077 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
8078 case llvm::Triple::ppc:
8079 return "elf32ppclinux";
8080 case llvm::Triple::ppc64:
8081 return "elf64ppc";
8082 case llvm::Triple::ppc64le:
8083 return "elf64lppc";
8084 case llvm::Triple::sparc:
8085 case llvm::Triple::sparcel:
8086 return "elf32_sparc";
8087 case llvm::Triple::sparcv9:
8088 return "elf64_sparc";
8089 case llvm::Triple::mips:
8090 return "elf32btsmip";
8091 case llvm::Triple::mipsel:
8092 return "elf32ltsmip";
8093 case llvm::Triple::mips64:
8094 if (mips::hasMipsAbiArg(Args, "n32"))
8095 return "elf32btsmipn32";
8096 return "elf64btsmip";
8097 case llvm::Triple::mips64el:
8098 if (mips::hasMipsAbiArg(Args, "n32"))
8099 return "elf32ltsmipn32";
8100 return "elf64ltsmip";
8101 case llvm::Triple::systemz:
8102 return "elf64_s390";
8103 case llvm::Triple::x86_64:
8104 if (T.getEnvironment() == llvm::Triple::GNUX32)
8105 return "elf32_x86_64";
8106 return "elf_x86_64";
8107 default:
8108 llvm_unreachable("Unexpected arch");
8109 }
8110 }
8111
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8112 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8113 const InputInfo &Output,
8114 const InputInfoList &Inputs,
8115 const ArgList &Args,
8116 const char *LinkingOutput) const {
8117 const toolchains::Linux &ToolChain =
8118 static_cast<const toolchains::Linux &>(getToolChain());
8119 const Driver &D = ToolChain.getDriver();
8120 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8121 const bool isAndroid =
8122 ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
8123 const bool IsPIE =
8124 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8125 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8126
8127 ArgStringList CmdArgs;
8128
8129 // Silence warning for "clang -g foo.o -o foo"
8130 Args.ClaimAllArgs(options::OPT_g_Group);
8131 // and "clang -emit-llvm foo.o -o foo"
8132 Args.ClaimAllArgs(options::OPT_emit_llvm);
8133 // and for "clang -w foo.o -o foo". Other warning options are already
8134 // handled somewhere else.
8135 Args.ClaimAllArgs(options::OPT_w);
8136
8137 if (!D.SysRoot.empty())
8138 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8139
8140 if (IsPIE)
8141 CmdArgs.push_back("-pie");
8142
8143 if (Args.hasArg(options::OPT_rdynamic))
8144 CmdArgs.push_back("-export-dynamic");
8145
8146 if (Args.hasArg(options::OPT_s))
8147 CmdArgs.push_back("-s");
8148
8149 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8150 arm::appendEBLinkFlags(
8151 Args, CmdArgs,
8152 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8153
8154 for (const auto &Opt : ToolChain.ExtraOpts)
8155 CmdArgs.push_back(Opt.c_str());
8156
8157 if (!Args.hasArg(options::OPT_static)) {
8158 CmdArgs.push_back("--eh-frame-hdr");
8159 }
8160
8161 CmdArgs.push_back("-m");
8162 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8163
8164 if (Args.hasArg(options::OPT_static)) {
8165 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8166 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8167 CmdArgs.push_back("-Bstatic");
8168 else
8169 CmdArgs.push_back("-static");
8170 } else if (Args.hasArg(options::OPT_shared)) {
8171 CmdArgs.push_back("-shared");
8172 }
8173
8174 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8175 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8176 (!Args.hasArg(options::OPT_static) &&
8177 !Args.hasArg(options::OPT_shared))) {
8178 CmdArgs.push_back("-dynamic-linker");
8179 CmdArgs.push_back(Args.MakeArgString(
8180 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8181 }
8182
8183 CmdArgs.push_back("-o");
8184 CmdArgs.push_back(Output.getFilename());
8185
8186 if (!Args.hasArg(options::OPT_nostdlib) &&
8187 !Args.hasArg(options::OPT_nostartfiles)) {
8188 if (!isAndroid) {
8189 const char *crt1 = nullptr;
8190 if (!Args.hasArg(options::OPT_shared)) {
8191 if (Args.hasArg(options::OPT_pg))
8192 crt1 = "gcrt1.o";
8193 else if (IsPIE)
8194 crt1 = "Scrt1.o";
8195 else
8196 crt1 = "crt1.o";
8197 }
8198 if (crt1)
8199 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8200
8201 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8202 }
8203
8204 const char *crtbegin;
8205 if (Args.hasArg(options::OPT_static))
8206 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8207 else if (Args.hasArg(options::OPT_shared))
8208 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8209 else if (IsPIE)
8210 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8211 else
8212 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8213 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8214
8215 // Add crtfastmath.o if available and fast math is enabled.
8216 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8217 }
8218
8219 Args.AddAllArgs(CmdArgs, options::OPT_L);
8220 Args.AddAllArgs(CmdArgs, options::OPT_u);
8221
8222 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8223
8224 for (const auto &Path : Paths)
8225 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8226
8227 if (D.IsUsingLTO(Args))
8228 AddGoldPlugin(ToolChain, Args, CmdArgs);
8229
8230 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8231 CmdArgs.push_back("--no-demangle");
8232
8233 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8234 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8235 // The profile runtime also needs access to system libraries.
8236 addProfileRT(getToolChain(), Args, CmdArgs);
8237
8238 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8239 !Args.hasArg(options::OPT_nodefaultlibs)) {
8240 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8241 !Args.hasArg(options::OPT_static);
8242 if (OnlyLibstdcxxStatic)
8243 CmdArgs.push_back("-Bstatic");
8244 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8245 if (OnlyLibstdcxxStatic)
8246 CmdArgs.push_back("-Bdynamic");
8247 CmdArgs.push_back("-lm");
8248 }
8249 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8250 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8251
8252 if (!Args.hasArg(options::OPT_nostdlib)) {
8253 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8254 if (Args.hasArg(options::OPT_static))
8255 CmdArgs.push_back("--start-group");
8256
8257 if (NeedsSanitizerDeps)
8258 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8259
8260 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8261 Args.hasArg(options::OPT_pthreads);
8262
8263 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8264 options::OPT_fno_openmp, false)) {
8265 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8266 // FIXME: Does this really make sense for all GNU toolchains?
8267 WantPthread = true;
8268
8269 // Also link the particular OpenMP runtimes.
8270 switch (getOpenMPRuntime(ToolChain, Args)) {
8271 case OMPRT_OMP:
8272 CmdArgs.push_back("-lomp");
8273 break;
8274 case OMPRT_GOMP:
8275 CmdArgs.push_back("-lgomp");
8276
8277 // FIXME: Exclude this for platforms with libgomp that don't require
8278 // librt. Most modern Linux platforms require it, but some may not.
8279 CmdArgs.push_back("-lrt");
8280 break;
8281 case OMPRT_IOMP5:
8282 CmdArgs.push_back("-liomp5");
8283 break;
8284 case OMPRT_Unknown:
8285 // Already diagnosed.
8286 break;
8287 }
8288 }
8289
8290 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8291
8292 if (WantPthread && !isAndroid)
8293 CmdArgs.push_back("-lpthread");
8294
8295 CmdArgs.push_back("-lc");
8296
8297 if (Args.hasArg(options::OPT_static))
8298 CmdArgs.push_back("--end-group");
8299 else
8300 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8301 }
8302
8303 if (!Args.hasArg(options::OPT_nostartfiles)) {
8304 const char *crtend;
8305 if (Args.hasArg(options::OPT_shared))
8306 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8307 else if (IsPIE)
8308 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8309 else
8310 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8311
8312 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8313 if (!isAndroid)
8314 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8315 }
8316 }
8317
8318 C.addCommand(
8319 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8320 }
8321
8322 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8323 // for the various SFI requirements like register masking. The assembly tool
8324 // inserts the file containing the macros as an input into all the assembly
8325 // jobs.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8326 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8327 const InputInfo &Output,
8328 const InputInfoList &Inputs,
8329 const ArgList &Args,
8330 const char *LinkingOutput) const {
8331 const toolchains::NaCl_TC &ToolChain =
8332 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8333 InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8334 "nacl-arm-macros.s");
8335 InputInfoList NewInputs;
8336 NewInputs.push_back(NaClMacros);
8337 NewInputs.append(Inputs.begin(), Inputs.end());
8338 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8339 LinkingOutput);
8340 }
8341
8342 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8343 // we use static by default, do not yet support sanitizers or LTO, and a few
8344 // others. Eventually we can support more of that and hopefully migrate back
8345 // to gnutools::Linker.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8346 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8347 const InputInfo &Output,
8348 const InputInfoList &Inputs,
8349 const ArgList &Args,
8350 const char *LinkingOutput) const {
8351
8352 const toolchains::NaCl_TC &ToolChain =
8353 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8354 const Driver &D = ToolChain.getDriver();
8355 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8356 const bool IsStatic =
8357 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8358
8359 ArgStringList CmdArgs;
8360
8361 // Silence warning for "clang -g foo.o -o foo"
8362 Args.ClaimAllArgs(options::OPT_g_Group);
8363 // and "clang -emit-llvm foo.o -o foo"
8364 Args.ClaimAllArgs(options::OPT_emit_llvm);
8365 // and for "clang -w foo.o -o foo". Other warning options are already
8366 // handled somewhere else.
8367 Args.ClaimAllArgs(options::OPT_w);
8368
8369 if (!D.SysRoot.empty())
8370 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8371
8372 if (Args.hasArg(options::OPT_rdynamic))
8373 CmdArgs.push_back("-export-dynamic");
8374
8375 if (Args.hasArg(options::OPT_s))
8376 CmdArgs.push_back("-s");
8377
8378 // NaCl_TC doesn't have ExtraOpts like Linux; the only relevant flag from
8379 // there is --build-id, which we do want.
8380 CmdArgs.push_back("--build-id");
8381
8382 if (!IsStatic)
8383 CmdArgs.push_back("--eh-frame-hdr");
8384
8385 CmdArgs.push_back("-m");
8386 if (Arch == llvm::Triple::x86)
8387 CmdArgs.push_back("elf_i386_nacl");
8388 else if (Arch == llvm::Triple::arm)
8389 CmdArgs.push_back("armelf_nacl");
8390 else if (Arch == llvm::Triple::x86_64)
8391 CmdArgs.push_back("elf_x86_64_nacl");
8392 else if (Arch == llvm::Triple::mipsel)
8393 CmdArgs.push_back("mipselelf_nacl");
8394 else
8395 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8396 << "Native Client";
8397
8398 if (IsStatic)
8399 CmdArgs.push_back("-static");
8400 else if (Args.hasArg(options::OPT_shared))
8401 CmdArgs.push_back("-shared");
8402
8403 CmdArgs.push_back("-o");
8404 CmdArgs.push_back(Output.getFilename());
8405 if (!Args.hasArg(options::OPT_nostdlib) &&
8406 !Args.hasArg(options::OPT_nostartfiles)) {
8407 if (!Args.hasArg(options::OPT_shared))
8408 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
8409 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8410
8411 const char *crtbegin;
8412 if (IsStatic)
8413 crtbegin = "crtbeginT.o";
8414 else if (Args.hasArg(options::OPT_shared))
8415 crtbegin = "crtbeginS.o";
8416 else
8417 crtbegin = "crtbegin.o";
8418 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8419 }
8420
8421 Args.AddAllArgs(CmdArgs, options::OPT_L);
8422 Args.AddAllArgs(CmdArgs, options::OPT_u);
8423
8424 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8425
8426 for (const auto &Path : Paths)
8427 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8428
8429 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8430 CmdArgs.push_back("--no-demangle");
8431
8432 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8433
8434 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8435 !Args.hasArg(options::OPT_nodefaultlibs)) {
8436 bool OnlyLibstdcxxStatic =
8437 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
8438 if (OnlyLibstdcxxStatic)
8439 CmdArgs.push_back("-Bstatic");
8440 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8441 if (OnlyLibstdcxxStatic)
8442 CmdArgs.push_back("-Bdynamic");
8443 CmdArgs.push_back("-lm");
8444 }
8445
8446 if (!Args.hasArg(options::OPT_nostdlib)) {
8447 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8448 // Always use groups, since it has no effect on dynamic libraries.
8449 CmdArgs.push_back("--start-group");
8450 CmdArgs.push_back("-lc");
8451 // NaCl's libc++ currently requires libpthread, so just always include it
8452 // in the group for C++.
8453 if (Args.hasArg(options::OPT_pthread) ||
8454 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
8455 // Gold, used by Mips, handles nested groups differently than ld, and
8456 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
8457 // which is not a desired behaviour here.
8458 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
8459 if (getToolChain().getArch() == llvm::Triple::mipsel)
8460 CmdArgs.push_back("-lnacl");
8461
8462 CmdArgs.push_back("-lpthread");
8463 }
8464
8465 CmdArgs.push_back("-lgcc");
8466 CmdArgs.push_back("--as-needed");
8467 if (IsStatic)
8468 CmdArgs.push_back("-lgcc_eh");
8469 else
8470 CmdArgs.push_back("-lgcc_s");
8471 CmdArgs.push_back("--no-as-needed");
8472
8473 // Mips needs to create and use pnacl_legacy library that contains
8474 // definitions from bitcode/pnaclmm.c and definitions for
8475 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
8476 if (getToolChain().getArch() == llvm::Triple::mipsel)
8477 CmdArgs.push_back("-lpnacl_legacy");
8478
8479 CmdArgs.push_back("--end-group");
8480 }
8481
8482 if (!Args.hasArg(options::OPT_nostartfiles)) {
8483 const char *crtend;
8484 if (Args.hasArg(options::OPT_shared))
8485 crtend = "crtendS.o";
8486 else
8487 crtend = "crtend.o";
8488
8489 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8490 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8491 }
8492 }
8493
8494 C.addCommand(
8495 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8496 }
8497
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8498 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8499 const InputInfo &Output,
8500 const InputInfoList &Inputs,
8501 const ArgList &Args,
8502 const char *LinkingOutput) const {
8503 claimNoWarnArgs(Args);
8504 ArgStringList CmdArgs;
8505
8506 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8507
8508 CmdArgs.push_back("-o");
8509 CmdArgs.push_back(Output.getFilename());
8510
8511 for (const auto &II : Inputs)
8512 CmdArgs.push_back(II.getFilename());
8513
8514 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8515 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8516 }
8517
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8518 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8519 const InputInfo &Output,
8520 const InputInfoList &Inputs,
8521 const ArgList &Args,
8522 const char *LinkingOutput) const {
8523 const Driver &D = getToolChain().getDriver();
8524 ArgStringList CmdArgs;
8525
8526 if (Output.isFilename()) {
8527 CmdArgs.push_back("-o");
8528 CmdArgs.push_back(Output.getFilename());
8529 } else {
8530 assert(Output.isNothing() && "Invalid output.");
8531 }
8532
8533 if (!Args.hasArg(options::OPT_nostdlib) &&
8534 !Args.hasArg(options::OPT_nostartfiles)) {
8535 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8536 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8537 CmdArgs.push_back(
8538 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8539 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8540 }
8541
8542 Args.AddAllArgs(CmdArgs, options::OPT_L);
8543 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8544 Args.AddAllArgs(CmdArgs, options::OPT_e);
8545
8546 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8547
8548 addProfileRT(getToolChain(), Args, CmdArgs);
8549
8550 if (!Args.hasArg(options::OPT_nostdlib) &&
8551 !Args.hasArg(options::OPT_nodefaultlibs)) {
8552 if (D.CCCIsCXX()) {
8553 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8554 CmdArgs.push_back("-lm");
8555 }
8556 }
8557
8558 if (!Args.hasArg(options::OPT_nostdlib) &&
8559 !Args.hasArg(options::OPT_nostartfiles)) {
8560 if (Args.hasArg(options::OPT_pthread))
8561 CmdArgs.push_back("-lpthread");
8562 CmdArgs.push_back("-lc");
8563 CmdArgs.push_back("-lCompilerRT-Generic");
8564 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
8565 CmdArgs.push_back(
8566 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8567 }
8568
8569 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8570 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8571 }
8572
8573 /// DragonFly Tools
8574
8575 // For now, DragonFly Assemble does just about the same as for
8576 // FreeBSD, but this may change soon.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8577 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8578 const InputInfo &Output,
8579 const InputInfoList &Inputs,
8580 const ArgList &Args,
8581 const char *LinkingOutput) const {
8582 claimNoWarnArgs(Args);
8583 ArgStringList CmdArgs;
8584
8585 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8586 // instruct as in the base system to assemble 32-bit code.
8587 if (getToolChain().getArch() == llvm::Triple::x86)
8588 CmdArgs.push_back("--32");
8589
8590 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8591
8592 CmdArgs.push_back("-o");
8593 CmdArgs.push_back(Output.getFilename());
8594
8595 for (const auto &II : Inputs)
8596 CmdArgs.push_back(II.getFilename());
8597
8598 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8599 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8600 }
8601
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8602 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8603 const InputInfo &Output,
8604 const InputInfoList &Inputs,
8605 const ArgList &Args,
8606 const char *LinkingOutput) const {
8607 const Driver &D = getToolChain().getDriver();
8608 ArgStringList CmdArgs;
8609 bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
8610
8611 if (!D.SysRoot.empty())
8612 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8613
8614 CmdArgs.push_back("--eh-frame-hdr");
8615 if (Args.hasArg(options::OPT_static)) {
8616 CmdArgs.push_back("-Bstatic");
8617 } else {
8618 if (Args.hasArg(options::OPT_rdynamic))
8619 CmdArgs.push_back("-export-dynamic");
8620 if (Args.hasArg(options::OPT_shared))
8621 CmdArgs.push_back("-Bshareable");
8622 else {
8623 CmdArgs.push_back("-dynamic-linker");
8624 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
8625 }
8626 CmdArgs.push_back("--hash-style=both");
8627 }
8628
8629 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8630 // instruct ld in the base system to link 32-bit code.
8631 if (getToolChain().getArch() == llvm::Triple::x86) {
8632 CmdArgs.push_back("-m");
8633 CmdArgs.push_back("elf_i386");
8634 }
8635
8636 if (Output.isFilename()) {
8637 CmdArgs.push_back("-o");
8638 CmdArgs.push_back(Output.getFilename());
8639 } else {
8640 assert(Output.isNothing() && "Invalid output.");
8641 }
8642
8643 if (!Args.hasArg(options::OPT_nostdlib) &&
8644 !Args.hasArg(options::OPT_nostartfiles)) {
8645 if (!Args.hasArg(options::OPT_shared)) {
8646 if (Args.hasArg(options::OPT_pg))
8647 CmdArgs.push_back(
8648 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
8649 else {
8650 if (Args.hasArg(options::OPT_pie))
8651 CmdArgs.push_back(
8652 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
8653 else
8654 CmdArgs.push_back(
8655 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8656 }
8657 }
8658 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8659 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8660 CmdArgs.push_back(
8661 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8662 else
8663 CmdArgs.push_back(
8664 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8665 }
8666
8667 Args.AddAllArgs(CmdArgs, options::OPT_L);
8668 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8669 Args.AddAllArgs(CmdArgs, options::OPT_e);
8670
8671 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8672
8673 if (!Args.hasArg(options::OPT_nostdlib) &&
8674 !Args.hasArg(options::OPT_nodefaultlibs)) {
8675 // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
8676 // rpaths
8677 if (UseGCC47)
8678 CmdArgs.push_back("-L/usr/lib/gcc47");
8679 else
8680 CmdArgs.push_back("-L/usr/lib/gcc44");
8681
8682 if (!Args.hasArg(options::OPT_static)) {
8683 if (UseGCC47) {
8684 CmdArgs.push_back("-rpath");
8685 CmdArgs.push_back("/usr/lib/gcc47");
8686 } else {
8687 CmdArgs.push_back("-rpath");
8688 CmdArgs.push_back("/usr/lib/gcc44");
8689 }
8690 }
8691
8692 if (D.CCCIsCXX()) {
8693 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8694 CmdArgs.push_back("-lm");
8695 }
8696
8697 if (Args.hasArg(options::OPT_pthread))
8698 CmdArgs.push_back("-lpthread");
8699
8700 if (!Args.hasArg(options::OPT_nolibc)) {
8701 CmdArgs.push_back("-lc");
8702 }
8703
8704 if (UseGCC47) {
8705 if (Args.hasArg(options::OPT_static) ||
8706 Args.hasArg(options::OPT_static_libgcc)) {
8707 CmdArgs.push_back("-lgcc");
8708 CmdArgs.push_back("-lgcc_eh");
8709 } else {
8710 if (Args.hasArg(options::OPT_shared_libgcc)) {
8711 CmdArgs.push_back("-lgcc_pic");
8712 if (!Args.hasArg(options::OPT_shared))
8713 CmdArgs.push_back("-lgcc");
8714 } else {
8715 CmdArgs.push_back("-lgcc");
8716 CmdArgs.push_back("--as-needed");
8717 CmdArgs.push_back("-lgcc_pic");
8718 CmdArgs.push_back("--no-as-needed");
8719 }
8720 }
8721 } else {
8722 if (Args.hasArg(options::OPT_shared)) {
8723 CmdArgs.push_back("-lgcc_pic");
8724 } else {
8725 CmdArgs.push_back("-lgcc");
8726 }
8727 }
8728 }
8729
8730 if (!Args.hasArg(options::OPT_nostdlib) &&
8731 !Args.hasArg(options::OPT_nostartfiles)) {
8732 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8733 CmdArgs.push_back(
8734 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8735 else
8736 CmdArgs.push_back(
8737 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8738 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8739 }
8740
8741 addProfileRT(getToolChain(), Args, CmdArgs);
8742
8743 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8744 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8745 }
8746
8747 // Try to find Exe from a Visual Studio distribution. This first tries to find
8748 // an installed copy of Visual Studio and, failing that, looks in the PATH,
8749 // making sure that whatever executable that's found is not a same-named exe
8750 // from clang itself to prevent clang from falling back to itself.
FindVisualStudioExecutable(const ToolChain & TC,const char * Exe,const char * ClangProgramPath)8751 static std::string FindVisualStudioExecutable(const ToolChain &TC,
8752 const char *Exe,
8753 const char *ClangProgramPath) {
8754 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8755 std::string visualStudioBinDir;
8756 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
8757 visualStudioBinDir)) {
8758 SmallString<128> FilePath(visualStudioBinDir);
8759 llvm::sys::path::append(FilePath, Exe);
8760 if (llvm::sys::fs::can_execute(FilePath.c_str()))
8761 return FilePath.str();
8762 }
8763
8764 return Exe;
8765 }
8766
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8767 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8768 const InputInfo &Output,
8769 const InputInfoList &Inputs,
8770 const ArgList &Args,
8771 const char *LinkingOutput) const {
8772 ArgStringList CmdArgs;
8773 const ToolChain &TC = getToolChain();
8774
8775 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
8776 if (Output.isFilename())
8777 CmdArgs.push_back(
8778 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
8779
8780 if (!Args.hasArg(options::OPT_nostdlib) &&
8781 !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
8782 CmdArgs.push_back("-defaultlib:libcmt");
8783
8784 if (!llvm::sys::Process::GetEnv("LIB")) {
8785 // If the VC environment hasn't been configured (perhaps because the user
8786 // did not run vcvarsall), try to build a consistent link environment. If
8787 // the environment variable is set however, assume the user knows what
8788 // they're doing.
8789 std::string VisualStudioDir;
8790 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8791 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
8792 SmallString<128> LibDir(VisualStudioDir);
8793 llvm::sys::path::append(LibDir, "VC", "lib");
8794 switch (MSVC.getArch()) {
8795 case llvm::Triple::x86:
8796 // x86 just puts the libraries directly in lib
8797 break;
8798 case llvm::Triple::x86_64:
8799 llvm::sys::path::append(LibDir, "amd64");
8800 break;
8801 case llvm::Triple::arm:
8802 llvm::sys::path::append(LibDir, "arm");
8803 break;
8804 default:
8805 break;
8806 }
8807 CmdArgs.push_back(
8808 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
8809 }
8810
8811 std::string WindowsSdkLibPath;
8812 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
8813 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
8814 WindowsSdkLibPath.c_str()));
8815 }
8816
8817 CmdArgs.push_back("-nologo");
8818
8819 if (Args.hasArg(options::OPT_g_Group))
8820 CmdArgs.push_back("-debug");
8821
8822 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
8823 options::OPT_shared);
8824 if (DLL) {
8825 CmdArgs.push_back(Args.MakeArgString("-dll"));
8826
8827 SmallString<128> ImplibName(Output.getFilename());
8828 llvm::sys::path::replace_extension(ImplibName, "lib");
8829 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
8830 }
8831
8832 if (TC.getSanitizerArgs().needsAsanRt()) {
8833 CmdArgs.push_back(Args.MakeArgString("-debug"));
8834 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
8835 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
8836 static const char *CompilerRTComponents[] = {
8837 "asan_dynamic", "asan_dynamic_runtime_thunk",
8838 };
8839 for (const auto &Component : CompilerRTComponents)
8840 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8841 // Make sure the dynamic runtime thunk is not optimized out at link time
8842 // to ensure proper SEH handling.
8843 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
8844 } else if (DLL) {
8845 CmdArgs.push_back(
8846 Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
8847 } else {
8848 static const char *CompilerRTComponents[] = {
8849 "asan", "asan_cxx",
8850 };
8851 for (const auto &Component : CompilerRTComponents)
8852 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8853 }
8854 }
8855
8856 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
8857
8858 // Add filenames, libraries, and other linker inputs.
8859 for (const auto &Input : Inputs) {
8860 if (Input.isFilename()) {
8861 CmdArgs.push_back(Input.getFilename());
8862 continue;
8863 }
8864
8865 const Arg &A = Input.getInputArg();
8866
8867 // Render -l options differently for the MSVC linker.
8868 if (A.getOption().matches(options::OPT_l)) {
8869 StringRef Lib = A.getValue();
8870 const char *LinkLibArg;
8871 if (Lib.endswith(".lib"))
8872 LinkLibArg = Args.MakeArgString(Lib);
8873 else
8874 LinkLibArg = Args.MakeArgString(Lib + ".lib");
8875 CmdArgs.push_back(LinkLibArg);
8876 continue;
8877 }
8878
8879 // Otherwise, this is some other kind of linker input option like -Wl, -z,
8880 // or -L. Render it, even if MSVC doesn't understand it.
8881 A.renderAsInput(Args, CmdArgs);
8882 }
8883
8884 // We need to special case some linker paths. In the case of lld, we need to
8885 // translate 'lld' into 'lld-link', and in the case of the regular msvc
8886 // linker, we need to use a special search algorithm.
8887 llvm::SmallString<128> linkPath;
8888 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
8889 if (Linker.equals_lower("lld"))
8890 Linker = "lld-link";
8891
8892 if (Linker.equals_lower("link")) {
8893 // If we're using the MSVC linker, it's not sufficient to just use link
8894 // from the program PATH, because other environments like GnuWin32 install
8895 // their own link.exe which may come first.
8896 linkPath = FindVisualStudioExecutable(TC, "link.exe",
8897 C.getDriver().getClangProgramPath());
8898 } else {
8899 linkPath = Linker;
8900 llvm::sys::path::replace_extension(linkPath, "exe");
8901 linkPath = TC.GetProgramPath(linkPath.c_str());
8902 }
8903
8904 const char *Exec = Args.MakeArgString(linkPath);
8905 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8906 }
8907
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8908 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
8909 const InputInfo &Output,
8910 const InputInfoList &Inputs,
8911 const ArgList &Args,
8912 const char *LinkingOutput) const {
8913 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
8914 }
8915
GetCommand(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8916 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
8917 Compilation &C, const JobAction &JA, const InputInfo &Output,
8918 const InputInfoList &Inputs, const ArgList &Args,
8919 const char *LinkingOutput) const {
8920 ArgStringList CmdArgs;
8921 CmdArgs.push_back("/nologo");
8922 CmdArgs.push_back("/c"); // Compile only.
8923 CmdArgs.push_back("/W0"); // No warnings.
8924
8925 // The goal is to be able to invoke this tool correctly based on
8926 // any flag accepted by clang-cl.
8927
8928 // These are spelled the same way in clang and cl.exe,.
8929 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
8930 Args.AddAllArgs(CmdArgs, options::OPT_I);
8931
8932 // Optimization level.
8933 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
8934 if (A->getOption().getID() == options::OPT_O0) {
8935 CmdArgs.push_back("/Od");
8936 } else {
8937 StringRef OptLevel = A->getValue();
8938 if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
8939 A->render(Args, CmdArgs);
8940 else if (OptLevel == "3")
8941 CmdArgs.push_back("/Ox");
8942 }
8943 }
8944
8945 // Flags for which clang-cl has an alias.
8946 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
8947
8948 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8949 /*default=*/false))
8950 CmdArgs.push_back("/GR-");
8951 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
8952 options::OPT_fno_function_sections))
8953 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
8954 ? "/Gy"
8955 : "/Gy-");
8956 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
8957 options::OPT_fno_data_sections))
8958 CmdArgs.push_back(
8959 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
8960 if (Args.hasArg(options::OPT_fsyntax_only))
8961 CmdArgs.push_back("/Zs");
8962 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
8963 CmdArgs.push_back("/Z7");
8964
8965 std::vector<std::string> Includes =
8966 Args.getAllArgValues(options::OPT_include);
8967 for (const auto &Include : Includes)
8968 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
8969
8970 // Flags that can simply be passed through.
8971 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
8972 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
8973 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
8974
8975 // The order of these flags is relevant, so pick the last one.
8976 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
8977 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
8978 A->render(Args, CmdArgs);
8979
8980 // Input filename.
8981 assert(Inputs.size() == 1);
8982 const InputInfo &II = Inputs[0];
8983 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
8984 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
8985 if (II.isFilename())
8986 CmdArgs.push_back(II.getFilename());
8987 else
8988 II.getInputArg().renderAsInput(Args, CmdArgs);
8989
8990 // Output filename.
8991 assert(Output.getType() == types::TY_Object);
8992 const char *Fo =
8993 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
8994 CmdArgs.push_back(Fo);
8995
8996 const Driver &D = getToolChain().getDriver();
8997 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
8998 D.getClangProgramPath());
8999 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9000 CmdArgs);
9001 }
9002
9003 /// MinGW Tools
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9004 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9005 const InputInfo &Output,
9006 const InputInfoList &Inputs,
9007 const ArgList &Args,
9008 const char *LinkingOutput) const {
9009 claimNoWarnArgs(Args);
9010 ArgStringList CmdArgs;
9011
9012 if (getToolChain().getArch() == llvm::Triple::x86) {
9013 CmdArgs.push_back("--32");
9014 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9015 CmdArgs.push_back("--64");
9016 }
9017
9018 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9019
9020 CmdArgs.push_back("-o");
9021 CmdArgs.push_back(Output.getFilename());
9022
9023 for (const auto &II : Inputs)
9024 CmdArgs.push_back(II.getFilename());
9025
9026 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9027 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9028
9029 if (Args.hasArg(options::OPT_gsplit_dwarf))
9030 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9031 SplitDebugName(Args, Inputs[0]));
9032 }
9033
AddLibGCC(const ArgList & Args,ArgStringList & CmdArgs) const9034 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9035 ArgStringList &CmdArgs) const {
9036 if (Args.hasArg(options::OPT_mthreads))
9037 CmdArgs.push_back("-lmingwthrd");
9038 CmdArgs.push_back("-lmingw32");
9039
9040 // Add libgcc or compiler-rt.
9041 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9042
9043 CmdArgs.push_back("-lmoldname");
9044 CmdArgs.push_back("-lmingwex");
9045 CmdArgs.push_back("-lmsvcrt");
9046 }
9047
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9048 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9049 const InputInfo &Output,
9050 const InputInfoList &Inputs,
9051 const ArgList &Args,
9052 const char *LinkingOutput) const {
9053 const ToolChain &TC = getToolChain();
9054 const Driver &D = TC.getDriver();
9055 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9056
9057 ArgStringList CmdArgs;
9058
9059 // Silence warning for "clang -g foo.o -o foo"
9060 Args.ClaimAllArgs(options::OPT_g_Group);
9061 // and "clang -emit-llvm foo.o -o foo"
9062 Args.ClaimAllArgs(options::OPT_emit_llvm);
9063 // and for "clang -w foo.o -o foo". Other warning options are already
9064 // handled somewhere else.
9065 Args.ClaimAllArgs(options::OPT_w);
9066
9067 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9068 if (LinkerName.equals_lower("lld")) {
9069 CmdArgs.push_back("-flavor");
9070 CmdArgs.push_back("gnu");
9071 }
9072
9073 if (!D.SysRoot.empty())
9074 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9075
9076 if (Args.hasArg(options::OPT_s))
9077 CmdArgs.push_back("-s");
9078
9079 CmdArgs.push_back("-m");
9080 if (TC.getArch() == llvm::Triple::x86)
9081 CmdArgs.push_back("i386pe");
9082 if (TC.getArch() == llvm::Triple::x86_64)
9083 CmdArgs.push_back("i386pep");
9084 if (TC.getArch() == llvm::Triple::arm)
9085 CmdArgs.push_back("thumb2pe");
9086
9087 if (Args.hasArg(options::OPT_mwindows)) {
9088 CmdArgs.push_back("--subsystem");
9089 CmdArgs.push_back("windows");
9090 } else if (Args.hasArg(options::OPT_mconsole)) {
9091 CmdArgs.push_back("--subsystem");
9092 CmdArgs.push_back("console");
9093 }
9094
9095 if (Args.hasArg(options::OPT_static))
9096 CmdArgs.push_back("-Bstatic");
9097 else {
9098 if (Args.hasArg(options::OPT_mdll))
9099 CmdArgs.push_back("--dll");
9100 else if (Args.hasArg(options::OPT_shared))
9101 CmdArgs.push_back("--shared");
9102 CmdArgs.push_back("-Bdynamic");
9103 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9104 CmdArgs.push_back("-e");
9105 if (TC.getArch() == llvm::Triple::x86)
9106 CmdArgs.push_back("_DllMainCRTStartup@12");
9107 else
9108 CmdArgs.push_back("DllMainCRTStartup");
9109 CmdArgs.push_back("--enable-auto-image-base");
9110 }
9111 }
9112
9113 CmdArgs.push_back("-o");
9114 CmdArgs.push_back(Output.getFilename());
9115
9116 Args.AddAllArgs(CmdArgs, options::OPT_e);
9117 // FIXME: add -N, -n flags
9118 Args.AddLastArg(CmdArgs, options::OPT_r);
9119 Args.AddLastArg(CmdArgs, options::OPT_s);
9120 Args.AddLastArg(CmdArgs, options::OPT_t);
9121 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9122 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9123
9124 if (!Args.hasArg(options::OPT_nostdlib) &&
9125 !Args.hasArg(options::OPT_nostartfiles)) {
9126 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9127 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9128 } else {
9129 if (Args.hasArg(options::OPT_municode))
9130 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9131 else
9132 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9133 }
9134 if (Args.hasArg(options::OPT_pg))
9135 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9136 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9137 }
9138
9139 Args.AddAllArgs(CmdArgs, options::OPT_L);
9140 const ToolChain::path_list Paths = TC.getFilePaths();
9141 for (const auto &Path : Paths)
9142 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9143
9144 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9145
9146 // TODO: Add ASan stuff here
9147
9148 // TODO: Add profile stuff here
9149
9150 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9151 !Args.hasArg(options::OPT_nodefaultlibs)) {
9152 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9153 !Args.hasArg(options::OPT_static);
9154 if (OnlyLibstdcxxStatic)
9155 CmdArgs.push_back("-Bstatic");
9156 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9157 if (OnlyLibstdcxxStatic)
9158 CmdArgs.push_back("-Bdynamic");
9159 }
9160
9161 if (!Args.hasArg(options::OPT_nostdlib)) {
9162 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9163 if (Args.hasArg(options::OPT_static))
9164 CmdArgs.push_back("--start-group");
9165
9166 if (Args.hasArg(options::OPT_fstack_protector) ||
9167 Args.hasArg(options::OPT_fstack_protector_strong) ||
9168 Args.hasArg(options::OPT_fstack_protector_all)) {
9169 CmdArgs.push_back("-lssp_nonshared");
9170 CmdArgs.push_back("-lssp");
9171 }
9172 if (Args.hasArg(options::OPT_fopenmp))
9173 CmdArgs.push_back("-lgomp");
9174
9175 AddLibGCC(Args, CmdArgs);
9176
9177 if (Args.hasArg(options::OPT_pg))
9178 CmdArgs.push_back("-lgmon");
9179
9180 if (Args.hasArg(options::OPT_pthread))
9181 CmdArgs.push_back("-lpthread");
9182
9183 // add system libraries
9184 if (Args.hasArg(options::OPT_mwindows)) {
9185 CmdArgs.push_back("-lgdi32");
9186 CmdArgs.push_back("-lcomdlg32");
9187 }
9188 CmdArgs.push_back("-ladvapi32");
9189 CmdArgs.push_back("-lshell32");
9190 CmdArgs.push_back("-luser32");
9191 CmdArgs.push_back("-lkernel32");
9192
9193 if (Args.hasArg(options::OPT_static))
9194 CmdArgs.push_back("--end-group");
9195 else if (!LinkerName.equals_lower("lld"))
9196 AddLibGCC(Args, CmdArgs);
9197 }
9198
9199 if (!Args.hasArg(options::OPT_nostartfiles)) {
9200 // Add crtfastmath.o if available and fast math is enabled.
9201 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9202
9203 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9204 }
9205 }
9206 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9207 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9208 }
9209
9210 /// XCore Tools
9211 // We pass assemble and link construction to the xcc tool.
9212
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9213 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9214 const InputInfo &Output,
9215 const InputInfoList &Inputs,
9216 const ArgList &Args,
9217 const char *LinkingOutput) const {
9218 claimNoWarnArgs(Args);
9219 ArgStringList CmdArgs;
9220
9221 CmdArgs.push_back("-o");
9222 CmdArgs.push_back(Output.getFilename());
9223
9224 CmdArgs.push_back("-c");
9225
9226 if (Args.hasArg(options::OPT_v))
9227 CmdArgs.push_back("-v");
9228
9229 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9230 if (!A->getOption().matches(options::OPT_g0))
9231 CmdArgs.push_back("-g");
9232
9233 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9234 false))
9235 CmdArgs.push_back("-fverbose-asm");
9236
9237 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9238
9239 for (const auto &II : Inputs)
9240 CmdArgs.push_back(II.getFilename());
9241
9242 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9243 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9244 }
9245
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9246 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9247 const InputInfo &Output,
9248 const InputInfoList &Inputs,
9249 const ArgList &Args,
9250 const char *LinkingOutput) const {
9251 ArgStringList CmdArgs;
9252
9253 if (Output.isFilename()) {
9254 CmdArgs.push_back("-o");
9255 CmdArgs.push_back(Output.getFilename());
9256 } else {
9257 assert(Output.isNothing() && "Invalid output.");
9258 }
9259
9260 if (Args.hasArg(options::OPT_v))
9261 CmdArgs.push_back("-v");
9262
9263 // Pass -fexceptions through to the linker if it was present.
9264 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9265 false))
9266 CmdArgs.push_back("-fexceptions");
9267
9268 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9269
9270 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9271 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9272 }
9273
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9274 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9275 const InputInfo &Output,
9276 const InputInfoList &Inputs,
9277 const ArgList &Args,
9278 const char *LinkingOutput) const {
9279 claimNoWarnArgs(Args);
9280 const auto &TC =
9281 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9282 ArgStringList CmdArgs;
9283 const char *Exec;
9284
9285 switch (TC.getArch()) {
9286 default:
9287 llvm_unreachable("unsupported architecture");
9288 case llvm::Triple::arm:
9289 case llvm::Triple::thumb:
9290 break;
9291 case llvm::Triple::x86:
9292 CmdArgs.push_back("--32");
9293 break;
9294 case llvm::Triple::x86_64:
9295 CmdArgs.push_back("--64");
9296 break;
9297 }
9298
9299 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9300
9301 CmdArgs.push_back("-o");
9302 CmdArgs.push_back(Output.getFilename());
9303
9304 for (const auto &Input : Inputs)
9305 CmdArgs.push_back(Input.getFilename());
9306
9307 const std::string Assembler = TC.GetProgramPath("as");
9308 Exec = Args.MakeArgString(Assembler);
9309
9310 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9311 }
9312
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9313 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9314 const InputInfo &Output,
9315 const InputInfoList &Inputs,
9316 const ArgList &Args,
9317 const char *LinkingOutput) const {
9318 const auto &TC =
9319 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9320 const llvm::Triple &T = TC.getTriple();
9321 const Driver &D = TC.getDriver();
9322 SmallString<128> EntryPoint;
9323 ArgStringList CmdArgs;
9324 const char *Exec;
9325
9326 // Silence warning for "clang -g foo.o -o foo"
9327 Args.ClaimAllArgs(options::OPT_g_Group);
9328 // and "clang -emit-llvm foo.o -o foo"
9329 Args.ClaimAllArgs(options::OPT_emit_llvm);
9330 // and for "clang -w foo.o -o foo"
9331 Args.ClaimAllArgs(options::OPT_w);
9332 // Other warning options are already handled somewhere else.
9333
9334 if (!D.SysRoot.empty())
9335 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9336
9337 if (Args.hasArg(options::OPT_pie))
9338 CmdArgs.push_back("-pie");
9339 if (Args.hasArg(options::OPT_rdynamic))
9340 CmdArgs.push_back("-export-dynamic");
9341 if (Args.hasArg(options::OPT_s))
9342 CmdArgs.push_back("--strip-all");
9343
9344 CmdArgs.push_back("-m");
9345 switch (TC.getArch()) {
9346 default:
9347 llvm_unreachable("unsupported architecture");
9348 case llvm::Triple::arm:
9349 case llvm::Triple::thumb:
9350 // FIXME: this is incorrect for WinCE
9351 CmdArgs.push_back("thumb2pe");
9352 break;
9353 case llvm::Triple::x86:
9354 CmdArgs.push_back("i386pe");
9355 EntryPoint.append("_");
9356 break;
9357 case llvm::Triple::x86_64:
9358 CmdArgs.push_back("i386pep");
9359 break;
9360 }
9361
9362 if (Args.hasArg(options::OPT_shared)) {
9363 switch (T.getArch()) {
9364 default:
9365 llvm_unreachable("unsupported architecture");
9366 case llvm::Triple::arm:
9367 case llvm::Triple::thumb:
9368 case llvm::Triple::x86_64:
9369 EntryPoint.append("_DllMainCRTStartup");
9370 break;
9371 case llvm::Triple::x86:
9372 EntryPoint.append("_DllMainCRTStartup@12");
9373 break;
9374 }
9375
9376 CmdArgs.push_back("-shared");
9377 CmdArgs.push_back("-Bdynamic");
9378
9379 CmdArgs.push_back("--enable-auto-image-base");
9380
9381 CmdArgs.push_back("--entry");
9382 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9383 } else {
9384 EntryPoint.append("mainCRTStartup");
9385
9386 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
9387 : "-Bdynamic");
9388
9389 if (!Args.hasArg(options::OPT_nostdlib) &&
9390 !Args.hasArg(options::OPT_nostartfiles)) {
9391 CmdArgs.push_back("--entry");
9392 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9393 }
9394
9395 // FIXME: handle subsystem
9396 }
9397
9398 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
9399 CmdArgs.push_back("--allow-multiple-definition");
9400
9401 CmdArgs.push_back("-o");
9402 CmdArgs.push_back(Output.getFilename());
9403
9404 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
9405 SmallString<261> ImpLib(Output.getFilename());
9406 llvm::sys::path::replace_extension(ImpLib, ".lib");
9407
9408 CmdArgs.push_back("--out-implib");
9409 CmdArgs.push_back(Args.MakeArgString(ImpLib));
9410 }
9411
9412 if (!Args.hasArg(options::OPT_nostdlib) &&
9413 !Args.hasArg(options::OPT_nostartfiles)) {
9414 const std::string CRTPath(D.SysRoot + "/usr/lib/");
9415 const char *CRTBegin;
9416
9417 CRTBegin =
9418 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
9419 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
9420 }
9421
9422 Args.AddAllArgs(CmdArgs, options::OPT_L);
9423
9424 const auto &Paths = TC.getFilePaths();
9425 for (const auto &Path : Paths)
9426 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9427
9428 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9429
9430 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9431 !Args.hasArg(options::OPT_nodefaultlibs)) {
9432 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
9433 !Args.hasArg(options::OPT_static);
9434 if (StaticCXX)
9435 CmdArgs.push_back("-Bstatic");
9436 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9437 if (StaticCXX)
9438 CmdArgs.push_back("-Bdynamic");
9439 }
9440
9441 if (!Args.hasArg(options::OPT_nostdlib)) {
9442 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9443 // TODO handle /MT[d] /MD[d]
9444 CmdArgs.push_back("-lmsvcrt");
9445 AddRunTimeLibs(TC, D, CmdArgs, Args);
9446 }
9447 }
9448
9449 const std::string Linker = TC.GetProgramPath("ld");
9450 Exec = Args.MakeArgString(Linker);
9451
9452 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9453 }
9454
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9455 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9456 const InputInfo &Output,
9457 const InputInfoList &Inputs,
9458 const ArgList &Args,
9459 const char *LinkingOutput) const {
9460
9461 ArgStringList CmdArgs;
9462
9463 assert(Inputs.size() == 1);
9464 const InputInfo &II = Inputs[0];
9465 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9466 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
9467
9468 // Append all -I, -iquote, -isystem paths.
9469 Args.AddAllArgs(CmdArgs, options::OPT_clang_i_Group);
9470 // These are spelled the same way in clang and moviCompile.
9471 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
9472
9473 CmdArgs.push_back("-DMYRIAD2");
9474 CmdArgs.push_back("-mcpu=myriad2");
9475 CmdArgs.push_back("-S");
9476
9477 // Any -O option passes through without translation. What about -Ofast ?
9478 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
9479 A->render(Args, CmdArgs);
9480
9481 if (Args.hasFlag(options::OPT_ffunction_sections,
9482 options::OPT_fno_function_sections)) {
9483 CmdArgs.push_back("-ffunction-sections");
9484 }
9485 if (Args.hasArg(options::OPT_fno_inline_functions))
9486 CmdArgs.push_back("-fno-inline-functions");
9487
9488 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
9489
9490 CmdArgs.push_back(II.getFilename());
9491 CmdArgs.push_back("-o");
9492 CmdArgs.push_back(Output.getFilename());
9493
9494 std::string Exec =
9495 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
9496 C.addCommand(
9497 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9498 }
9499
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9500 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9501 const InputInfo &Output,
9502 const InputInfoList &Inputs,
9503 const ArgList &Args,
9504 const char *LinkingOutput) const {
9505 ArgStringList CmdArgs;
9506
9507 assert(Inputs.size() == 1);
9508 const InputInfo &II = Inputs[0];
9509 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
9510 assert(Output.getType() == types::TY_Object);
9511
9512 CmdArgs.push_back("-no6thSlotCompression");
9513 CmdArgs.push_back("-cv:myriad2"); // Chip Version ?
9514 CmdArgs.push_back("-noSPrefixing");
9515 CmdArgs.push_back("-a"); // Mystery option.
9516 for (auto Arg : Args.filtered(options::OPT_I)) {
9517 Arg->claim();
9518 CmdArgs.push_back(
9519 Args.MakeArgString(std::string("-i:") + Arg->getValue(0)));
9520 }
9521 CmdArgs.push_back("-elf"); // Output format.
9522 CmdArgs.push_back(II.getFilename());
9523 CmdArgs.push_back(
9524 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
9525
9526 std::string Exec =
9527 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
9528 C.addCommand(
9529 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9530 }
9531