blob: e3dfb09c7399ff226ace45102daaf103765ea98a [file] [log] [blame]
David L. Jonesf561aba2017-03-08 01:02:16 +00001//===--- LLVM.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Clang.h"
11#include "Arch/AArch64.h"
12#include "Arch/ARM.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
Alex Bradbury71f45452018-01-11 13:36:56 +000015#include "Arch/RISCV.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000016#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Arch/X86.h"
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +000019#include "AMDGPU.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000020#include "CommonArgs.h"
21#include "Hexagon.h"
22#include "InputInfo.h"
23#include "PS4CPU.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000028#include "clang/Driver/DriverDiagnostic.h"
29#include "clang/Driver/Options.h"
30#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000031#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000032#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000033#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#include "llvm/Option/ArgList.h"
35#include "llvm/Support/CodeGen.h"
36#include "llvm/Support/Compression.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000040#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000041#include "llvm/Support/YAMLParser.h"
42
43#ifdef LLVM_ON_UNIX
44#include <unistd.h> // For getuid().
45#endif
46
47using namespace clang::driver;
48using namespace clang::driver::tools;
49using namespace clang;
50using namespace llvm::opt;
51
52static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
53 if (Arg *A =
54 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
55 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
56 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
57 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
58 << A->getBaseArg().getAsString(Args)
59 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
60 }
61 }
62}
63
64static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
65 // In gcc, only ARM checks this, but it seems reasonable to check universally.
66 if (Args.hasArg(options::OPT_static))
67 if (const Arg *A =
68 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
69 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
70 << "-static";
71}
72
73// Add backslashes to escape spaces and other backslashes.
74// This is used for the space-separated argument list specified with
75// the -dwarf-debug-flags option.
76static void EscapeSpacesAndBackslashes(const char *Arg,
77 SmallVectorImpl<char> &Res) {
78 for (; *Arg; ++Arg) {
79 switch (*Arg) {
80 default:
81 break;
82 case ' ':
83 case '\\':
84 Res.push_back('\\');
85 break;
86 }
87 Res.push_back(*Arg);
88 }
89}
90
91// Quote target names for inclusion in GNU Make dependency files.
92// Only the characters '$', '#', ' ', '\t' are quoted.
93static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
94 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
95 switch (Target[i]) {
96 case ' ':
97 case '\t':
98 // Escape the preceding backslashes
99 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
100 Res.push_back('\\');
101
102 // Escape the space/tab
103 Res.push_back('\\');
104 break;
105 case '$':
106 Res.push_back('$');
107 break;
108 case '#':
109 Res.push_back('\\');
110 break;
111 default:
112 break;
113 }
114
115 Res.push_back(Target[i]);
116 }
117}
118
119/// Apply \a Work on the current tool chain \a RegularToolChain and any other
120/// offloading tool chain that is associated with the current action \a JA.
121static void
122forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
123 const ToolChain &RegularToolChain,
124 llvm::function_ref<void(const ToolChain &)> Work) {
125 // Apply Work on the current/regular tool chain.
126 Work(RegularToolChain);
127
128 // Apply Work on all the offloading tool chains associated with the current
129 // action.
130 if (JA.isHostOffloading(Action::OFK_Cuda))
131 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
132 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000134 else if (JA.isHostOffloading(Action::OFK_HIP))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
136 else if (JA.isDeviceOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000138
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000139 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
140 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
141 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
142 Work(*II->second);
143 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
144 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
145
David L. Jonesf561aba2017-03-08 01:02:16 +0000146 //
147 // TODO: Add support for other offloading programming models here.
148 //
149}
150
151/// This is a helper function for validating the optional refinement step
152/// parameter in reciprocal argument strings. Return false if there is an error
153/// parsing the refinement step. Otherwise, return true and set the Position
154/// of the refinement step in the input string.
155static bool getRefinementStep(StringRef In, const Driver &D,
156 const Arg &A, size_t &Position) {
157 const char RefinementStepToken = ':';
158 Position = In.find(RefinementStepToken);
159 if (Position != StringRef::npos) {
160 StringRef Option = A.getOption().getName();
161 StringRef RefStep = In.substr(Position + 1);
162 // Allow exactly one numeric character for the additional refinement
163 // step parameter. This is reasonable for all currently-supported
164 // operations and architectures because we would expect that a larger value
165 // of refinement steps would cause the estimate "optimization" to
166 // under-perform the native operation. Also, if the estimate does not
167 // converge quickly, it probably will not ever converge, so further
168 // refinement steps will not produce a better answer.
169 if (RefStep.size() != 1) {
170 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
171 return false;
172 }
173 char RefStepChar = RefStep[0];
174 if (RefStepChar < '0' || RefStepChar > '9') {
175 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
176 return false;
177 }
178 }
179 return true;
180}
181
182/// The -mrecip flag requires processing of many optional parameters.
183static void ParseMRecip(const Driver &D, const ArgList &Args,
184 ArgStringList &OutStrings) {
185 StringRef DisabledPrefixIn = "!";
186 StringRef DisabledPrefixOut = "!";
187 StringRef EnabledPrefixOut = "";
188 StringRef Out = "-mrecip=";
189
190 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
191 if (!A)
192 return;
193
194 unsigned NumOptions = A->getNumValues();
195 if (NumOptions == 0) {
196 // No option is the same as "all".
197 OutStrings.push_back(Args.MakeArgString(Out + "all"));
198 return;
199 }
200
201 // Pass through "all", "none", or "default" with an optional refinement step.
202 if (NumOptions == 1) {
203 StringRef Val = A->getValue(0);
204 size_t RefStepLoc;
205 if (!getRefinementStep(Val, D, *A, RefStepLoc))
206 return;
207 StringRef ValBase = Val.slice(0, RefStepLoc);
208 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
209 OutStrings.push_back(Args.MakeArgString(Out + Val));
210 return;
211 }
212 }
213
214 // Each reciprocal type may be enabled or disabled individually.
215 // Check each input value for validity, concatenate them all back together,
216 // and pass through.
217
218 llvm::StringMap<bool> OptionStrings;
219 OptionStrings.insert(std::make_pair("divd", false));
220 OptionStrings.insert(std::make_pair("divf", false));
221 OptionStrings.insert(std::make_pair("vec-divd", false));
222 OptionStrings.insert(std::make_pair("vec-divf", false));
223 OptionStrings.insert(std::make_pair("sqrtd", false));
224 OptionStrings.insert(std::make_pair("sqrtf", false));
225 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
226 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
227
228 for (unsigned i = 0; i != NumOptions; ++i) {
229 StringRef Val = A->getValue(i);
230
231 bool IsDisabled = Val.startswith(DisabledPrefixIn);
232 // Ignore the disablement token for string matching.
233 if (IsDisabled)
234 Val = Val.substr(1);
235
236 size_t RefStep;
237 if (!getRefinementStep(Val, D, *A, RefStep))
238 return;
239
240 StringRef ValBase = Val.slice(0, RefStep);
241 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
242 if (OptionIter == OptionStrings.end()) {
243 // Try again specifying float suffix.
244 OptionIter = OptionStrings.find(ValBase.str() + 'f');
245 if (OptionIter == OptionStrings.end()) {
246 // The input name did not match any known option string.
247 D.Diag(diag::err_drv_unknown_argument) << Val;
248 return;
249 }
250 // The option was specified without a float or double suffix.
251 // Make sure that the double entry was not already specified.
252 // The float entry will be checked below.
253 if (OptionStrings[ValBase.str() + 'd']) {
254 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
255 return;
256 }
257 }
258
259 if (OptionIter->second == true) {
260 // Duplicate option specified.
261 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
262 return;
263 }
264
265 // Mark the matched option as found. Do not allow duplicate specifiers.
266 OptionIter->second = true;
267
268 // If the precision was not specified, also mark the double entry as found.
269 if (ValBase.back() != 'f' && ValBase.back() != 'd')
270 OptionStrings[ValBase.str() + 'd'] = true;
271
272 // Build the output string.
273 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
274 Out = Args.MakeArgString(Out + Prefix + Val);
275 if (i != NumOptions - 1)
276 Out = Args.MakeArgString(Out + ",");
277 }
278
279 OutStrings.push_back(Args.MakeArgString(Out));
280}
281
Craig Topper9a724aa2017-12-11 21:09:19 +0000282/// The -mprefer-vector-width option accepts either a positive integer
283/// or the string "none".
284static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
285 ArgStringList &CmdArgs) {
286 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
287 if (!A)
288 return;
289
290 StringRef Value = A->getValue();
291 if (Value == "none") {
292 CmdArgs.push_back("-mprefer-vector-width=none");
293 } else {
294 unsigned Width;
295 if (Value.getAsInteger(10, Width)) {
296 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
297 return;
298 }
299 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
300 }
301}
302
David L. Jonesf561aba2017-03-08 01:02:16 +0000303static void getWebAssemblyTargetFeatures(const ArgList &Args,
304 std::vector<StringRef> &Features) {
305 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
306}
307
David L. Jonesf561aba2017-03-08 01:02:16 +0000308static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
309 const ArgList &Args, ArgStringList &CmdArgs,
310 bool ForAS) {
311 const Driver &D = TC.getDriver();
312 std::vector<StringRef> Features;
313 switch (Triple.getArch()) {
314 default:
315 break;
316 case llvm::Triple::mips:
317 case llvm::Triple::mipsel:
318 case llvm::Triple::mips64:
319 case llvm::Triple::mips64el:
320 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
321 break;
322
323 case llvm::Triple::arm:
324 case llvm::Triple::armeb:
325 case llvm::Triple::thumb:
326 case llvm::Triple::thumbeb:
327 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
328 break;
329
330 case llvm::Triple::ppc:
331 case llvm::Triple::ppc64:
332 case llvm::Triple::ppc64le:
333 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
334 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000335 case llvm::Triple::riscv32:
336 case llvm::Triple::riscv64:
337 riscv::getRISCVTargetFeatures(D, Args, Features);
338 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000339 case llvm::Triple::systemz:
340 systemz::getSystemZTargetFeatures(Args, Features);
341 break;
342 case llvm::Triple::aarch64:
343 case llvm::Triple::aarch64_be:
344 aarch64::getAArch64TargetFeatures(D, Args, Features);
345 break;
346 case llvm::Triple::x86:
347 case llvm::Triple::x86_64:
348 x86::getX86TargetFeatures(D, Triple, Args, Features);
349 break;
350 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000351 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000352 break;
353 case llvm::Triple::wasm32:
354 case llvm::Triple::wasm64:
355 getWebAssemblyTargetFeatures(Args, Features);
356 break;
357 case llvm::Triple::sparc:
358 case llvm::Triple::sparcel:
359 case llvm::Triple::sparcv9:
360 sparc::getSparcTargetFeatures(D, Args, Features);
361 break;
362 case llvm::Triple::r600:
363 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000364 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000365 break;
366 }
367
368 // Find the last of each feature.
369 llvm::StringMap<unsigned> LastOpt;
370 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
371 StringRef Name = Features[I];
372 assert(Name[0] == '-' || Name[0] == '+');
373 LastOpt[Name.drop_front(1)] = I;
374 }
375
376 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
377 // If this feature was overridden, ignore it.
378 StringRef Name = Features[I];
379 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
380 assert(LastI != LastOpt.end());
381 unsigned Last = LastI->second;
382 if (Last != I)
383 continue;
384
385 CmdArgs.push_back("-target-feature");
386 CmdArgs.push_back(Name.data());
387 }
388}
389
390static bool
391shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
392 const llvm::Triple &Triple) {
393 // We use the zero-cost exception tables for Objective-C if the non-fragile
394 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
395 // later.
396 if (runtime.isNonFragile())
397 return true;
398
399 if (!Triple.isMacOSX())
400 return false;
401
402 return (!Triple.isMacOSXVersionLT(10, 5) &&
403 (Triple.getArch() == llvm::Triple::x86_64 ||
404 Triple.getArch() == llvm::Triple::arm));
405}
406
407/// Adds exception related arguments to the driver command arguments. There's a
408/// master flag, -fexceptions and also language specific flags to enable/disable
409/// C++ and Objective-C exceptions. This makes it possible to for example
410/// disable C++ exceptions but enable Objective-C exceptions.
411static void addExceptionArgs(const ArgList &Args, types::ID InputType,
412 const ToolChain &TC, bool KernelOrKext,
413 const ObjCRuntime &objcRuntime,
414 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000415 const llvm::Triple &Triple = TC.getTriple();
416
417 if (KernelOrKext) {
418 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
419 // arguments now to avoid warnings about unused arguments.
420 Args.ClaimAllArgs(options::OPT_fexceptions);
421 Args.ClaimAllArgs(options::OPT_fno_exceptions);
422 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
423 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
424 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
425 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
426 return;
427 }
428
429 // See if the user explicitly enabled exceptions.
430 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
431 false);
432
433 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
434 // is not necessarily sensible, but follows GCC.
435 if (types::isObjC(InputType) &&
436 Args.hasFlag(options::OPT_fobjc_exceptions,
437 options::OPT_fno_objc_exceptions, true)) {
438 CmdArgs.push_back("-fobjc-exceptions");
439
440 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
441 }
442
443 if (types::isCXX(InputType)) {
444 // Disable C++ EH by default on XCore and PS4.
445 bool CXXExceptionsEnabled =
446 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
447 Arg *ExceptionArg = Args.getLastArg(
448 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
449 options::OPT_fexceptions, options::OPT_fno_exceptions);
450 if (ExceptionArg)
451 CXXExceptionsEnabled =
452 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
453 ExceptionArg->getOption().matches(options::OPT_fexceptions);
454
455 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000456 CmdArgs.push_back("-fcxx-exceptions");
457
458 EH = true;
459 }
460 }
461
462 if (EH)
463 CmdArgs.push_back("-fexceptions");
464}
465
466static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
467 bool Default = true;
468 if (TC.getTriple().isOSDarwin()) {
469 // The native darwin assembler doesn't support the linker_option directives,
470 // so we disable them if we think the .s file will be passed to it.
471 Default = TC.useIntegratedAs();
472 }
473 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
474 Default);
475}
476
477static bool ShouldDisableDwarfDirectory(const ArgList &Args,
478 const ToolChain &TC) {
479 bool UseDwarfDirectory =
480 Args.hasFlag(options::OPT_fdwarf_directory_asm,
481 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
482 return !UseDwarfDirectory;
483}
484
485// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
486// to the corresponding DebugInfoKind.
487static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
488 assert(A.getOption().matches(options::OPT_gN_Group) &&
489 "Not a -g option that specifies a debug-info level");
490 if (A.getOption().matches(options::OPT_g0) ||
491 A.getOption().matches(options::OPT_ggdb0))
492 return codegenoptions::NoDebugInfo;
493 if (A.getOption().matches(options::OPT_gline_tables_only) ||
494 A.getOption().matches(options::OPT_ggdb1))
495 return codegenoptions::DebugLineTablesOnly;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000496 if (A.getOption().matches(options::OPT_gline_directives_only))
497 return codegenoptions::DebugDirectivesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +0000498 return codegenoptions::LimitedDebugInfo;
499}
500
501static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
502 switch (Triple.getArch()){
503 default:
504 return false;
505 case llvm::Triple::arm:
506 case llvm::Triple::thumb:
507 // ARM Darwin targets require a frame pointer to be always present to aid
508 // offline debugging via backtraces.
509 return Triple.isOSDarwin();
510 }
511}
512
513static bool useFramePointerForTargetByDefault(const ArgList &Args,
514 const llvm::Triple &Triple) {
515 switch (Triple.getArch()) {
516 case llvm::Triple::xcore:
517 case llvm::Triple::wasm32:
518 case llvm::Triple::wasm64:
519 // XCore never wants frame pointers, regardless of OS.
520 // WebAssembly never wants frame pointers.
521 return false;
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000522 case llvm::Triple::riscv32:
523 case llvm::Triple::riscv64:
524 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000525 default:
526 break;
527 }
528
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000529 if (Triple.getOS() == llvm::Triple::NetBSD) {
530 return !areOptimizationsEnabled(Args);
531 }
532
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000533 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
534 Triple.isOSHurd()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000535 switch (Triple.getArch()) {
536 // Don't use a frame pointer on linux if optimizing for certain targets.
537 case llvm::Triple::mips64:
538 case llvm::Triple::mips64el:
539 case llvm::Triple::mips:
540 case llvm::Triple::mipsel:
541 case llvm::Triple::ppc:
542 case llvm::Triple::ppc64:
543 case llvm::Triple::ppc64le:
544 case llvm::Triple::systemz:
545 case llvm::Triple::x86:
546 case llvm::Triple::x86_64:
547 return !areOptimizationsEnabled(Args);
548 default:
549 return true;
550 }
551 }
552
553 if (Triple.isOSWindows()) {
554 switch (Triple.getArch()) {
555 case llvm::Triple::x86:
556 return !areOptimizationsEnabled(Args);
557 case llvm::Triple::x86_64:
558 return Triple.isOSBinFormatMachO();
559 case llvm::Triple::arm:
560 case llvm::Triple::thumb:
561 // Windows on ARM builds with FPO disabled to aid fast stack walking
562 return true;
563 default:
564 // All other supported Windows ISAs use xdata unwind information, so frame
565 // pointers are not generally useful.
566 return false;
567 }
568 }
569
570 return true;
571}
572
573static bool shouldUseFramePointer(const ArgList &Args,
574 const llvm::Triple &Triple) {
575 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
576 options::OPT_fomit_frame_pointer))
577 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
578 mustUseNonLeafFramePointerForTarget(Triple);
579
580 if (Args.hasArg(options::OPT_pg))
581 return true;
582
583 return useFramePointerForTargetByDefault(Args, Triple);
584}
585
586static bool shouldUseLeafFramePointer(const ArgList &Args,
587 const llvm::Triple &Triple) {
588 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
589 options::OPT_momit_leaf_frame_pointer))
590 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
591
592 if (Args.hasArg(options::OPT_pg))
593 return true;
594
595 if (Triple.isPS4CPU())
596 return false;
597
598 return useFramePointerForTargetByDefault(Args, Triple);
599}
600
601/// Add a CC1 option to specify the debug compilation directory.
602static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
603 SmallString<128> cwd;
604 if (!llvm::sys::fs::current_path(cwd)) {
605 CmdArgs.push_back("-fdebug-compilation-dir");
606 CmdArgs.push_back(Args.MakeArgString(cwd));
607 }
608}
609
Paul Robinson9b292b42018-07-10 15:15:24 +0000610/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
611static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
612 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
613 StringRef Map = A->getValue();
614 if (Map.find('=') == StringRef::npos)
615 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
616 else
617 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
618 A->claim();
619 }
620}
621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000622/// Vectorize at all optimization levels greater than 1 except for -Oz.
David L. Jonesf561aba2017-03-08 01:02:16 +0000623/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
624static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
625 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
626 if (A->getOption().matches(options::OPT_O4) ||
627 A->getOption().matches(options::OPT_Ofast))
628 return true;
629
630 if (A->getOption().matches(options::OPT_O0))
631 return false;
632
633 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
634
635 // Vectorize -Os.
636 StringRef S(A->getValue());
637 if (S == "s")
638 return true;
639
640 // Don't vectorize -Oz, unless it's the slp vectorizer.
641 if (S == "z")
642 return isSlpVec;
643
644 unsigned OptLevel = 0;
645 if (S.getAsInteger(10, OptLevel))
646 return false;
647
648 return OptLevel > 1;
649 }
650
651 return false;
652}
653
654/// Add -x lang to \p CmdArgs for \p Input.
655static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
656 ArgStringList &CmdArgs) {
657 // When using -verify-pch, we don't want to provide the type
658 // 'precompiled-header' if it was inferred from the file extension
659 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
660 return;
661
662 CmdArgs.push_back("-x");
663 if (Args.hasArg(options::OPT_rewrite_objc))
664 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000665 else {
666 // Map the driver type to the frontend type. This is mostly an identity
667 // mapping, except that the distinction between module interface units
668 // and other source files does not exist at the frontend layer.
669 const char *ClangType;
670 switch (Input.getType()) {
671 case types::TY_CXXModule:
672 ClangType = "c++";
673 break;
674 case types::TY_PP_CXXModule:
675 ClangType = "c++-cpp-output";
676 break;
677 default:
678 ClangType = types::getTypeName(Input.getType());
679 break;
680 }
681 CmdArgs.push_back(ClangType);
682 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000683}
684
685static void appendUserToPath(SmallVectorImpl<char> &Result) {
686#ifdef LLVM_ON_UNIX
687 const char *Username = getenv("LOGNAME");
688#else
689 const char *Username = getenv("USERNAME");
690#endif
691 if (Username) {
692 // Validate that LoginName can be used in a path, and get its length.
693 size_t Len = 0;
694 for (const char *P = Username; *P; ++P, ++Len) {
695 if (!clang::isAlphanumeric(*P) && *P != '_') {
696 Username = nullptr;
697 break;
698 }
699 }
700
701 if (Username && Len > 0) {
702 Result.append(Username, Username + Len);
703 return;
704 }
705 }
706
707// Fallback to user id.
708#ifdef LLVM_ON_UNIX
709 std::string UID = llvm::utostr(getuid());
710#else
711 // FIXME: Windows seems to have an 'SID' that might work.
712 std::string UID = "9999";
713#endif
714 Result.append(UID.begin(), UID.end());
715}
716
717static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
718 const InputInfo &Output, const ArgList &Args,
719 ArgStringList &CmdArgs) {
720
721 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
722 options::OPT_fprofile_generate_EQ,
723 options::OPT_fno_profile_generate);
724 if (PGOGenerateArg &&
725 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
726 PGOGenerateArg = nullptr;
727
728 auto *ProfileGenerateArg = Args.getLastArg(
729 options::OPT_fprofile_instr_generate,
730 options::OPT_fprofile_instr_generate_EQ,
731 options::OPT_fno_profile_instr_generate);
732 if (ProfileGenerateArg &&
733 ProfileGenerateArg->getOption().matches(
734 options::OPT_fno_profile_instr_generate))
735 ProfileGenerateArg = nullptr;
736
737 if (PGOGenerateArg && ProfileGenerateArg)
738 D.Diag(diag::err_drv_argument_not_allowed_with)
739 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
740
741 auto *ProfileUseArg = getLastProfileUseArg(Args);
742
743 if (PGOGenerateArg && ProfileUseArg)
744 D.Diag(diag::err_drv_argument_not_allowed_with)
745 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
746
747 if (ProfileGenerateArg && ProfileUseArg)
748 D.Diag(diag::err_drv_argument_not_allowed_with)
749 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
750
751 if (ProfileGenerateArg) {
752 if (ProfileGenerateArg->getOption().matches(
753 options::OPT_fprofile_instr_generate_EQ))
754 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
755 ProfileGenerateArg->getValue()));
756 // The default is to use Clang Instrumentation.
757 CmdArgs.push_back("-fprofile-instrument=clang");
758 }
759
760 if (PGOGenerateArg) {
761 CmdArgs.push_back("-fprofile-instrument=llvm");
762 if (PGOGenerateArg->getOption().matches(
763 options::OPT_fprofile_generate_EQ)) {
764 SmallString<128> Path(PGOGenerateArg->getValue());
765 llvm::sys::path::append(Path, "default_%m.profraw");
766 CmdArgs.push_back(
767 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
768 }
769 }
770
771 if (ProfileUseArg) {
772 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
773 CmdArgs.push_back(Args.MakeArgString(
774 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
775 else if ((ProfileUseArg->getOption().matches(
776 options::OPT_fprofile_use_EQ) ||
777 ProfileUseArg->getOption().matches(
778 options::OPT_fprofile_instr_use))) {
779 SmallString<128> Path(
780 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
781 if (Path.empty() || llvm::sys::fs::is_directory(Path))
782 llvm::sys::path::append(Path, "default.profdata");
783 CmdArgs.push_back(
784 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
785 }
786 }
787
788 if (Args.hasArg(options::OPT_ftest_coverage) ||
789 Args.hasArg(options::OPT_coverage))
790 CmdArgs.push_back("-femit-coverage-notes");
791 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
792 false) ||
793 Args.hasArg(options::OPT_coverage))
794 CmdArgs.push_back("-femit-coverage-data");
795
796 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000797 options::OPT_fno_coverage_mapping, false)) {
798 if (!ProfileGenerateArg)
799 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
800 << "-fcoverage-mapping"
801 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000802
David L. Jonesf561aba2017-03-08 01:02:16 +0000803 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000804 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000805
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000806 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
807 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
808 if (!Args.hasArg(options::OPT_coverage))
809 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
810 << "-fprofile-exclude-files="
811 << "--coverage";
812
813 StringRef v = Arg->getValue();
814 CmdArgs.push_back(
815 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
816 }
817
818 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
819 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
820 if (!Args.hasArg(options::OPT_coverage))
821 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
822 << "-fprofile-filter-files="
823 << "--coverage";
824
825 StringRef v = Arg->getValue();
826 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
827 }
828
David L. Jonesf561aba2017-03-08 01:02:16 +0000829 if (C.getArgs().hasArg(options::OPT_c) ||
830 C.getArgs().hasArg(options::OPT_S)) {
831 if (Output.isFilename()) {
832 CmdArgs.push_back("-coverage-notes-file");
833 SmallString<128> OutputFilename;
834 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
835 OutputFilename = FinalOutput->getValue();
836 else
837 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
838 SmallString<128> CoverageFilename = OutputFilename;
839 if (llvm::sys::path::is_relative(CoverageFilename)) {
840 SmallString<128> Pwd;
841 if (!llvm::sys::fs::current_path(Pwd)) {
842 llvm::sys::path::append(Pwd, CoverageFilename);
843 CoverageFilename.swap(Pwd);
844 }
845 }
846 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
847 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
848
849 // Leave -fprofile-dir= an unused argument unless .gcda emission is
850 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
851 // the flag used. There is no -fno-profile-dir, so the user has no
852 // targeted way to suppress the warning.
853 if (Args.hasArg(options::OPT_fprofile_arcs) ||
854 Args.hasArg(options::OPT_coverage)) {
855 CmdArgs.push_back("-coverage-data-file");
856 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
857 CoverageFilename = FProfileDir->getValue();
858 llvm::sys::path::append(CoverageFilename, OutputFilename);
859 }
860 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
861 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
862 }
863 }
864 }
865}
866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000867/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000868static bool ContainsCompileAction(const Action *A) {
869 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
870 return true;
871
872 for (const auto &AI : A->inputs())
873 if (ContainsCompileAction(AI))
874 return true;
875
876 return false;
877}
878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000879/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000880/// This is done by default when compiling non-assembler source with -O0.
881static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
882 bool RelaxDefault = true;
883
884 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
885 RelaxDefault = A->getOption().matches(options::OPT_O0);
886
887 if (RelaxDefault) {
888 RelaxDefault = false;
889 for (const auto &Act : C.getActions()) {
890 if (ContainsCompileAction(Act)) {
891 RelaxDefault = true;
892 break;
893 }
894 }
895 }
896
897 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
898 RelaxDefault);
899}
900
901// Extract the integer N from a string spelled "-dwarf-N", returning 0
902// on mismatch. The StringRef input (rather than an Arg) allows
903// for use by the "-Xassembler" option parser.
904static unsigned DwarfVersionNum(StringRef ArgValue) {
905 return llvm::StringSwitch<unsigned>(ArgValue)
906 .Case("-gdwarf-2", 2)
907 .Case("-gdwarf-3", 3)
908 .Case("-gdwarf-4", 4)
909 .Case("-gdwarf-5", 5)
910 .Default(0);
911}
912
913static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
914 codegenoptions::DebugInfoKind DebugInfoKind,
915 unsigned DwarfVersion,
916 llvm::DebuggerKind DebuggerTuning) {
917 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000918 case codegenoptions::DebugDirectivesOnly:
919 CmdArgs.push_back("-debug-info-kind=line-directives-only");
920 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000921 case codegenoptions::DebugLineTablesOnly:
922 CmdArgs.push_back("-debug-info-kind=line-tables-only");
923 break;
924 case codegenoptions::LimitedDebugInfo:
925 CmdArgs.push_back("-debug-info-kind=limited");
926 break;
927 case codegenoptions::FullDebugInfo:
928 CmdArgs.push_back("-debug-info-kind=standalone");
929 break;
930 default:
931 break;
932 }
933 if (DwarfVersion > 0)
934 CmdArgs.push_back(
935 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
936 switch (DebuggerTuning) {
937 case llvm::DebuggerKind::GDB:
938 CmdArgs.push_back("-debugger-tuning=gdb");
939 break;
940 case llvm::DebuggerKind::LLDB:
941 CmdArgs.push_back("-debugger-tuning=lldb");
942 break;
943 case llvm::DebuggerKind::SCE:
944 CmdArgs.push_back("-debugger-tuning=sce");
945 break;
946 default:
947 break;
948 }
949}
950
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000951static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
952 const Driver &D, const ToolChain &TC) {
953 assert(A && "Expected non-nullptr argument.");
954 if (TC.supportsDebugInfoOption(A))
955 return true;
956 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
957 << A->getAsString(Args) << TC.getTripleString();
958 return false;
959}
960
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000961static void RenderDebugInfoCompressionArgs(const ArgList &Args,
962 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000963 const Driver &D,
964 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000965 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
966 if (!A)
967 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000968 if (checkDebugInfoOption(A, Args, D, TC)) {
969 if (A->getOption().getID() == options::OPT_gz) {
970 if (llvm::zlib::isAvailable())
971 CmdArgs.push_back("-compress-debug-sections");
972 else
973 D.Diag(diag::warn_debug_compression_unavailable);
974 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000975 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000976
977 StringRef Value = A->getValue();
978 if (Value == "none") {
979 CmdArgs.push_back("-compress-debug-sections=none");
980 } else if (Value == "zlib" || Value == "zlib-gnu") {
981 if (llvm::zlib::isAvailable()) {
982 CmdArgs.push_back(
983 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
984 } else {
985 D.Diag(diag::warn_debug_compression_unavailable);
986 }
987 } else {
988 D.Diag(diag::err_drv_unsupported_option_argument)
989 << A->getOption().getName() << Value;
990 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000991 }
992}
993
David L. Jonesf561aba2017-03-08 01:02:16 +0000994static const char *RelocationModelName(llvm::Reloc::Model Model) {
995 switch (Model) {
996 case llvm::Reloc::Static:
997 return "static";
998 case llvm::Reloc::PIC_:
999 return "pic";
1000 case llvm::Reloc::DynamicNoPIC:
1001 return "dynamic-no-pic";
1002 case llvm::Reloc::ROPI:
1003 return "ropi";
1004 case llvm::Reloc::RWPI:
1005 return "rwpi";
1006 case llvm::Reloc::ROPI_RWPI:
1007 return "ropi-rwpi";
1008 }
1009 llvm_unreachable("Unknown Reloc::Model kind");
1010}
1011
1012void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1013 const Driver &D, const ArgList &Args,
1014 ArgStringList &CmdArgs,
1015 const InputInfo &Output,
1016 const InputInfoList &Inputs) const {
1017 Arg *A;
1018 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1019
1020 CheckPreprocessingOptions(D, Args);
1021
1022 Args.AddLastArg(CmdArgs, options::OPT_C);
1023 Args.AddLastArg(CmdArgs, options::OPT_CC);
1024
1025 // Handle dependency file generation.
1026 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1027 (A = Args.getLastArg(options::OPT_MD)) ||
1028 (A = Args.getLastArg(options::OPT_MMD))) {
1029 // Determine the output location.
1030 const char *DepFile;
1031 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1032 DepFile = MF->getValue();
1033 C.addFailureResultFile(DepFile, &JA);
1034 } else if (Output.getType() == types::TY_Dependencies) {
1035 DepFile = Output.getFilename();
1036 } else if (A->getOption().matches(options::OPT_M) ||
1037 A->getOption().matches(options::OPT_MM)) {
1038 DepFile = "-";
1039 } else {
1040 DepFile = getDependencyFileName(Args, Inputs);
1041 C.addFailureResultFile(DepFile, &JA);
1042 }
1043 CmdArgs.push_back("-dependency-file");
1044 CmdArgs.push_back(DepFile);
1045
1046 // Add a default target if one wasn't specified.
1047 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1048 const char *DepTarget;
1049
1050 // If user provided -o, that is the dependency target, except
1051 // when we are only generating a dependency file.
1052 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1053 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1054 DepTarget = OutputOpt->getValue();
1055 } else {
1056 // Otherwise derive from the base input.
1057 //
1058 // FIXME: This should use the computed output file location.
1059 SmallString<128> P(Inputs[0].getBaseInput());
1060 llvm::sys::path::replace_extension(P, "o");
1061 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1062 }
1063
Yuka Takahashicdb53482017-06-16 16:01:13 +00001064 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1065 CmdArgs.push_back("-w");
1066 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001067 CmdArgs.push_back("-MT");
1068 SmallString<128> Quoted;
1069 QuoteTarget(DepTarget, Quoted);
1070 CmdArgs.push_back(Args.MakeArgString(Quoted));
1071 }
1072
1073 if (A->getOption().matches(options::OPT_M) ||
1074 A->getOption().matches(options::OPT_MD))
1075 CmdArgs.push_back("-sys-header-deps");
1076 if ((isa<PrecompileJobAction>(JA) &&
1077 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1078 Args.hasArg(options::OPT_fmodule_file_deps))
1079 CmdArgs.push_back("-module-file-deps");
1080 }
1081
1082 if (Args.hasArg(options::OPT_MG)) {
1083 if (!A || A->getOption().matches(options::OPT_MD) ||
1084 A->getOption().matches(options::OPT_MMD))
1085 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1086 CmdArgs.push_back("-MG");
1087 }
1088
1089 Args.AddLastArg(CmdArgs, options::OPT_MP);
1090 Args.AddLastArg(CmdArgs, options::OPT_MV);
1091
1092 // Convert all -MQ <target> args to -MT <quoted target>
1093 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1094 A->claim();
1095
1096 if (A->getOption().matches(options::OPT_MQ)) {
1097 CmdArgs.push_back("-MT");
1098 SmallString<128> Quoted;
1099 QuoteTarget(A->getValue(), Quoted);
1100 CmdArgs.push_back(Args.MakeArgString(Quoted));
1101
1102 // -MT flag - no change
1103 } else {
1104 A->render(Args, CmdArgs);
1105 }
1106 }
1107
1108 // Add offload include arguments specific for CUDA. This must happen before
1109 // we -I or -include anything else, because we must pick up the CUDA headers
1110 // from the particular CUDA installation, rather than from e.g.
1111 // /usr/local/include.
1112 if (JA.isOffloading(Action::OFK_Cuda))
1113 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1114
1115 // Add -i* options, and automatically translate to
1116 // -include-pch/-include-pth for transparent PCH support. It's
1117 // wonky, but we include looking for .gch so we can support seamless
1118 // replacement into a build system already set up to be generating
1119 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001120
1121 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001122 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1123 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001124 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1125 JA.getKind() <= Action::AssembleJobClass) {
1126 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001127 }
Erich Keane76675de2018-07-05 17:22:13 +00001128 if (YcArg || YuArg) {
1129 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1130 if (!isa<PrecompileJobAction>(JA)) {
1131 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001132 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1133 C, !ThroughHeader.empty()
1134 ? ThroughHeader
1135 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001136 }
Mike Rice58df1af2018-09-11 17:10:44 +00001137
1138 if (ThroughHeader.empty()) {
1139 CmdArgs.push_back(Args.MakeArgString(
1140 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1141 } else {
1142 CmdArgs.push_back(
1143 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1144 }
Erich Keane76675de2018-07-05 17:22:13 +00001145 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001146 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001147
1148 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001149 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001150 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001151 // Handling of gcc-style gch precompiled headers.
1152 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1153 RenderedImplicitInclude = true;
1154
David L. Jonesf561aba2017-03-08 01:02:16 +00001155 bool FoundPCH = false;
1156 SmallString<128> P(A->getValue());
1157 // We want the files to have a name like foo.h.pch. Add a dummy extension
1158 // so that replace_extension does the right thing.
1159 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001160 llvm::sys::path::replace_extension(P, "pch");
1161 if (llvm::sys::fs::exists(P))
1162 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001163
1164 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001165 llvm::sys::path::replace_extension(P, "gch");
1166 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001167 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001168 }
1169 }
1170
Erich Keane0a6b5b62018-12-04 14:34:09 +00001171 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001172 if (IsFirstImplicitInclude) {
1173 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001174 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001175 CmdArgs.push_back(Args.MakeArgString(P));
1176 continue;
1177 } else {
1178 // Ignore the PCH if not first on command line and emit warning.
1179 D.Diag(diag::warn_drv_pch_not_first_include) << P
1180 << A->getAsString(Args);
1181 }
1182 }
1183 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1184 // Handling of paths which must come late. These entries are handled by
1185 // the toolchain itself after the resource dir is inserted in the right
1186 // search order.
1187 // Do not claim the argument so that the use of the argument does not
1188 // silently go unnoticed on toolchains which do not honour the option.
1189 continue;
1190 }
1191
1192 // Not translated, render as usual.
1193 A->claim();
1194 A->render(Args, CmdArgs);
1195 }
1196
1197 Args.AddAllArgs(CmdArgs,
1198 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1199 options::OPT_F, options::OPT_index_header_map});
1200
1201 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1202
1203 // FIXME: There is a very unfortunate problem here, some troubled
1204 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1205 // really support that we would have to parse and then translate
1206 // those options. :(
1207 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1208 options::OPT_Xpreprocessor);
1209
1210 // -I- is a deprecated GCC feature, reject it.
1211 if (Arg *A = Args.getLastArg(options::OPT_I_))
1212 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1213
1214 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1215 // -isysroot to the CC1 invocation.
1216 StringRef sysroot = C.getSysRoot();
1217 if (sysroot != "") {
1218 if (!Args.hasArg(options::OPT_isysroot)) {
1219 CmdArgs.push_back("-isysroot");
1220 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1221 }
1222 }
1223
1224 // Parse additional include paths from environment variables.
1225 // FIXME: We should probably sink the logic for handling these from the
1226 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1227 // CPATH - included following the user specified includes (but prior to
1228 // builtin and standard includes).
1229 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1230 // C_INCLUDE_PATH - system includes enabled when compiling C.
1231 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1232 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1233 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1234 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1235 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1236 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1237 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1238
1239 // While adding the include arguments, we also attempt to retrieve the
1240 // arguments of related offloading toolchains or arguments that are specific
1241 // of an offloading programming model.
1242
1243 // Add C++ include arguments, if needed.
1244 if (types::isCXX(Inputs[0].getType()))
1245 forAllAssociatedToolChains(C, JA, getToolChain(),
1246 [&Args, &CmdArgs](const ToolChain &TC) {
1247 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1248 });
1249
1250 // Add system include arguments for all targets but IAMCU.
1251 if (!IsIAMCU)
1252 forAllAssociatedToolChains(C, JA, getToolChain(),
1253 [&Args, &CmdArgs](const ToolChain &TC) {
1254 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1255 });
1256 else {
1257 // For IAMCU add special include arguments.
1258 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1259 }
1260}
1261
1262// FIXME: Move to target hook.
1263static bool isSignedCharDefault(const llvm::Triple &Triple) {
1264 switch (Triple.getArch()) {
1265 default:
1266 return true;
1267
1268 case llvm::Triple::aarch64:
1269 case llvm::Triple::aarch64_be:
1270 case llvm::Triple::arm:
1271 case llvm::Triple::armeb:
1272 case llvm::Triple::thumb:
1273 case llvm::Triple::thumbeb:
1274 if (Triple.isOSDarwin() || Triple.isOSWindows())
1275 return true;
1276 return false;
1277
1278 case llvm::Triple::ppc:
1279 case llvm::Triple::ppc64:
1280 if (Triple.isOSDarwin())
1281 return true;
1282 return false;
1283
1284 case llvm::Triple::hexagon:
1285 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001286 case llvm::Triple::riscv32:
1287 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001288 case llvm::Triple::systemz:
1289 case llvm::Triple::xcore:
1290 return false;
1291 }
1292}
1293
1294static bool isNoCommonDefault(const llvm::Triple &Triple) {
1295 switch (Triple.getArch()) {
1296 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001297 if (Triple.isOSFuchsia())
1298 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001299 return false;
1300
1301 case llvm::Triple::xcore:
1302 case llvm::Triple::wasm32:
1303 case llvm::Triple::wasm64:
1304 return true;
1305 }
1306}
1307
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001308namespace {
1309void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1310 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001311 // Select the ABI to use.
1312 // FIXME: Support -meabi.
1313 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1314 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001315 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001316 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001317 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001318 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001319 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001320 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001321
David L. Jonesf561aba2017-03-08 01:02:16 +00001322 CmdArgs.push_back("-target-abi");
1323 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001324}
1325}
1326
1327void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1328 ArgStringList &CmdArgs, bool KernelOrKext) const {
1329 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001330
1331 // Determine floating point ABI from the options & target defaults.
1332 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1333 if (ABI == arm::FloatABI::Soft) {
1334 // Floating point operations and argument passing are soft.
1335 // FIXME: This changes CPP defines, we need -target-soft-float.
1336 CmdArgs.push_back("-msoft-float");
1337 CmdArgs.push_back("-mfloat-abi");
1338 CmdArgs.push_back("soft");
1339 } else if (ABI == arm::FloatABI::SoftFP) {
1340 // Floating point operations are hard, but argument passing is soft.
1341 CmdArgs.push_back("-mfloat-abi");
1342 CmdArgs.push_back("soft");
1343 } else {
1344 // Floating point operations and argument passing are hard.
1345 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1346 CmdArgs.push_back("-mfloat-abi");
1347 CmdArgs.push_back("hard");
1348 }
1349
1350 // Forward the -mglobal-merge option for explicit control over the pass.
1351 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1352 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001353 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001354 if (A->getOption().matches(options::OPT_mno_global_merge))
1355 CmdArgs.push_back("-arm-global-merge=false");
1356 else
1357 CmdArgs.push_back("-arm-global-merge=true");
1358 }
1359
1360 if (!Args.hasFlag(options::OPT_mimplicit_float,
1361 options::OPT_mno_implicit_float, true))
1362 CmdArgs.push_back("-no-implicit-float");
1363}
1364
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001365void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1366 const ArgList &Args, bool KernelOrKext,
1367 ArgStringList &CmdArgs) const {
1368 const ToolChain &TC = getToolChain();
1369
1370 // Add the target features
1371 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1372
1373 // Add target specific flags.
1374 switch (TC.getArch()) {
1375 default:
1376 break;
1377
1378 case llvm::Triple::arm:
1379 case llvm::Triple::armeb:
1380 case llvm::Triple::thumb:
1381 case llvm::Triple::thumbeb:
1382 // Use the effective triple, which takes into account the deployment target.
1383 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1384 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1385 break;
1386
1387 case llvm::Triple::aarch64:
1388 case llvm::Triple::aarch64_be:
1389 AddAArch64TargetArgs(Args, CmdArgs);
1390 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1391 break;
1392
1393 case llvm::Triple::mips:
1394 case llvm::Triple::mipsel:
1395 case llvm::Triple::mips64:
1396 case llvm::Triple::mips64el:
1397 AddMIPSTargetArgs(Args, CmdArgs);
1398 break;
1399
1400 case llvm::Triple::ppc:
1401 case llvm::Triple::ppc64:
1402 case llvm::Triple::ppc64le:
1403 AddPPCTargetArgs(Args, CmdArgs);
1404 break;
1405
Alex Bradbury71f45452018-01-11 13:36:56 +00001406 case llvm::Triple::riscv32:
1407 case llvm::Triple::riscv64:
1408 AddRISCVTargetArgs(Args, CmdArgs);
1409 break;
1410
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001411 case llvm::Triple::sparc:
1412 case llvm::Triple::sparcel:
1413 case llvm::Triple::sparcv9:
1414 AddSparcTargetArgs(Args, CmdArgs);
1415 break;
1416
1417 case llvm::Triple::systemz:
1418 AddSystemZTargetArgs(Args, CmdArgs);
1419 break;
1420
1421 case llvm::Triple::x86:
1422 case llvm::Triple::x86_64:
1423 AddX86TargetArgs(Args, CmdArgs);
1424 break;
1425
1426 case llvm::Triple::lanai:
1427 AddLanaiTargetArgs(Args, CmdArgs);
1428 break;
1429
1430 case llvm::Triple::hexagon:
1431 AddHexagonTargetArgs(Args, CmdArgs);
1432 break;
1433
1434 case llvm::Triple::wasm32:
1435 case llvm::Triple::wasm64:
1436 AddWebAssemblyTargetArgs(Args, CmdArgs);
1437 break;
1438 }
1439}
1440
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001441// Parse -mbranch-protection=<protection>[+<protection>]* where
1442// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1443// Returns a triple of (return address signing Scope, signing key, require
1444// landing pads)
1445static std::tuple<StringRef, StringRef, bool>
1446ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1447 const Arg *A) {
1448 StringRef Scope = "none";
1449 StringRef Key = "a_key";
1450 bool IndirectBranches = false;
1451
1452 StringRef Value = A->getValue();
1453 // This maps onto -mbranch-protection=<scope>+<key>
1454
1455 if (Value.equals("standard")) {
1456 Scope = "non-leaf";
1457 Key = "a_key";
1458 IndirectBranches = true;
1459
1460 } else if (!Value.equals("none")) {
1461 SmallVector<StringRef, 4> BranchProtection;
1462 StringRef(A->getValue()).split(BranchProtection, '+');
1463
1464 auto Protection = BranchProtection.begin();
1465 while (Protection != BranchProtection.end()) {
1466 if (Protection->equals("bti"))
1467 IndirectBranches = true;
1468 else if (Protection->equals("pac-ret")) {
1469 Scope = "non-leaf";
1470 while (++Protection != BranchProtection.end()) {
1471 // Inner loop as "leaf" and "b-key" options must only appear attached
1472 // to pac-ret.
1473 if (Protection->equals("leaf"))
1474 Scope = "all";
1475 else if (Protection->equals("b-key"))
1476 Key = "b_key";
1477 else
1478 break;
1479 }
1480 Protection--;
1481 } else
1482 D.Diag(diag::err_invalid_branch_protection)
1483 << *Protection << A->getAsString(Args);
1484 Protection++;
1485 }
1486 }
1487
1488 return std::make_tuple(Scope, Key, IndirectBranches);
1489}
1490
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001491namespace {
1492void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1493 ArgStringList &CmdArgs) {
1494 const char *ABIName = nullptr;
1495 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1496 ABIName = A->getValue();
1497 else if (Triple.isOSDarwin())
1498 ABIName = "darwinpcs";
1499 else
1500 ABIName = "aapcs";
1501
1502 CmdArgs.push_back("-target-abi");
1503 CmdArgs.push_back(ABIName);
1504}
1505}
1506
David L. Jonesf561aba2017-03-08 01:02:16 +00001507void Clang::AddAArch64TargetArgs(const ArgList &Args,
1508 ArgStringList &CmdArgs) const {
1509 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1510
1511 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1512 Args.hasArg(options::OPT_mkernel) ||
1513 Args.hasArg(options::OPT_fapple_kext))
1514 CmdArgs.push_back("-disable-red-zone");
1515
1516 if (!Args.hasFlag(options::OPT_mimplicit_float,
1517 options::OPT_mno_implicit_float, true))
1518 CmdArgs.push_back("-no-implicit-float");
1519
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001520 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001521
1522 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1523 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001524 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001525 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1526 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1527 else
1528 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1529 } else if (Triple.isAndroid()) {
1530 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001531 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001532 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1533 }
1534
1535 // Forward the -mglobal-merge option for explicit control over the pass.
1536 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1537 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001538 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001539 if (A->getOption().matches(options::OPT_mno_global_merge))
1540 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1541 else
1542 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1543 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001544
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001545 // Enable/disable return address signing and indirect branch targets.
1546 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1547 options::OPT_mbranch_protection_EQ)) {
1548
1549 const Driver &D = getToolChain().getDriver();
1550
1551 StringRef Scope, Key;
1552 bool IndirectBranches;
1553
1554 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1555 Scope = A->getValue();
1556 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1557 !Scope.equals("all"))
1558 D.Diag(diag::err_invalid_branch_protection)
1559 << Scope << A->getAsString(Args);
1560 Key = "a_key";
1561 IndirectBranches = false;
1562 } else
1563 std::tie(Scope, Key, IndirectBranches) =
1564 ParseAArch64BranchProtection(D, Args, A);
1565
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001566 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001567 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1568 CmdArgs.push_back(
1569 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1570 if (IndirectBranches)
1571 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001572 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001573}
1574
1575void Clang::AddMIPSTargetArgs(const ArgList &Args,
1576 ArgStringList &CmdArgs) const {
1577 const Driver &D = getToolChain().getDriver();
1578 StringRef CPUName;
1579 StringRef ABIName;
1580 const llvm::Triple &Triple = getToolChain().getTriple();
1581 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1582
1583 CmdArgs.push_back("-target-abi");
1584 CmdArgs.push_back(ABIName.data());
1585
1586 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1587 if (ABI == mips::FloatABI::Soft) {
1588 // Floating point operations and argument passing are soft.
1589 CmdArgs.push_back("-msoft-float");
1590 CmdArgs.push_back("-mfloat-abi");
1591 CmdArgs.push_back("soft");
1592 } else {
1593 // Floating point operations and argument passing are hard.
1594 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1595 CmdArgs.push_back("-mfloat-abi");
1596 CmdArgs.push_back("hard");
1597 }
1598
1599 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1600 if (A->getOption().matches(options::OPT_mxgot)) {
1601 CmdArgs.push_back("-mllvm");
1602 CmdArgs.push_back("-mxgot");
1603 }
1604 }
1605
1606 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1607 options::OPT_mno_ldc1_sdc1)) {
1608 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1609 CmdArgs.push_back("-mllvm");
1610 CmdArgs.push_back("-mno-ldc1-sdc1");
1611 }
1612 }
1613
1614 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1615 options::OPT_mno_check_zero_division)) {
1616 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1617 CmdArgs.push_back("-mllvm");
1618 CmdArgs.push_back("-mno-check-zero-division");
1619 }
1620 }
1621
1622 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1623 StringRef v = A->getValue();
1624 CmdArgs.push_back("-mllvm");
1625 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1626 A->claim();
1627 }
1628
Simon Dardis31636a12017-07-20 14:04:12 +00001629 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1630 Arg *ABICalls =
1631 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1632
1633 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1634 // -mgpopt is the default for static, -fno-pic environments but these two
1635 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1636 // the only case where -mllvm -mgpopt is passed.
1637 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1638 // passed explicitly when compiling something with -mabicalls
1639 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001640 //
1641 // When the ABI in use is N64, we also need to determine the PIC mode that
1642 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001643 bool NoABICalls =
1644 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001645
1646 llvm::Reloc::Model RelocationModel;
1647 unsigned PICLevel;
1648 bool IsPIE;
1649 std::tie(RelocationModel, PICLevel, IsPIE) =
1650 ParsePICArgs(getToolChain(), Args);
1651
1652 NoABICalls = NoABICalls ||
1653 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1654
Simon Dardis31636a12017-07-20 14:04:12 +00001655 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1656 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1657 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1658 CmdArgs.push_back("-mllvm");
1659 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001660
1661 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1662 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001663 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001664 options::OPT_mno_extern_sdata);
1665 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1666 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001667 if (LocalSData) {
1668 CmdArgs.push_back("-mllvm");
1669 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1670 CmdArgs.push_back("-mlocal-sdata=1");
1671 } else {
1672 CmdArgs.push_back("-mlocal-sdata=0");
1673 }
1674 LocalSData->claim();
1675 }
1676
Simon Dardis7d318782017-07-24 14:02:09 +00001677 if (ExternSData) {
1678 CmdArgs.push_back("-mllvm");
1679 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1680 CmdArgs.push_back("-mextern-sdata=1");
1681 } else {
1682 CmdArgs.push_back("-mextern-sdata=0");
1683 }
1684 ExternSData->claim();
1685 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001686
1687 if (EmbeddedData) {
1688 CmdArgs.push_back("-mllvm");
1689 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1690 CmdArgs.push_back("-membedded-data=1");
1691 } else {
1692 CmdArgs.push_back("-membedded-data=0");
1693 }
1694 EmbeddedData->claim();
1695 }
1696
Simon Dardis31636a12017-07-20 14:04:12 +00001697 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1698 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1699
1700 if (GPOpt)
1701 GPOpt->claim();
1702
David L. Jonesf561aba2017-03-08 01:02:16 +00001703 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1704 StringRef Val = StringRef(A->getValue());
1705 if (mips::hasCompactBranches(CPUName)) {
1706 if (Val == "never" || Val == "always" || Val == "optimal") {
1707 CmdArgs.push_back("-mllvm");
1708 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1709 } else
1710 D.Diag(diag::err_drv_unsupported_option_argument)
1711 << A->getOption().getName() << Val;
1712 } else
1713 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1714 }
1715}
1716
1717void Clang::AddPPCTargetArgs(const ArgList &Args,
1718 ArgStringList &CmdArgs) const {
1719 // Select the ABI to use.
1720 const char *ABIName = nullptr;
1721 if (getToolChain().getTriple().isOSLinux())
1722 switch (getToolChain().getArch()) {
1723 case llvm::Triple::ppc64: {
1724 // When targeting a processor that supports QPX, or if QPX is
1725 // specifically enabled, default to using the ABI that supports QPX (so
1726 // long as it is not specifically disabled).
1727 bool HasQPX = false;
1728 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1729 HasQPX = A->getValue() == StringRef("a2q");
1730 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1731 if (HasQPX) {
1732 ABIName = "elfv1-qpx";
1733 break;
1734 }
1735
1736 ABIName = "elfv1";
1737 break;
1738 }
1739 case llvm::Triple::ppc64le:
1740 ABIName = "elfv2";
1741 break;
1742 default:
1743 break;
1744 }
1745
1746 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1747 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1748 // the option if given as we don't have backend support for any targets
1749 // that don't use the altivec abi.
1750 if (StringRef(A->getValue()) != "altivec")
1751 ABIName = A->getValue();
1752
1753 ppc::FloatABI FloatABI =
1754 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1755
1756 if (FloatABI == ppc::FloatABI::Soft) {
1757 // Floating point operations and argument passing are soft.
1758 CmdArgs.push_back("-msoft-float");
1759 CmdArgs.push_back("-mfloat-abi");
1760 CmdArgs.push_back("soft");
1761 } else {
1762 // Floating point operations and argument passing are hard.
1763 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1764 CmdArgs.push_back("-mfloat-abi");
1765 CmdArgs.push_back("hard");
1766 }
1767
1768 if (ABIName) {
1769 CmdArgs.push_back("-target-abi");
1770 CmdArgs.push_back(ABIName);
1771 }
1772}
1773
Alex Bradbury71f45452018-01-11 13:36:56 +00001774void Clang::AddRISCVTargetArgs(const ArgList &Args,
1775 ArgStringList &CmdArgs) const {
1776 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001777 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001778 const char *ABIName = nullptr;
1779 const llvm::Triple &Triple = getToolChain().getTriple();
1780 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1781 ABIName = A->getValue();
1782 else if (Triple.getArch() == llvm::Triple::riscv32)
1783 ABIName = "ilp32";
1784 else if (Triple.getArch() == llvm::Triple::riscv64)
1785 ABIName = "lp64";
1786 else
1787 llvm_unreachable("Unexpected triple!");
1788
1789 CmdArgs.push_back("-target-abi");
1790 CmdArgs.push_back(ABIName);
1791}
1792
David L. Jonesf561aba2017-03-08 01:02:16 +00001793void Clang::AddSparcTargetArgs(const ArgList &Args,
1794 ArgStringList &CmdArgs) const {
1795 sparc::FloatABI FloatABI =
1796 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1797
1798 if (FloatABI == sparc::FloatABI::Soft) {
1799 // Floating point operations and argument passing are soft.
1800 CmdArgs.push_back("-msoft-float");
1801 CmdArgs.push_back("-mfloat-abi");
1802 CmdArgs.push_back("soft");
1803 } else {
1804 // Floating point operations and argument passing are hard.
1805 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1806 CmdArgs.push_back("-mfloat-abi");
1807 CmdArgs.push_back("hard");
1808 }
1809}
1810
1811void Clang::AddSystemZTargetArgs(const ArgList &Args,
1812 ArgStringList &CmdArgs) const {
1813 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1814 CmdArgs.push_back("-mbackchain");
1815}
1816
1817void Clang::AddX86TargetArgs(const ArgList &Args,
1818 ArgStringList &CmdArgs) const {
1819 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1820 Args.hasArg(options::OPT_mkernel) ||
1821 Args.hasArg(options::OPT_fapple_kext))
1822 CmdArgs.push_back("-disable-red-zone");
1823
Kristina Brooks7f569b72018-10-18 14:07:02 +00001824 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1825 options::OPT_mno_tls_direct_seg_refs, true))
1826 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1827
David L. Jonesf561aba2017-03-08 01:02:16 +00001828 // Default to avoid implicit floating-point for kernel/kext code, but allow
1829 // that to be overridden with -mno-soft-float.
1830 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1831 Args.hasArg(options::OPT_fapple_kext));
1832 if (Arg *A = Args.getLastArg(
1833 options::OPT_msoft_float, options::OPT_mno_soft_float,
1834 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1835 const Option &O = A->getOption();
1836 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1837 O.matches(options::OPT_msoft_float));
1838 }
1839 if (NoImplicitFloat)
1840 CmdArgs.push_back("-no-implicit-float");
1841
1842 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1843 StringRef Value = A->getValue();
1844 if (Value == "intel" || Value == "att") {
1845 CmdArgs.push_back("-mllvm");
1846 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1847 } else {
1848 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1849 << A->getOption().getName() << Value;
1850 }
Nico Webere3712cf2018-01-17 13:34:20 +00001851 } else if (getToolChain().getDriver().IsCLMode()) {
1852 CmdArgs.push_back("-mllvm");
1853 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001854 }
1855
1856 // Set flags to support MCU ABI.
1857 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1858 CmdArgs.push_back("-mfloat-abi");
1859 CmdArgs.push_back("soft");
1860 CmdArgs.push_back("-mstack-alignment=4");
1861 }
1862}
1863
1864void Clang::AddHexagonTargetArgs(const ArgList &Args,
1865 ArgStringList &CmdArgs) const {
1866 CmdArgs.push_back("-mqdsp6-compat");
1867 CmdArgs.push_back("-Wreturn-type");
1868
1869 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001870 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001871 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1872 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001873 }
1874
1875 if (!Args.hasArg(options::OPT_fno_short_enums))
1876 CmdArgs.push_back("-fshort-enums");
1877 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1878 CmdArgs.push_back("-mllvm");
1879 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1880 }
1881 CmdArgs.push_back("-mllvm");
1882 CmdArgs.push_back("-machine-sink-split=0");
1883}
1884
1885void Clang::AddLanaiTargetArgs(const ArgList &Args,
1886 ArgStringList &CmdArgs) const {
1887 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1888 StringRef CPUName = A->getValue();
1889
1890 CmdArgs.push_back("-target-cpu");
1891 CmdArgs.push_back(Args.MakeArgString(CPUName));
1892 }
1893 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1894 StringRef Value = A->getValue();
1895 // Only support mregparm=4 to support old usage. Report error for all other
1896 // cases.
1897 int Mregparm;
1898 if (Value.getAsInteger(10, Mregparm)) {
1899 if (Mregparm != 4) {
1900 getToolChain().getDriver().Diag(
1901 diag::err_drv_unsupported_option_argument)
1902 << A->getOption().getName() << Value;
1903 }
1904 }
1905 }
1906}
1907
1908void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1909 ArgStringList &CmdArgs) const {
1910 // Default to "hidden" visibility.
1911 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1912 options::OPT_fvisibility_ms_compat)) {
1913 CmdArgs.push_back("-fvisibility");
1914 CmdArgs.push_back("hidden");
1915 }
1916}
1917
1918void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1919 StringRef Target, const InputInfo &Output,
1920 const InputInfo &Input, const ArgList &Args) const {
1921 // If this is a dry run, do not create the compilation database file.
1922 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1923 return;
1924
1925 using llvm::yaml::escape;
1926 const Driver &D = getToolChain().getDriver();
1927
1928 if (!CompilationDatabase) {
1929 std::error_code EC;
1930 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1931 if (EC) {
1932 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1933 << EC.message();
1934 return;
1935 }
1936 CompilationDatabase = std::move(File);
1937 }
1938 auto &CDB = *CompilationDatabase;
1939 SmallString<128> Buf;
1940 if (llvm::sys::fs::current_path(Buf))
1941 Buf = ".";
1942 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1943 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1944 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1945 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1946 Buf = "-x";
1947 Buf += types::getTypeName(Input.getType());
1948 CDB << ", \"" << escape(Buf) << "\"";
1949 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1950 Buf = "--sysroot=";
1951 Buf += D.SysRoot;
1952 CDB << ", \"" << escape(Buf) << "\"";
1953 }
1954 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1955 for (auto &A: Args) {
1956 auto &O = A->getOption();
1957 // Skip language selection, which is positional.
1958 if (O.getID() == options::OPT_x)
1959 continue;
1960 // Skip writing dependency output and the compilation database itself.
1961 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1962 continue;
1963 // Skip inputs.
1964 if (O.getKind() == Option::InputClass)
1965 continue;
1966 // All other arguments are quoted and appended.
1967 ArgStringList ASL;
1968 A->render(Args, ASL);
1969 for (auto &it: ASL)
1970 CDB << ", \"" << escape(it) << "\"";
1971 }
1972 Buf = "--target=";
1973 Buf += Target;
1974 CDB << ", \"" << escape(Buf) << "\"]},\n";
1975}
1976
1977static void CollectArgsForIntegratedAssembler(Compilation &C,
1978 const ArgList &Args,
1979 ArgStringList &CmdArgs,
1980 const Driver &D) {
1981 if (UseRelaxAll(C, Args))
1982 CmdArgs.push_back("-mrelax-all");
1983
1984 // Only default to -mincremental-linker-compatible if we think we are
1985 // targeting the MSVC linker.
1986 bool DefaultIncrementalLinkerCompatible =
1987 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1988 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1989 options::OPT_mno_incremental_linker_compatible,
1990 DefaultIncrementalLinkerCompatible))
1991 CmdArgs.push_back("-mincremental-linker-compatible");
1992
1993 switch (C.getDefaultToolChain().getArch()) {
1994 case llvm::Triple::arm:
1995 case llvm::Triple::armeb:
1996 case llvm::Triple::thumb:
1997 case llvm::Triple::thumbeb:
1998 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1999 StringRef Value = A->getValue();
2000 if (Value == "always" || Value == "never" || Value == "arm" ||
2001 Value == "thumb") {
2002 CmdArgs.push_back("-mllvm");
2003 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2004 } else {
2005 D.Diag(diag::err_drv_unsupported_option_argument)
2006 << A->getOption().getName() << Value;
2007 }
2008 }
2009 break;
2010 default:
2011 break;
2012 }
2013
2014 // When passing -I arguments to the assembler we sometimes need to
2015 // unconditionally take the next argument. For example, when parsing
2016 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2017 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2018 // arg after parsing the '-I' arg.
2019 bool TakeNextArg = false;
2020
Petr Hosek5668d832017-11-22 01:38:31 +00002021 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00002022 const char *MipsTargetFeature = nullptr;
2023 for (const Arg *A :
2024 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2025 A->claim();
2026
2027 for (StringRef Value : A->getValues()) {
2028 if (TakeNextArg) {
2029 CmdArgs.push_back(Value.data());
2030 TakeNextArg = false;
2031 continue;
2032 }
2033
2034 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2035 Value == "-mbig-obj")
2036 continue; // LLVM handles bigobj automatically
2037
2038 switch (C.getDefaultToolChain().getArch()) {
2039 default:
2040 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002041 case llvm::Triple::thumb:
2042 case llvm::Triple::thumbeb:
2043 case llvm::Triple::arm:
2044 case llvm::Triple::armeb:
2045 if (Value == "-mthumb")
2046 // -mthumb has already been processed in ComputeLLVMTriple()
2047 // recognize but skip over here.
2048 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002049 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002050 case llvm::Triple::mips:
2051 case llvm::Triple::mipsel:
2052 case llvm::Triple::mips64:
2053 case llvm::Triple::mips64el:
2054 if (Value == "--trap") {
2055 CmdArgs.push_back("-target-feature");
2056 CmdArgs.push_back("+use-tcc-in-div");
2057 continue;
2058 }
2059 if (Value == "--break") {
2060 CmdArgs.push_back("-target-feature");
2061 CmdArgs.push_back("-use-tcc-in-div");
2062 continue;
2063 }
2064 if (Value.startswith("-msoft-float")) {
2065 CmdArgs.push_back("-target-feature");
2066 CmdArgs.push_back("+soft-float");
2067 continue;
2068 }
2069 if (Value.startswith("-mhard-float")) {
2070 CmdArgs.push_back("-target-feature");
2071 CmdArgs.push_back("-soft-float");
2072 continue;
2073 }
2074
2075 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2076 .Case("-mips1", "+mips1")
2077 .Case("-mips2", "+mips2")
2078 .Case("-mips3", "+mips3")
2079 .Case("-mips4", "+mips4")
2080 .Case("-mips5", "+mips5")
2081 .Case("-mips32", "+mips32")
2082 .Case("-mips32r2", "+mips32r2")
2083 .Case("-mips32r3", "+mips32r3")
2084 .Case("-mips32r5", "+mips32r5")
2085 .Case("-mips32r6", "+mips32r6")
2086 .Case("-mips64", "+mips64")
2087 .Case("-mips64r2", "+mips64r2")
2088 .Case("-mips64r3", "+mips64r3")
2089 .Case("-mips64r5", "+mips64r5")
2090 .Case("-mips64r6", "+mips64r6")
2091 .Default(nullptr);
2092 if (MipsTargetFeature)
2093 continue;
2094 }
2095
2096 if (Value == "-force_cpusubtype_ALL") {
2097 // Do nothing, this is the default and we don't support anything else.
2098 } else if (Value == "-L") {
2099 CmdArgs.push_back("-msave-temp-labels");
2100 } else if (Value == "--fatal-warnings") {
2101 CmdArgs.push_back("-massembler-fatal-warnings");
2102 } else if (Value == "--noexecstack") {
2103 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002104 } else if (Value.startswith("-compress-debug-sections") ||
2105 Value.startswith("--compress-debug-sections") ||
2106 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002107 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002108 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002109 } else if (Value == "-mrelax-relocations=yes" ||
2110 Value == "--mrelax-relocations=yes") {
2111 UseRelaxRelocations = true;
2112 } else if (Value == "-mrelax-relocations=no" ||
2113 Value == "--mrelax-relocations=no") {
2114 UseRelaxRelocations = false;
2115 } else if (Value.startswith("-I")) {
2116 CmdArgs.push_back(Value.data());
2117 // We need to consume the next argument if the current arg is a plain
2118 // -I. The next arg will be the include directory.
2119 if (Value == "-I")
2120 TakeNextArg = true;
2121 } else if (Value.startswith("-gdwarf-")) {
2122 // "-gdwarf-N" options are not cc1as options.
2123 unsigned DwarfVersion = DwarfVersionNum(Value);
2124 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2125 CmdArgs.push_back(Value.data());
2126 } else {
2127 RenderDebugEnablingArgs(Args, CmdArgs,
2128 codegenoptions::LimitedDebugInfo,
2129 DwarfVersion, llvm::DebuggerKind::Default);
2130 }
2131 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2132 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2133 // Do nothing, we'll validate it later.
2134 } else if (Value == "-defsym") {
2135 if (A->getNumValues() != 2) {
2136 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2137 break;
2138 }
2139 const char *S = A->getValue(1);
2140 auto Pair = StringRef(S).split('=');
2141 auto Sym = Pair.first;
2142 auto SVal = Pair.second;
2143
2144 if (Sym.empty() || SVal.empty()) {
2145 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2146 break;
2147 }
2148 int64_t IVal;
2149 if (SVal.getAsInteger(0, IVal)) {
2150 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2151 break;
2152 }
2153 CmdArgs.push_back(Value.data());
2154 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002155 } else if (Value == "-fdebug-compilation-dir") {
2156 CmdArgs.push_back("-fdebug-compilation-dir");
2157 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002158 } else {
2159 D.Diag(diag::err_drv_unsupported_option_argument)
2160 << A->getOption().getName() << Value;
2161 }
2162 }
2163 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002164 if (UseRelaxRelocations)
2165 CmdArgs.push_back("--mrelax-relocations");
2166 if (MipsTargetFeature != nullptr) {
2167 CmdArgs.push_back("-target-feature");
2168 CmdArgs.push_back(MipsTargetFeature);
2169 }
Steven Wu098742f2018-12-12 17:30:16 +00002170
2171 // forward -fembed-bitcode to assmebler
2172 if (C.getDriver().embedBitcodeEnabled() ||
2173 C.getDriver().embedBitcodeMarkerOnly())
2174 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002175}
2176
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002177static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2178 bool OFastEnabled, const ArgList &Args,
2179 ArgStringList &CmdArgs) {
2180 // Handle various floating point optimization flags, mapping them to the
2181 // appropriate LLVM code generation flags. This is complicated by several
2182 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002183 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002184 // LLVM flags based on the final state.
2185 bool HonorINFs = true;
2186 bool HonorNaNs = true;
2187 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2188 bool MathErrno = TC.IsMathErrnoDefault();
2189 bool AssociativeMath = false;
2190 bool ReciprocalMath = false;
2191 bool SignedZeros = true;
2192 bool TrappingMath = true;
2193 StringRef DenormalFPMath = "";
2194 StringRef FPContract = "";
2195
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002196 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2197 CmdArgs.push_back("-mlimit-float-precision");
2198 CmdArgs.push_back(A->getValue());
2199 }
2200
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002201 for (const Arg *A : Args) {
2202 switch (A->getOption().getID()) {
2203 // If this isn't an FP option skip the claim below
2204 default: continue;
2205
2206 // Options controlling individual features
2207 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2208 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2209 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2210 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2211 case options::OPT_fmath_errno: MathErrno = true; break;
2212 case options::OPT_fno_math_errno: MathErrno = false; break;
2213 case options::OPT_fassociative_math: AssociativeMath = true; break;
2214 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2215 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2216 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2217 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2218 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2219 case options::OPT_ftrapping_math: TrappingMath = true; break;
2220 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2221
2222 case options::OPT_fdenormal_fp_math_EQ:
2223 DenormalFPMath = A->getValue();
2224 break;
2225
2226 // Validate and pass through -fp-contract option.
2227 case options::OPT_ffp_contract: {
2228 StringRef Val = A->getValue();
2229 if (Val == "fast" || Val == "on" || Val == "off")
2230 FPContract = Val;
2231 else
2232 D.Diag(diag::err_drv_unsupported_option_argument)
2233 << A->getOption().getName() << Val;
2234 break;
2235 }
2236
2237 case options::OPT_ffinite_math_only:
2238 HonorINFs = false;
2239 HonorNaNs = false;
2240 break;
2241 case options::OPT_fno_finite_math_only:
2242 HonorINFs = true;
2243 HonorNaNs = true;
2244 break;
2245
2246 case options::OPT_funsafe_math_optimizations:
2247 AssociativeMath = true;
2248 ReciprocalMath = true;
2249 SignedZeros = false;
2250 TrappingMath = false;
2251 break;
2252 case options::OPT_fno_unsafe_math_optimizations:
2253 AssociativeMath = false;
2254 ReciprocalMath = false;
2255 SignedZeros = true;
2256 TrappingMath = true;
2257 // -fno_unsafe_math_optimizations restores default denormal handling
2258 DenormalFPMath = "";
2259 break;
2260
2261 case options::OPT_Ofast:
2262 // If -Ofast is the optimization level, then -ffast-math should be enabled
2263 if (!OFastEnabled)
2264 continue;
2265 LLVM_FALLTHROUGH;
2266 case options::OPT_ffast_math:
2267 HonorINFs = false;
2268 HonorNaNs = false;
2269 MathErrno = false;
2270 AssociativeMath = true;
2271 ReciprocalMath = true;
2272 SignedZeros = false;
2273 TrappingMath = false;
2274 // If fast-math is set then set the fp-contract mode to fast.
2275 FPContract = "fast";
2276 break;
2277 case options::OPT_fno_fast_math:
2278 HonorINFs = true;
2279 HonorNaNs = true;
2280 // Turning on -ffast-math (with either flag) removes the need for
2281 // MathErrno. However, turning *off* -ffast-math merely restores the
2282 // toolchain default (which may be false).
2283 MathErrno = TC.IsMathErrnoDefault();
2284 AssociativeMath = false;
2285 ReciprocalMath = false;
2286 SignedZeros = true;
2287 TrappingMath = true;
2288 // -fno_fast_math restores default denormal and fpcontract handling
2289 DenormalFPMath = "";
2290 FPContract = "";
2291 break;
2292 }
2293
2294 // If we handled this option claim it
2295 A->claim();
2296 }
2297
2298 if (!HonorINFs)
2299 CmdArgs.push_back("-menable-no-infs");
2300
2301 if (!HonorNaNs)
2302 CmdArgs.push_back("-menable-no-nans");
2303
2304 if (MathErrno)
2305 CmdArgs.push_back("-fmath-errno");
2306
2307 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2308 !TrappingMath)
2309 CmdArgs.push_back("-menable-unsafe-fp-math");
2310
2311 if (!SignedZeros)
2312 CmdArgs.push_back("-fno-signed-zeros");
2313
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002314 if (AssociativeMath && !SignedZeros && !TrappingMath)
2315 CmdArgs.push_back("-mreassociate");
2316
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002317 if (ReciprocalMath)
2318 CmdArgs.push_back("-freciprocal-math");
2319
2320 if (!TrappingMath)
2321 CmdArgs.push_back("-fno-trapping-math");
2322
2323 if (!DenormalFPMath.empty())
2324 CmdArgs.push_back(
2325 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2326
2327 if (!FPContract.empty())
2328 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2329
2330 ParseMRecip(D, Args, CmdArgs);
2331
2332 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2333 // individual features enabled by -ffast-math instead of the option itself as
2334 // that's consistent with gcc's behaviour.
2335 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2336 ReciprocalMath && !SignedZeros && !TrappingMath)
2337 CmdArgs.push_back("-ffast-math");
2338
2339 // Handle __FINITE_MATH_ONLY__ similarly.
2340 if (!HonorINFs && !HonorNaNs)
2341 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002342
2343 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2344 CmdArgs.push_back("-mfpmath");
2345 CmdArgs.push_back(A->getValue());
2346 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002347
2348 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002349 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2350 options::OPT_fstrict_float_cast_overflow, false))
2351 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002352}
2353
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002354static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2355 const llvm::Triple &Triple,
2356 const InputInfo &Input) {
2357 // Enable region store model by default.
2358 CmdArgs.push_back("-analyzer-store=region");
2359
2360 // Treat blocks as analysis entry points.
2361 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2362
Kristof Umannd1a4b062018-11-30 21:24:31 +00002363 // Enable compatilibily mode to avoid analyzer-config related errors.
2364 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
2365
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002366 // Add default argument set.
2367 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2368 CmdArgs.push_back("-analyzer-checker=core");
2369 CmdArgs.push_back("-analyzer-checker=apiModeling");
2370
2371 if (!Triple.isWindowsMSVCEnvironment()) {
2372 CmdArgs.push_back("-analyzer-checker=unix");
2373 } else {
2374 // Enable "unix" checkers that also work on Windows.
2375 CmdArgs.push_back("-analyzer-checker=unix.API");
2376 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2377 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2378 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2379 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2380 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2381 }
2382
2383 // Disable some unix checkers for PS4.
2384 if (Triple.isPS4CPU()) {
2385 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2386 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2387 }
2388
2389 if (Triple.isOSDarwin())
2390 CmdArgs.push_back("-analyzer-checker=osx");
2391
2392 CmdArgs.push_back("-analyzer-checker=deadcode");
2393
2394 if (types::isCXX(Input.getType()))
2395 CmdArgs.push_back("-analyzer-checker=cplusplus");
2396
2397 if (!Triple.isPS4CPU()) {
2398 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2399 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2400 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2401 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2402 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2403 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2404 }
2405
2406 // Default nullability checks.
2407 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2408 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2409 }
2410
2411 // Set the output format. The default is plist, for (lame) historical reasons.
2412 CmdArgs.push_back("-analyzer-output");
2413 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2414 CmdArgs.push_back(A->getValue());
2415 else
2416 CmdArgs.push_back("plist");
2417
2418 // Disable the presentation of standard compiler warnings when using
2419 // --analyze. We only want to show static analyzer diagnostics or frontend
2420 // errors.
2421 CmdArgs.push_back("-w");
2422
2423 // Add -Xanalyzer arguments when running as analyzer.
2424 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2425}
2426
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002427static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002428 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002429 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2430
2431 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2432 // doesn't even have a stack!
2433 if (EffectiveTriple.isNVPTX())
2434 return;
2435
2436 // -stack-protector=0 is default.
2437 unsigned StackProtectorLevel = 0;
2438 unsigned DefaultStackProtectorLevel =
2439 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2440
2441 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2442 options::OPT_fstack_protector_all,
2443 options::OPT_fstack_protector_strong,
2444 options::OPT_fstack_protector)) {
2445 if (A->getOption().matches(options::OPT_fstack_protector))
2446 StackProtectorLevel =
2447 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2448 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2449 StackProtectorLevel = LangOptions::SSPStrong;
2450 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2451 StackProtectorLevel = LangOptions::SSPReq;
2452 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002453 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002454 }
2455
2456 if (StackProtectorLevel) {
2457 CmdArgs.push_back("-stack-protector");
2458 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2459 }
2460
2461 // --param ssp-buffer-size=
2462 for (const Arg *A : Args.filtered(options::OPT__param)) {
2463 StringRef Str(A->getValue());
2464 if (Str.startswith("ssp-buffer-size=")) {
2465 if (StackProtectorLevel) {
2466 CmdArgs.push_back("-stack-protector-buffer-size");
2467 // FIXME: Verify the argument is a valid integer.
2468 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2469 }
2470 A->claim();
2471 }
2472 }
2473}
2474
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002475static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2476 const unsigned ForwardedArguments[] = {
2477 options::OPT_cl_opt_disable,
2478 options::OPT_cl_strict_aliasing,
2479 options::OPT_cl_single_precision_constant,
2480 options::OPT_cl_finite_math_only,
2481 options::OPT_cl_kernel_arg_info,
2482 options::OPT_cl_unsafe_math_optimizations,
2483 options::OPT_cl_fast_relaxed_math,
2484 options::OPT_cl_mad_enable,
2485 options::OPT_cl_no_signed_zeros,
2486 options::OPT_cl_denorms_are_zero,
2487 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002488 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002489 };
2490
2491 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2492 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2493 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2494 }
2495
2496 for (const auto &Arg : ForwardedArguments)
2497 if (const auto *A = Args.getLastArg(Arg))
2498 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2499}
2500
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002501static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2502 ArgStringList &CmdArgs) {
2503 bool ARCMTEnabled = false;
2504 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2505 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2506 options::OPT_ccc_arcmt_modify,
2507 options::OPT_ccc_arcmt_migrate)) {
2508 ARCMTEnabled = true;
2509 switch (A->getOption().getID()) {
2510 default: llvm_unreachable("missed a case");
2511 case options::OPT_ccc_arcmt_check:
2512 CmdArgs.push_back("-arcmt-check");
2513 break;
2514 case options::OPT_ccc_arcmt_modify:
2515 CmdArgs.push_back("-arcmt-modify");
2516 break;
2517 case options::OPT_ccc_arcmt_migrate:
2518 CmdArgs.push_back("-arcmt-migrate");
2519 CmdArgs.push_back("-mt-migrate-directory");
2520 CmdArgs.push_back(A->getValue());
2521
2522 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2523 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2524 break;
2525 }
2526 }
2527 } else {
2528 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2529 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2530 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2531 }
2532
2533 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2534 if (ARCMTEnabled)
2535 D.Diag(diag::err_drv_argument_not_allowed_with)
2536 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2537
2538 CmdArgs.push_back("-mt-migrate-directory");
2539 CmdArgs.push_back(A->getValue());
2540
2541 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2542 options::OPT_objcmt_migrate_subscripting,
2543 options::OPT_objcmt_migrate_property)) {
2544 // None specified, means enable them all.
2545 CmdArgs.push_back("-objcmt-migrate-literals");
2546 CmdArgs.push_back("-objcmt-migrate-subscripting");
2547 CmdArgs.push_back("-objcmt-migrate-property");
2548 } else {
2549 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2550 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2551 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2552 }
2553 } else {
2554 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2555 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2556 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2557 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2558 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2559 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2560 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2561 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2562 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2563 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2564 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2565 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2566 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2567 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2568 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2569 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2570 }
2571}
2572
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002573static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2574 const ArgList &Args, ArgStringList &CmdArgs) {
2575 // -fbuiltin is default unless -mkernel is used.
2576 bool UseBuiltins =
2577 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2578 !Args.hasArg(options::OPT_mkernel));
2579 if (!UseBuiltins)
2580 CmdArgs.push_back("-fno-builtin");
2581
2582 // -ffreestanding implies -fno-builtin.
2583 if (Args.hasArg(options::OPT_ffreestanding))
2584 UseBuiltins = false;
2585
2586 // Process the -fno-builtin-* options.
2587 for (const auto &Arg : Args) {
2588 const Option &O = Arg->getOption();
2589 if (!O.matches(options::OPT_fno_builtin_))
2590 continue;
2591
2592 Arg->claim();
2593
2594 // If -fno-builtin is specified, then there's no need to pass the option to
2595 // the frontend.
2596 if (!UseBuiltins)
2597 continue;
2598
2599 StringRef FuncName = Arg->getValue();
2600 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2601 }
2602
2603 // le32-specific flags:
2604 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2605 // by default.
2606 if (TC.getArch() == llvm::Triple::le32)
2607 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002608}
2609
Adrian Prantl70599032018-02-09 18:43:10 +00002610void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2611 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2612 llvm::sys::path::append(Result, "org.llvm.clang.");
2613 appendUserToPath(Result);
2614 llvm::sys::path::append(Result, "ModuleCache");
2615}
2616
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002617static void RenderModulesOptions(Compilation &C, const Driver &D,
2618 const ArgList &Args, const InputInfo &Input,
2619 const InputInfo &Output,
2620 ArgStringList &CmdArgs, bool &HaveModules) {
2621 // -fmodules enables the use of precompiled modules (off by default).
2622 // Users can pass -fno-cxx-modules to turn off modules support for
2623 // C++/Objective-C++ programs.
2624 bool HaveClangModules = false;
2625 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2626 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2627 options::OPT_fno_cxx_modules, true);
2628 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2629 CmdArgs.push_back("-fmodules");
2630 HaveClangModules = true;
2631 }
2632 }
2633
2634 HaveModules = HaveClangModules;
2635 if (Args.hasArg(options::OPT_fmodules_ts)) {
2636 CmdArgs.push_back("-fmodules-ts");
2637 HaveModules = true;
2638 }
2639
2640 // -fmodule-maps enables implicit reading of module map files. By default,
2641 // this is enabled if we are using Clang's flavor of precompiled modules.
2642 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2643 options::OPT_fno_implicit_module_maps, HaveClangModules))
2644 CmdArgs.push_back("-fimplicit-module-maps");
2645
2646 // -fmodules-decluse checks that modules used are declared so (off by default)
2647 if (Args.hasFlag(options::OPT_fmodules_decluse,
2648 options::OPT_fno_modules_decluse, false))
2649 CmdArgs.push_back("-fmodules-decluse");
2650
2651 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2652 // all #included headers are part of modules.
2653 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2654 options::OPT_fno_modules_strict_decluse, false))
2655 CmdArgs.push_back("-fmodules-strict-decluse");
2656
2657 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002658 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002659 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2660 options::OPT_fno_implicit_modules, HaveClangModules)) {
2661 if (HaveModules)
2662 CmdArgs.push_back("-fno-implicit-modules");
2663 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002664 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002665 // -fmodule-cache-path specifies where our implicitly-built module files
2666 // should be written.
2667 SmallString<128> Path;
2668 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2669 Path = A->getValue();
2670
2671 if (C.isForDiagnostics()) {
2672 // When generating crash reports, we want to emit the modules along with
2673 // the reproduction sources, so we ignore any provided module path.
2674 Path = Output.getFilename();
2675 llvm::sys::path::replace_extension(Path, ".cache");
2676 llvm::sys::path::append(Path, "modules");
2677 } else if (Path.empty()) {
2678 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002679 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002680 }
2681
2682 const char Arg[] = "-fmodules-cache-path=";
2683 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2684 CmdArgs.push_back(Args.MakeArgString(Path));
2685 }
2686
2687 if (HaveModules) {
2688 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2689 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2690 CmdArgs.push_back(Args.MakeArgString(
2691 std::string("-fprebuilt-module-path=") + A->getValue()));
2692 A->claim();
2693 }
2694 }
2695
2696 // -fmodule-name specifies the module that is currently being built (or
2697 // used for header checking by -fmodule-maps).
2698 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2699
2700 // -fmodule-map-file can be used to specify files containing module
2701 // definitions.
2702 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2703
2704 // -fbuiltin-module-map can be used to load the clang
2705 // builtin headers modulemap file.
2706 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2707 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2708 llvm::sys::path::append(BuiltinModuleMap, "include");
2709 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2710 if (llvm::sys::fs::exists(BuiltinModuleMap))
2711 CmdArgs.push_back(
2712 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2713 }
2714
2715 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2716 // names to precompiled module files (the module is loaded only if used).
2717 // The -fmodule-file=<file> form can be used to unconditionally load
2718 // precompiled module files (whether used or not).
2719 if (HaveModules)
2720 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2721 else
2722 Args.ClaimAllArgs(options::OPT_fmodule_file);
2723
2724 // When building modules and generating crashdumps, we need to dump a module
2725 // dependency VFS alongside the output.
2726 if (HaveClangModules && C.isForDiagnostics()) {
2727 SmallString<128> VFSDir(Output.getFilename());
2728 llvm::sys::path::replace_extension(VFSDir, ".cache");
2729 // Add the cache directory as a temp so the crash diagnostics pick it up.
2730 C.addTempFile(Args.MakeArgString(VFSDir));
2731
2732 llvm::sys::path::append(VFSDir, "vfs");
2733 CmdArgs.push_back("-module-dependency-dir");
2734 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2735 }
2736
2737 if (HaveClangModules)
2738 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2739
2740 // Pass through all -fmodules-ignore-macro arguments.
2741 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2742 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2743 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2744
2745 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2746
2747 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2748 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2749 D.Diag(diag::err_drv_argument_not_allowed_with)
2750 << A->getAsString(Args) << "-fbuild-session-timestamp";
2751
2752 llvm::sys::fs::file_status Status;
2753 if (llvm::sys::fs::status(A->getValue(), Status))
2754 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2755 CmdArgs.push_back(
2756 Args.MakeArgString("-fbuild-session-timestamp=" +
2757 Twine((uint64_t)Status.getLastModificationTime()
2758 .time_since_epoch()
2759 .count())));
2760 }
2761
2762 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2763 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2764 options::OPT_fbuild_session_file))
2765 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2766
2767 Args.AddLastArg(CmdArgs,
2768 options::OPT_fmodules_validate_once_per_build_session);
2769 }
2770
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002771 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2772 options::OPT_fno_modules_validate_system_headers,
2773 ImplicitModules))
2774 CmdArgs.push_back("-fmodules-validate-system-headers");
2775
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002776 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2777}
2778
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002779static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2780 ArgStringList &CmdArgs) {
2781 // -fsigned-char is default.
2782 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2783 options::OPT_fno_signed_char,
2784 options::OPT_funsigned_char,
2785 options::OPT_fno_unsigned_char)) {
2786 if (A->getOption().matches(options::OPT_funsigned_char) ||
2787 A->getOption().matches(options::OPT_fno_signed_char)) {
2788 CmdArgs.push_back("-fno-signed-char");
2789 }
2790 } else if (!isSignedCharDefault(T)) {
2791 CmdArgs.push_back("-fno-signed-char");
2792 }
2793
Richard Smith28ddb912018-11-14 21:04:34 +00002794 // The default depends on the language standard.
2795 if (const Arg *A =
2796 Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t))
2797 A->render(Args, CmdArgs);
Richard Smith3a8244d2018-05-01 05:02:45 +00002798
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002799 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2800 options::OPT_fno_short_wchar)) {
2801 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2802 CmdArgs.push_back("-fwchar-type=short");
2803 CmdArgs.push_back("-fno-signed-wchar");
2804 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002805 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002806 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002807 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2808 T.getOS() == llvm::Triple::OpenBSD))
2809 CmdArgs.push_back("-fno-signed-wchar");
2810 else
2811 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002812 }
2813 }
2814}
2815
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002816static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2817 const llvm::Triple &T, const ArgList &Args,
2818 ObjCRuntime &Runtime, bool InferCovariantReturns,
2819 const InputInfo &Input, ArgStringList &CmdArgs) {
2820 const llvm::Triple::ArchType Arch = TC.getArch();
2821
2822 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2823 // is the default. Except for deployment target of 10.5, next runtime is
2824 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2825 if (Runtime.isNonFragile()) {
2826 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2827 options::OPT_fno_objc_legacy_dispatch,
2828 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2829 if (TC.UseObjCMixedDispatch())
2830 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2831 else
2832 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2833 }
2834 }
2835
2836 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2837 // to do Array/Dictionary subscripting by default.
2838 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002839 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2840 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2841
2842 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2843 // NOTE: This logic is duplicated in ToolChains.cpp.
2844 if (isObjCAutoRefCount(Args)) {
2845 TC.CheckObjCARC();
2846
2847 CmdArgs.push_back("-fobjc-arc");
2848
2849 // FIXME: It seems like this entire block, and several around it should be
2850 // wrapped in isObjC, but for now we just use it here as this is where it
2851 // was being used previously.
2852 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2853 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2854 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2855 else
2856 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2857 }
2858
2859 // Allow the user to enable full exceptions code emission.
2860 // We default off for Objective-C, on for Objective-C++.
2861 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2862 options::OPT_fno_objc_arc_exceptions,
2863 /*default=*/types::isCXX(Input.getType())))
2864 CmdArgs.push_back("-fobjc-arc-exceptions");
2865 }
2866
2867 // Silence warning for full exception code emission options when explicitly
2868 // set to use no ARC.
2869 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2870 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2871 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2872 }
2873
Pete Coopere3886802018-12-08 05:13:50 +00002874 // Allow the user to control whether messages can be converted to runtime
2875 // functions.
2876 if (types::isObjC(Input.getType())) {
2877 auto *Arg = Args.getLastArg(
2878 options::OPT_fobjc_convert_messages_to_runtime_calls,
2879 options::OPT_fno_objc_convert_messages_to_runtime_calls);
2880 if (Arg &&
2881 Arg->getOption().matches(
2882 options::OPT_fno_objc_convert_messages_to_runtime_calls))
2883 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2884 }
2885
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002886 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2887 // rewriter.
2888 if (InferCovariantReturns)
2889 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2890
2891 // Pass down -fobjc-weak or -fno-objc-weak if present.
2892 if (types::isObjC(Input.getType())) {
2893 auto WeakArg =
2894 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2895 if (!WeakArg) {
2896 // nothing to do
2897 } else if (!Runtime.allowsWeak()) {
2898 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2899 D.Diag(diag::err_objc_weak_unsupported);
2900 } else {
2901 WeakArg->render(Args, CmdArgs);
2902 }
2903 }
2904}
2905
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002906static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2907 ArgStringList &CmdArgs) {
2908 bool CaretDefault = true;
2909 bool ColumnDefault = true;
2910
2911 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2912 options::OPT__SLASH_diagnostics_column,
2913 options::OPT__SLASH_diagnostics_caret)) {
2914 switch (A->getOption().getID()) {
2915 case options::OPT__SLASH_diagnostics_caret:
2916 CaretDefault = true;
2917 ColumnDefault = true;
2918 break;
2919 case options::OPT__SLASH_diagnostics_column:
2920 CaretDefault = false;
2921 ColumnDefault = true;
2922 break;
2923 case options::OPT__SLASH_diagnostics_classic:
2924 CaretDefault = false;
2925 ColumnDefault = false;
2926 break;
2927 }
2928 }
2929
2930 // -fcaret-diagnostics is default.
2931 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2932 options::OPT_fno_caret_diagnostics, CaretDefault))
2933 CmdArgs.push_back("-fno-caret-diagnostics");
2934
2935 // -fdiagnostics-fixit-info is default, only pass non-default.
2936 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2937 options::OPT_fno_diagnostics_fixit_info))
2938 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2939
2940 // Enable -fdiagnostics-show-option by default.
2941 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2942 options::OPT_fno_diagnostics_show_option))
2943 CmdArgs.push_back("-fdiagnostics-show-option");
2944
2945 if (const Arg *A =
2946 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2947 CmdArgs.push_back("-fdiagnostics-show-category");
2948 CmdArgs.push_back(A->getValue());
2949 }
2950
2951 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2952 options::OPT_fno_diagnostics_show_hotness, false))
2953 CmdArgs.push_back("-fdiagnostics-show-hotness");
2954
2955 if (const Arg *A =
2956 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2957 std::string Opt =
2958 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2959 CmdArgs.push_back(Args.MakeArgString(Opt));
2960 }
2961
2962 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2963 CmdArgs.push_back("-fdiagnostics-format");
2964 CmdArgs.push_back(A->getValue());
2965 }
2966
2967 if (const Arg *A = Args.getLastArg(
2968 options::OPT_fdiagnostics_show_note_include_stack,
2969 options::OPT_fno_diagnostics_show_note_include_stack)) {
2970 const Option &O = A->getOption();
2971 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2972 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2973 else
2974 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2975 }
2976
2977 // Color diagnostics are parsed by the driver directly from argv and later
2978 // re-parsed to construct this job; claim any possible color diagnostic here
2979 // to avoid warn_drv_unused_argument and diagnose bad
2980 // OPT_fdiagnostics_color_EQ values.
2981 for (const Arg *A : Args) {
2982 const Option &O = A->getOption();
2983 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2984 !O.matches(options::OPT_fdiagnostics_color) &&
2985 !O.matches(options::OPT_fno_color_diagnostics) &&
2986 !O.matches(options::OPT_fno_diagnostics_color) &&
2987 !O.matches(options::OPT_fdiagnostics_color_EQ))
2988 continue;
2989
2990 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2991 StringRef Value(A->getValue());
2992 if (Value != "always" && Value != "never" && Value != "auto")
2993 D.Diag(diag::err_drv_clang_unsupported)
2994 << ("-fdiagnostics-color=" + Value).str();
2995 }
2996 A->claim();
2997 }
2998
2999 if (D.getDiags().getDiagnosticOptions().ShowColors)
3000 CmdArgs.push_back("-fcolor-diagnostics");
3001
3002 if (Args.hasArg(options::OPT_fansi_escape_codes))
3003 CmdArgs.push_back("-fansi-escape-codes");
3004
3005 if (!Args.hasFlag(options::OPT_fshow_source_location,
3006 options::OPT_fno_show_source_location))
3007 CmdArgs.push_back("-fno-show-source-location");
3008
3009 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3010 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3011
3012 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3013 ColumnDefault))
3014 CmdArgs.push_back("-fno-show-column");
3015
3016 if (!Args.hasFlag(options::OPT_fspell_checking,
3017 options::OPT_fno_spell_checking))
3018 CmdArgs.push_back("-fno-spell-checking");
3019}
3020
George Rimar91829ee2018-11-14 09:22:16 +00003021enum class DwarfFissionKind { None, Split, Single };
3022
3023static DwarfFissionKind getDebugFissionKind(const Driver &D,
3024 const ArgList &Args, Arg *&Arg) {
3025 Arg =
3026 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3027 if (!Arg)
3028 return DwarfFissionKind::None;
3029
3030 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3031 return DwarfFissionKind::Split;
3032
3033 StringRef Value = Arg->getValue();
3034 if (Value == "split")
3035 return DwarfFissionKind::Split;
3036 if (Value == "single")
3037 return DwarfFissionKind::Single;
3038
3039 D.Diag(diag::err_drv_unsupported_option_argument)
3040 << Arg->getOption().getName() << Arg->getValue();
3041 return DwarfFissionKind::None;
3042}
3043
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003044static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3045 const llvm::Triple &T, const ArgList &Args,
3046 bool EmitCodeView, bool IsWindowsMSVC,
3047 ArgStringList &CmdArgs,
3048 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003049 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003050 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003051 options::OPT_fno_debug_info_for_profiling, false) &&
3052 checkDebugInfoOption(
3053 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003054 CmdArgs.push_back("-fdebug-info-for-profiling");
3055
3056 // The 'g' groups options involve a somewhat intricate sequence of decisions
3057 // about what to pass from the driver to the frontend, but by the time they
3058 // reach cc1 they've been factored into three well-defined orthogonal choices:
3059 // * what level of debug info to generate
3060 // * what dwarf version to write
3061 // * what debugger tuning to use
3062 // This avoids having to monkey around further in cc1 other than to disable
3063 // codeview if not running in a Windows environment. Perhaps even that
3064 // decision should be made in the driver as well though.
3065 unsigned DWARFVersion = 0;
3066 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3067
3068 bool SplitDWARFInlining =
3069 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3070 options::OPT_fno_split_dwarf_inlining, true);
3071
3072 Args.ClaimAllArgs(options::OPT_g_Group);
3073
George Rimar91829ee2018-11-14 09:22:16 +00003074 Arg* SplitDWARFArg;
3075 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003076
George Rimar91829ee2018-11-14 09:22:16 +00003077 if (DwarfFission != DwarfFissionKind::None &&
3078 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3079 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003080 SplitDWARFInlining = false;
3081 }
3082
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003083 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003084 if (checkDebugInfoOption(A, Args, D, TC)) {
3085 // If the last option explicitly specified a debug-info level, use it.
3086 if (A->getOption().matches(options::OPT_gN_Group)) {
3087 DebugInfoKind = DebugLevelToInfoKind(*A);
3088 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
3089 // But -gsplit-dwarf is not a g_group option, hence we have to check the
3090 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
3091 // This gets a bit more complicated if you've disabled inline info in
3092 // the skeleton CUs (SplitDWARFInlining) - then there's value in
3093 // composing split-dwarf and line-tables-only, so let those compose
3094 // naturally in that case. And if you just turned off debug info,
3095 // (-gsplit-dwarf -g0) - do that.
George Rimar91829ee2018-11-14 09:22:16 +00003096 if (DwarfFission != DwarfFissionKind::None) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003097 if (A->getIndex() > SplitDWARFArg->getIndex()) {
3098 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003099 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003100 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3101 SplitDWARFInlining))
George Rimar91829ee2018-11-14 09:22:16 +00003102 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003103 } else if (SplitDWARFInlining)
3104 DebugInfoKind = codegenoptions::NoDebugInfo;
3105 }
3106 } else {
3107 // For any other 'g' option, use Limited.
3108 DebugInfoKind = codegenoptions::LimitedDebugInfo;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003109 }
3110 } else {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003111 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3112 }
3113 }
3114
3115 // If a debugger tuning argument appeared, remember it.
3116 if (const Arg *A =
3117 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003118 if (checkDebugInfoOption(A, Args, D, TC)) {
3119 if (A->getOption().matches(options::OPT_glldb))
3120 DebuggerTuning = llvm::DebuggerKind::LLDB;
3121 else if (A->getOption().matches(options::OPT_gsce))
3122 DebuggerTuning = llvm::DebuggerKind::SCE;
3123 else
3124 DebuggerTuning = llvm::DebuggerKind::GDB;
3125 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003126 }
3127
3128 // If a -gdwarf argument appeared, remember it.
3129 if (const Arg *A =
3130 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3131 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003132 if (checkDebugInfoOption(A, Args, D, TC))
3133 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003134
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003135 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3136 if (checkDebugInfoOption(A, Args, D, TC))
3137 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003138 }
3139
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003140 // If the user asked for debug info but did not explicitly specify -gcodeview
3141 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003142 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003143 DebugInfoKind != codegenoptions::NoDebugInfo) {
3144 switch (TC.getDefaultDebugFormat()) {
3145 case codegenoptions::DIF_CodeView:
3146 EmitCodeView = true;
3147 break;
3148 case codegenoptions::DIF_DWARF:
3149 DWARFVersion = TC.GetDefaultDwarfVersion();
3150 break;
3151 }
3152 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003153
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003154 // -gline-directives-only supported only for the DWARF debug info.
3155 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3156 DebugInfoKind = codegenoptions::NoDebugInfo;
3157
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003158 // We ignore flag -gstrict-dwarf for now.
3159 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3160 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3161
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003162 // Column info is included by default for everything except SCE and
3163 // CodeView. Clang doesn't track end columns, just starting columns, which,
3164 // in theory, is fine for CodeView (and PDB). In practice, however, the
3165 // Microsoft debuggers don't handle missing end columns well, so it's better
3166 // not to include any column info.
3167 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3168 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003169 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003170 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003171 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003172 CmdArgs.push_back("-dwarf-column-info");
3173
3174 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003175 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003176 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3177 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003178 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3179 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003180 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3181 CmdArgs.push_back("-dwarf-ext-refs");
3182 CmdArgs.push_back("-fmodule-format=obj");
3183 }
3184 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003185
3186 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3187 // splitting and extraction.
Petr Hosekd3265352018-10-15 21:30:32 +00003188 // FIXME: Currently only works on Linux and Fuchsia.
3189 if (T.isOSLinux() || T.isOSFuchsia()) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003190 if (!SplitDWARFInlining)
3191 CmdArgs.push_back("-fno-split-dwarf-inlining");
3192
George Rimar91829ee2018-11-14 09:22:16 +00003193 if (DwarfFission != DwarfFissionKind::None) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003194 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3195 DebugInfoKind = codegenoptions::LimitedDebugInfo;
George Rimar91829ee2018-11-14 09:22:16 +00003196
3197 if (DwarfFission == DwarfFissionKind::Single)
3198 CmdArgs.push_back("-enable-split-dwarf=single");
3199 else
3200 CmdArgs.push_back("-enable-split-dwarf");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003201 }
3202 }
3203
3204 // After we've dealt with all combinations of things that could
3205 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3206 // figure out if we need to "upgrade" it to standalone debug info.
3207 // We parse these two '-f' options whether or not they will be used,
3208 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3209 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3210 options::OPT_fno_standalone_debug,
3211 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003212 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3213 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003214 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3215 DebugInfoKind = codegenoptions::FullDebugInfo;
3216
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003217 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3218 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003219 // Source embedding is a vendor extension to DWARF v5. By now we have
3220 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003221 // fallen back to the target default, so if this is still not at least 5
3222 // we emit an error.
3223 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003224 if (DWARFVersion < 5)
3225 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003226 << A->getAsString(Args) << "-gdwarf-5";
3227 else if (checkDebugInfoOption(A, Args, D, TC))
3228 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003229 }
3230
Reid Kleckner75557712018-11-16 18:47:41 +00003231 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003232 CmdArgs.push_back("-gcodeview");
3233
Reid Kleckner75557712018-11-16 18:47:41 +00003234 // Emit codeview type hashes if requested.
3235 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3236 options::OPT_gno_codeview_ghash, false)) {
3237 CmdArgs.push_back("-gcodeview-ghash");
3238 }
3239 }
3240
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003241 // Adjust the debug info kind for the given toolchain.
3242 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3243
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003244 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3245 DebuggerTuning);
3246
3247 // -fdebug-macro turns on macro debug info generation.
3248 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3249 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003250 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3251 D, TC))
3252 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003253
3254 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003255 const auto *PubnamesArg =
3256 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3257 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003258 if (DwarfFission != DwarfFissionKind::None ||
3259 DebuggerTuning == llvm::DebuggerKind::LLDB ||
David Blaikie65864522018-08-20 20:14:08 +00003260 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3261 if (!PubnamesArg ||
3262 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3263 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3264 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3265 options::OPT_gpubnames)
3266 ? "-gpubnames"
3267 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003268
David Blaikie27692de2018-11-13 20:08:13 +00003269 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3270 options::OPT_fno_debug_ranges_base_address, false)) {
3271 CmdArgs.push_back("-fdebug-ranges-base-address");
3272 }
3273
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003274 // -gdwarf-aranges turns on the emission of the aranges section in the
3275 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003276 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003277 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3278 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3279 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3280 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003281 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003282 CmdArgs.push_back("-generate-arange-section");
3283 }
3284
3285 if (Args.hasFlag(options::OPT_fdebug_types_section,
3286 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003287 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003288 D.Diag(diag::err_drv_unsupported_opt_for_target)
3289 << Args.getLastArg(options::OPT_fdebug_types_section)
3290 ->getAsString(Args)
3291 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003292 } else if (checkDebugInfoOption(
3293 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3294 TC)) {
3295 CmdArgs.push_back("-mllvm");
3296 CmdArgs.push_back("-generate-type-units");
3297 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003298 }
3299
Paul Robinson1787f812017-09-28 18:37:02 +00003300 // Decide how to render forward declarations of template instantiations.
3301 // SCE wants full descriptions, others just get them in the name.
3302 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3303 CmdArgs.push_back("-debug-forward-template-params");
3304
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003305 // Do we need to explicitly import anonymous namespaces into the parent
3306 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003307 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3308 CmdArgs.push_back("-dwarf-explicit-import");
3309
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003310 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003311}
3312
David L. Jonesf561aba2017-03-08 01:02:16 +00003313void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3314 const InputInfo &Output, const InputInfoList &Inputs,
3315 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003316 const auto &TC = getToolChain();
3317 const llvm::Triple &RawTriple = TC.getTriple();
3318 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003319 const std::string &TripleStr = Triple.getTriple();
3320
3321 bool KernelOrKext =
3322 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003323 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003324 ArgStringList CmdArgs;
3325
3326 // Check number of inputs for sanity. We need at least one input.
3327 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003328 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003329 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003330 // second input. Module precompilation accepts a list of header files to
3331 // include as part of the module. All other jobs are expected to have exactly
3332 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003333 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003334 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003335 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003336 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3337
3338 // A header module compilation doesn't have a main input file, so invent a
3339 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003340 const char *ModuleName = [&]{
3341 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3342 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3343 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003344 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003345
3346 const InputInfo &Input =
3347 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3348
3349 InputInfoList ModuleHeaderInputs;
3350 const InputInfo *CudaDeviceInput = nullptr;
3351 const InputInfo *OpenMPDeviceInput = nullptr;
3352 for (const InputInfo &I : Inputs) {
3353 if (&I == &Input) {
3354 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003355 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003356 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003357 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003358 if (I.getType() != Expected) {
3359 D.Diag(diag::err_drv_module_header_wrong_kind)
3360 << I.getFilename() << types::getTypeName(I.getType())
3361 << types::getTypeName(Expected);
3362 }
3363 ModuleHeaderInputs.push_back(I);
3364 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3365 CudaDeviceInput = &I;
3366 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3367 OpenMPDeviceInput = &I;
3368 } else {
3369 llvm_unreachable("unexpectedly given multiple inputs");
3370 }
3371 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003372
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003373 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003374 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3375 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3376 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003377 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003378
Yaxun Liu398612b2018-05-08 21:02:12 +00003379 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3380 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3381 // Windows), we need to pass Windows-specific flags to cc1.
3382 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003383 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3384 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3385 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3386 }
3387
3388 // C++ is not supported for IAMCU.
3389 if (IsIAMCU && types::isCXX(Input.getType()))
3390 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3391
3392 // Invoke ourselves in -cc1 mode.
3393 //
3394 // FIXME: Implement custom jobs for internal actions.
3395 CmdArgs.push_back("-cc1");
3396
3397 // Add the "effective" target triple.
3398 CmdArgs.push_back("-triple");
3399 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3400
3401 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3402 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3403 Args.ClaimAllArgs(options::OPT_MJ);
3404 }
3405
Yaxun Liu398612b2018-05-08 21:02:12 +00003406 if (IsCuda || IsHIP) {
3407 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3408 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003409 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003410 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3411 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003412 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3413 ->getTriple()
3414 .normalize();
3415 else
Yaxun Liu398612b2018-05-08 21:02:12 +00003416 NormalizedTriple =
3417 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3418 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3419 ->getTriple()
3420 .normalize();
David L. Jonesf561aba2017-03-08 01:02:16 +00003421
3422 CmdArgs.push_back("-aux-triple");
3423 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3424 }
3425
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003426 if (IsOpenMPDevice) {
3427 // We have to pass the triple of the host if compiling for an OpenMP device.
3428 std::string NormalizedTriple =
3429 C.getSingleOffloadToolChain<Action::OFK_Host>()
3430 ->getTriple()
3431 .normalize();
3432 CmdArgs.push_back("-aux-triple");
3433 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3434 }
3435
David L. Jonesf561aba2017-03-08 01:02:16 +00003436 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3437 Triple.getArch() == llvm::Triple::thumb)) {
3438 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3439 unsigned Version;
3440 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3441 if (Version < 7)
3442 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3443 << TripleStr;
3444 }
3445
3446 // Push all default warning arguments that are specific to
3447 // the given target. These come before user provided warning options
3448 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003449 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003450
3451 // Select the appropriate action.
3452 RewriteKind rewriteKind = RK_None;
3453
3454 if (isa<AnalyzeJobAction>(JA)) {
3455 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3456 CmdArgs.push_back("-analyze");
3457 } else if (isa<MigrateJobAction>(JA)) {
3458 CmdArgs.push_back("-migrate");
3459 } else if (isa<PreprocessJobAction>(JA)) {
3460 if (Output.getType() == types::TY_Dependencies)
3461 CmdArgs.push_back("-Eonly");
3462 else {
3463 CmdArgs.push_back("-E");
3464 if (Args.hasArg(options::OPT_rewrite_objc) &&
3465 !Args.hasArg(options::OPT_g_Group))
3466 CmdArgs.push_back("-P");
3467 }
3468 } else if (isa<AssembleJobAction>(JA)) {
3469 CmdArgs.push_back("-emit-obj");
3470
3471 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3472
3473 // Also ignore explicit -force_cpusubtype_ALL option.
3474 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3475 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003476 if (JA.getType() == types::TY_Nothing)
3477 CmdArgs.push_back("-fsyntax-only");
3478 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003479 CmdArgs.push_back(IsHeaderModulePrecompile
3480 ? "-emit-header-module"
3481 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003482 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003483 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003484 } else if (isa<VerifyPCHJobAction>(JA)) {
3485 CmdArgs.push_back("-verify-pch");
3486 } else {
3487 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3488 "Invalid action for clang tool.");
3489 if (JA.getType() == types::TY_Nothing) {
3490 CmdArgs.push_back("-fsyntax-only");
3491 } else if (JA.getType() == types::TY_LLVM_IR ||
3492 JA.getType() == types::TY_LTO_IR) {
3493 CmdArgs.push_back("-emit-llvm");
3494 } else if (JA.getType() == types::TY_LLVM_BC ||
3495 JA.getType() == types::TY_LTO_BC) {
3496 CmdArgs.push_back("-emit-llvm-bc");
3497 } else if (JA.getType() == types::TY_PP_Asm) {
3498 CmdArgs.push_back("-S");
3499 } else if (JA.getType() == types::TY_AST) {
3500 CmdArgs.push_back("-emit-pch");
3501 } else if (JA.getType() == types::TY_ModuleFile) {
3502 CmdArgs.push_back("-module-file-info");
3503 } else if (JA.getType() == types::TY_RewrittenObjC) {
3504 CmdArgs.push_back("-rewrite-objc");
3505 rewriteKind = RK_NonFragile;
3506 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3507 CmdArgs.push_back("-rewrite-objc");
3508 rewriteKind = RK_Fragile;
3509 } else {
3510 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3511 }
3512
3513 // Preserve use-list order by default when emitting bitcode, so that
3514 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3515 // same result as running passes here. For LTO, we don't need to preserve
3516 // the use-list order, since serialization to bitcode is part of the flow.
3517 if (JA.getType() == types::TY_LLVM_BC)
3518 CmdArgs.push_back("-emit-llvm-uselists");
3519
Artem Belevichecb178b2018-03-21 22:22:59 +00003520 // Device-side jobs do not support LTO.
3521 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3522 JA.isDeviceOffloading(Action::OFK_Host));
3523
3524 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003525 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3526
Paul Robinsond23f2a82017-07-13 21:25:47 +00003527 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3528 // does not support LTO unit features (CFI, whole program vtable opt)
3529 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003530 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003531 D.getLTOMode() == LTOK_Full)
3532 CmdArgs.push_back("-flto-unit");
3533 }
3534 }
3535
3536 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3537 if (!types::isLLVMIR(Input.getType()))
3538 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3539 << "-x ir";
3540 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3541 }
3542
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003543 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003544 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3545
David L. Jonesf561aba2017-03-08 01:02:16 +00003546 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003547 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003548 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3549 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3550 // Add flags implied by -fembed-bitcode.
3551 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3552 // Disable all llvm IR level optimizations.
3553 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003554
3555 // reject options that shouldn't be supported in bitcode
3556 // also reject kernel/kext
3557 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3558 options::OPT_mkernel,
3559 options::OPT_fapple_kext,
3560 options::OPT_ffunction_sections,
3561 options::OPT_fno_function_sections,
3562 options::OPT_fdata_sections,
3563 options::OPT_fno_data_sections,
3564 options::OPT_funique_section_names,
3565 options::OPT_fno_unique_section_names,
3566 options::OPT_mrestrict_it,
3567 options::OPT_mno_restrict_it,
3568 options::OPT_mstackrealign,
3569 options::OPT_mno_stackrealign,
3570 options::OPT_mstack_alignment,
3571 options::OPT_mcmodel_EQ,
3572 options::OPT_mlong_calls,
3573 options::OPT_mno_long_calls,
3574 options::OPT_ggnu_pubnames,
3575 options::OPT_gdwarf_aranges,
3576 options::OPT_fdebug_types_section,
3577 options::OPT_fno_debug_types_section,
3578 options::OPT_fdwarf_directory_asm,
3579 options::OPT_fno_dwarf_directory_asm,
3580 options::OPT_mrelax_all,
3581 options::OPT_mno_relax_all,
3582 options::OPT_ftrap_function_EQ,
3583 options::OPT_ffixed_r9,
3584 options::OPT_mfix_cortex_a53_835769,
3585 options::OPT_mno_fix_cortex_a53_835769,
3586 options::OPT_ffixed_x18,
3587 options::OPT_mglobal_merge,
3588 options::OPT_mno_global_merge,
3589 options::OPT_mred_zone,
3590 options::OPT_mno_red_zone,
3591 options::OPT_Wa_COMMA,
3592 options::OPT_Xassembler,
3593 options::OPT_mllvm,
3594 };
3595 for (const auto &A : Args)
3596 if (std::find(std::begin(kBitcodeOptionBlacklist),
3597 std::end(kBitcodeOptionBlacklist),
3598 A->getOption().getID()) !=
3599 std::end(kBitcodeOptionBlacklist))
3600 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3601
3602 // Render the CodeGen options that need to be passed.
3603 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3604 options::OPT_fno_optimize_sibling_calls))
3605 CmdArgs.push_back("-mdisable-tail-calls");
3606
3607 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3608 CmdArgs);
3609
3610 // Render ABI arguments
3611 switch (TC.getArch()) {
3612 default: break;
3613 case llvm::Triple::arm:
3614 case llvm::Triple::armeb:
3615 case llvm::Triple::thumbeb:
3616 RenderARMABI(Triple, Args, CmdArgs);
3617 break;
3618 case llvm::Triple::aarch64:
3619 case llvm::Triple::aarch64_be:
3620 RenderAArch64ABI(Triple, Args, CmdArgs);
3621 break;
3622 }
3623
3624 // Optimization level for CodeGen.
3625 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3626 if (A->getOption().matches(options::OPT_O4)) {
3627 CmdArgs.push_back("-O3");
3628 D.Diag(diag::warn_O4_is_O3);
3629 } else {
3630 A->render(Args, CmdArgs);
3631 }
3632 }
3633
3634 // Input/Output file.
3635 if (Output.getType() == types::TY_Dependencies) {
3636 // Handled with other dependency code.
3637 } else if (Output.isFilename()) {
3638 CmdArgs.push_back("-o");
3639 CmdArgs.push_back(Output.getFilename());
3640 } else {
3641 assert(Output.isNothing() && "Input output.");
3642 }
3643
3644 for (const auto &II : Inputs) {
3645 addDashXForInput(Args, II, CmdArgs);
3646 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003647 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003648 else
3649 II.getInputArg().renderAsInput(Args, CmdArgs);
3650 }
3651
3652 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3653 CmdArgs, Inputs));
3654 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003655 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003656
David L. Jonesf561aba2017-03-08 01:02:16 +00003657 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3658 CmdArgs.push_back("-fembed-bitcode=marker");
3659
3660 // We normally speed up the clang process a bit by skipping destructors at
3661 // exit, but when we're generating diagnostics we can rely on some of the
3662 // cleanup.
3663 if (!C.isForDiagnostics())
3664 CmdArgs.push_back("-disable-free");
3665
David L. Jonesf561aba2017-03-08 01:02:16 +00003666#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003667 const bool IsAssertBuild = false;
3668#else
3669 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003670#endif
3671
Eric Fiselier123c7492018-02-07 18:36:51 +00003672 // Disable the verification pass in -asserts builds.
3673 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003674 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003675
3676 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003677 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3678 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003679 CmdArgs.push_back("-discard-value-names");
3680
David L. Jonesf561aba2017-03-08 01:02:16 +00003681 // Set the main file name, so that debug info works even with
3682 // -save-temps.
3683 CmdArgs.push_back("-main-file-name");
3684 CmdArgs.push_back(getBaseInputName(Args, Input));
3685
3686 // Some flags which affect the language (via preprocessor
3687 // defines).
3688 if (Args.hasArg(options::OPT_static))
3689 CmdArgs.push_back("-static-define");
3690
Martin Storsjo434ef832018-08-06 19:48:44 +00003691 if (Args.hasArg(options::OPT_municode))
3692 CmdArgs.push_back("-DUNICODE");
3693
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003694 if (isa<AnalyzeJobAction>(JA))
3695 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003696
3697 CheckCodeGenerationOptions(D, Args);
3698
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003699 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003700 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3701 if (FunctionAlignment) {
3702 CmdArgs.push_back("-function-alignment");
3703 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3704 }
3705
David L. Jonesf561aba2017-03-08 01:02:16 +00003706 llvm::Reloc::Model RelocationModel;
3707 unsigned PICLevel;
3708 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003709 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003710
3711 const char *RMName = RelocationModelName(RelocationModel);
3712
3713 if ((RelocationModel == llvm::Reloc::ROPI ||
3714 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3715 types::isCXX(Input.getType()) &&
3716 !Args.hasArg(options::OPT_fallow_unsupported))
3717 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3718
3719 if (RMName) {
3720 CmdArgs.push_back("-mrelocation-model");
3721 CmdArgs.push_back(RMName);
3722 }
3723 if (PICLevel > 0) {
3724 CmdArgs.push_back("-pic-level");
3725 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3726 if (IsPIE)
3727 CmdArgs.push_back("-pic-is-pie");
3728 }
3729
3730 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3731 CmdArgs.push_back("-meabi");
3732 CmdArgs.push_back(A->getValue());
3733 }
3734
3735 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003736 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003737 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003738 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3739 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003740 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003741 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003742 else
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003743 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003744
3745 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3746
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003747 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3748 options::OPT_fno_merge_all_constants, false))
3749 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003750
Manoj Guptada08f6a2018-07-19 00:44:52 +00003751 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3752 options::OPT_fdelete_null_pointer_checks, false))
3753 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3754
David L. Jonesf561aba2017-03-08 01:02:16 +00003755 // LLVM Code Generator Options.
3756
3757 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3758 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3759 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3760 options::OPT_frewrite_map_file_EQ)) {
3761 StringRef Map = A->getValue();
3762 if (!llvm::sys::fs::exists(Map)) {
3763 D.Diag(diag::err_drv_no_such_file) << Map;
3764 } else {
3765 CmdArgs.push_back("-frewrite-map-file");
3766 CmdArgs.push_back(A->getValue());
3767 A->claim();
3768 }
3769 }
3770 }
3771
3772 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3773 StringRef v = A->getValue();
3774 CmdArgs.push_back("-mllvm");
3775 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3776 A->claim();
3777 }
3778
3779 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3780 true))
3781 CmdArgs.push_back("-fno-jump-tables");
3782
Dehao Chen5e97f232017-08-24 21:37:33 +00003783 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3784 options::OPT_fno_profile_sample_accurate, false))
3785 CmdArgs.push_back("-fprofile-sample-accurate");
3786
David L. Jonesf561aba2017-03-08 01:02:16 +00003787 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3788 options::OPT_fno_preserve_as_comments, true))
3789 CmdArgs.push_back("-fno-preserve-as-comments");
3790
3791 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3792 CmdArgs.push_back("-mregparm");
3793 CmdArgs.push_back(A->getValue());
3794 }
3795
3796 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3797 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003798 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003799 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003800 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003801 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3802 CmdArgs.push_back("-fpcc-struct-return");
3803 } else {
3804 assert(A->getOption().matches(options::OPT_freg_struct_return));
3805 CmdArgs.push_back("-freg-struct-return");
3806 }
3807 }
3808
3809 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3810 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3811
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003812 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003813 CmdArgs.push_back("-mdisable-fp-elim");
3814 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3815 options::OPT_fno_zero_initialized_in_bss))
3816 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3817
3818 bool OFastEnabled = isOptimizationLevelFast(Args);
3819 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3820 // enabled. This alias option is being used to simplify the hasFlag logic.
3821 OptSpecifier StrictAliasingAliasOption =
3822 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3823 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3824 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003825 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003826 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3827 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3828 CmdArgs.push_back("-relaxed-aliasing");
3829 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3830 options::OPT_fno_struct_path_tbaa))
3831 CmdArgs.push_back("-no-struct-path-tbaa");
3832 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3833 false))
3834 CmdArgs.push_back("-fstrict-enums");
3835 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3836 true))
3837 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003838 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3839 options::OPT_fno_allow_editor_placeholders, false))
3840 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003841 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3842 options::OPT_fno_strict_vtable_pointers,
3843 false))
3844 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003845 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3846 options::OPT_fno_force_emit_vtables,
3847 false))
3848 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003849 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3850 options::OPT_fno_optimize_sibling_calls))
3851 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003852 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003853 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003854 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003855
Wei Mi9b3d6272017-10-16 16:50:27 +00003856 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3857 options::OPT_fno_fine_grained_bitfield_accesses);
3858
David L. Jonesf561aba2017-03-08 01:02:16 +00003859 // Handle segmented stacks.
3860 if (Args.hasArg(options::OPT_fsplit_stack))
3861 CmdArgs.push_back("-split-stacks");
3862
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003863 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003864
3865 // Decide whether to use verbose asm. Verbose assembly is the default on
3866 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003867 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00003868 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3869 IsIntegratedAssemblerDefault) ||
3870 Args.hasArg(options::OPT_dA))
3871 CmdArgs.push_back("-masm-verbose");
3872
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003873 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00003874 CmdArgs.push_back("-no-integrated-as");
3875
3876 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3877 CmdArgs.push_back("-mdebug-pass");
3878 CmdArgs.push_back("Structure");
3879 }
3880 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3881 CmdArgs.push_back("-mdebug-pass");
3882 CmdArgs.push_back("Arguments");
3883 }
3884
3885 // Enable -mconstructor-aliases except on darwin, where we have to work around
3886 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3887 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003888 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003889 CmdArgs.push_back("-mconstructor-aliases");
3890
3891 // Darwin's kernel doesn't support guard variables; just die if we
3892 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003893 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003894 CmdArgs.push_back("-fforbid-guard-variables");
3895
3896 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3897 false)) {
3898 CmdArgs.push_back("-mms-bitfields");
3899 }
3900
3901 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3902 options::OPT_mno_pie_copy_relocations,
3903 false)) {
3904 CmdArgs.push_back("-mpie-copy-relocations");
3905 }
3906
Sriraman Tallam5c651482017-11-07 19:37:51 +00003907 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3908 CmdArgs.push_back("-fno-plt");
3909 }
3910
Vedant Kumardf502592017-09-12 22:51:53 +00003911 // -fhosted is default.
3912 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3913 // use Freestanding.
3914 bool Freestanding =
3915 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3916 KernelOrKext;
3917 if (Freestanding)
3918 CmdArgs.push_back("-ffreestanding");
3919
David L. Jonesf561aba2017-03-08 01:02:16 +00003920 // This is a coarse approximation of what llvm-gcc actually does, both
3921 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3922 // complicated ways.
3923 bool AsynchronousUnwindTables =
3924 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3925 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003926 (TC.IsUnwindTablesDefault(Args) ||
3927 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003928 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003929 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3930 AsynchronousUnwindTables))
3931 CmdArgs.push_back("-munwind-tables");
3932
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003933 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003934
David L. Jonesf561aba2017-03-08 01:02:16 +00003935 // FIXME: Handle -mtune=.
3936 (void)Args.hasArg(options::OPT_mtune_EQ);
3937
3938 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3939 CmdArgs.push_back("-mcode-model");
3940 CmdArgs.push_back(A->getValue());
3941 }
3942
3943 // Add the target cpu
3944 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3945 if (!CPU.empty()) {
3946 CmdArgs.push_back("-target-cpu");
3947 CmdArgs.push_back(Args.MakeArgString(CPU));
3948 }
3949
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003950 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003951
David L. Jonesf561aba2017-03-08 01:02:16 +00003952 // These two are potentially updated by AddClangCLArgs.
3953 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3954 bool EmitCodeView = false;
3955
3956 // Add clang-cl arguments.
3957 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003958 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003959 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
3960
George Rimar91829ee2018-11-14 09:22:16 +00003961 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003962 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00003963 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003964
3965 // Add the split debug info name to the command lines here so we
3966 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00003967 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Petr Hosekd3265352018-10-15 21:30:32 +00003968 (RawTriple.isOSLinux() || RawTriple.isOSFuchsia()) &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003969 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3970 isa<BackendJobAction>(JA));
3971 const char *SplitDWARFOut;
3972 if (SplitDWARF) {
3973 CmdArgs.push_back("-split-dwarf-file");
George Rimarab090332018-12-05 11:09:10 +00003974 SplitDWARFOut = SplitDebugName(Args, Output);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003975 CmdArgs.push_back(SplitDWARFOut);
3976 }
3977
David L. Jonesf561aba2017-03-08 01:02:16 +00003978 // Pass the linker version in use.
3979 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3980 CmdArgs.push_back("-target-linker-version");
3981 CmdArgs.push_back(A->getValue());
3982 }
3983
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003984 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003985 CmdArgs.push_back("-momit-leaf-frame-pointer");
3986
3987 // Explicitly error on some things we know we don't support and can't just
3988 // ignore.
3989 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3990 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003991 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003992 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003993 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3994 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3995 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3996 << Unsupported->getOption().getName();
3997 }
Eric Christopher758aad72017-03-21 22:06:18 +00003998 // The faltivec option has been superseded by the maltivec option.
3999 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4000 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4001 << Unsupported->getOption().getName()
4002 << "please use -maltivec and include altivec.h explicitly";
4003 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4004 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4005 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004006 }
4007
4008 Args.AddAllArgs(CmdArgs, options::OPT_v);
4009 Args.AddLastArg(CmdArgs, options::OPT_H);
4010 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4011 CmdArgs.push_back("-header-include-file");
4012 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4013 : "-");
4014 }
4015 Args.AddLastArg(CmdArgs, options::OPT_P);
4016 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4017
4018 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4019 CmdArgs.push_back("-diagnostic-log-file");
4020 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4021 : "-");
4022 }
4023
David L. Jonesf561aba2017-03-08 01:02:16 +00004024 bool UseSeparateSections = isUseSeparateSections(Triple);
4025
4026 if (Args.hasFlag(options::OPT_ffunction_sections,
4027 options::OPT_fno_function_sections, UseSeparateSections)) {
4028 CmdArgs.push_back("-ffunction-sections");
4029 }
4030
4031 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4032 UseSeparateSections)) {
4033 CmdArgs.push_back("-fdata-sections");
4034 }
4035
4036 if (!Args.hasFlag(options::OPT_funique_section_names,
4037 options::OPT_fno_unique_section_names, true))
4038 CmdArgs.push_back("-fno-unique-section-names");
4039
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00004040 if (auto *A = Args.getLastArg(
4041 options::OPT_finstrument_functions,
4042 options::OPT_finstrument_functions_after_inlining,
4043 options::OPT_finstrument_function_entry_bare))
4044 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004045
Artem Belevichc30bcad2018-01-24 17:41:02 +00004046 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4047 // sampling, overhead of call arc collection is way too high and there's no
4048 // way to collect the output.
4049 if (!Triple.isNVPTX())
4050 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004051
Richard Smithf667ad52017-08-26 01:04:35 +00004052 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
4053 ABICompatArg->render(Args, CmdArgs);
4054
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004055 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
4056 if (RawTriple.isPS4CPU()) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004057 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4058 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004059 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004060
4061 // Pass options for controlling the default header search paths.
4062 if (Args.hasArg(options::OPT_nostdinc)) {
4063 CmdArgs.push_back("-nostdsysteminc");
4064 CmdArgs.push_back("-nobuiltininc");
4065 } else {
4066 if (Args.hasArg(options::OPT_nostdlibinc))
4067 CmdArgs.push_back("-nostdsysteminc");
4068 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4069 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4070 }
4071
4072 // Pass the path to compiler resource files.
4073 CmdArgs.push_back("-resource-dir");
4074 CmdArgs.push_back(D.ResourceDir.c_str());
4075
4076 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4077
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004078 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004079
4080 // Add preprocessing options like -I, -D, etc. if we are using the
4081 // preprocessor.
4082 //
4083 // FIXME: Support -fpreprocessed
4084 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4085 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4086
4087 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4088 // that "The compiler can only warn and ignore the option if not recognized".
4089 // When building with ccache, it will pass -D options to clang even on
4090 // preprocessed inputs and configure concludes that -fPIC is not supported.
4091 Args.ClaimAllArgs(options::OPT_D);
4092
4093 // Manually translate -O4 to -O3; let clang reject others.
4094 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4095 if (A->getOption().matches(options::OPT_O4)) {
4096 CmdArgs.push_back("-O3");
4097 D.Diag(diag::warn_O4_is_O3);
4098 } else {
4099 A->render(Args, CmdArgs);
4100 }
4101 }
4102
4103 // Warn about ignored options to clang.
4104 for (const Arg *A :
4105 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4106 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4107 A->claim();
4108 }
4109
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004110 for (const Arg *A :
4111 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4112 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4113 A->claim();
4114 }
4115
David L. Jonesf561aba2017-03-08 01:02:16 +00004116 claimNoWarnArgs(Args);
4117
4118 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4119
4120 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4121 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4122 CmdArgs.push_back("-pedantic");
4123 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4124 Args.AddLastArg(CmdArgs, options::OPT_w);
4125
Leonard Chanf921d852018-06-04 16:07:52 +00004126 // Fixed point flags
4127 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4128 /*Default=*/false))
4129 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4130
David L. Jonesf561aba2017-03-08 01:02:16 +00004131 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4132 // (-ansi is equivalent to -std=c89 or -std=c++98).
4133 //
4134 // If a std is supplied, only add -trigraphs if it follows the
4135 // option.
4136 bool ImplyVCPPCXXVer = false;
4137 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4138 if (Std->getOption().matches(options::OPT_ansi))
4139 if (types::isCXX(InputType))
4140 CmdArgs.push_back("-std=c++98");
4141 else
4142 CmdArgs.push_back("-std=c89");
4143 else
4144 Std->render(Args, CmdArgs);
4145
4146 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4147 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4148 options::OPT_ftrigraphs,
4149 options::OPT_fno_trigraphs))
4150 if (A != Std)
4151 A->render(Args, CmdArgs);
4152 } else {
4153 // Honor -std-default.
4154 //
4155 // FIXME: Clang doesn't correctly handle -std= when the input language
4156 // doesn't match. For the time being just ignore this for C++ inputs;
4157 // eventually we want to do all the standard defaulting here instead of
4158 // splitting it between the driver and clang -cc1.
4159 if (!types::isCXX(InputType))
4160 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4161 /*Joined=*/true);
4162 else if (IsWindowsMSVC)
4163 ImplyVCPPCXXVer = true;
4164
4165 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4166 options::OPT_fno_trigraphs);
4167 }
4168
4169 // GCC's behavior for -Wwrite-strings is a bit strange:
4170 // * In C, this "warning flag" changes the types of string literals from
4171 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4172 // for the discarded qualifier.
4173 // * In C++, this is just a normal warning flag.
4174 //
4175 // Implementing this warning correctly in C is hard, so we follow GCC's
4176 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4177 // a non-const char* in C, rather than using this crude hack.
4178 if (!types::isCXX(InputType)) {
4179 // FIXME: This should behave just like a warning flag, and thus should also
4180 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4181 Arg *WriteStrings =
4182 Args.getLastArg(options::OPT_Wwrite_strings,
4183 options::OPT_Wno_write_strings, options::OPT_w);
4184 if (WriteStrings &&
4185 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4186 CmdArgs.push_back("-fconst-strings");
4187 }
4188
4189 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4190 // during C++ compilation, which it is by default. GCC keeps this define even
4191 // in the presence of '-w', match this behavior bug-for-bug.
4192 if (types::isCXX(InputType) &&
4193 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4194 true)) {
4195 CmdArgs.push_back("-fdeprecated-macro");
4196 }
4197
4198 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4199 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4200 if (Asm->getOption().matches(options::OPT_fasm))
4201 CmdArgs.push_back("-fgnu-keywords");
4202 else
4203 CmdArgs.push_back("-fno-gnu-keywords");
4204 }
4205
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004206 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004207 CmdArgs.push_back("-fno-dwarf-directory-asm");
4208
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004209 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004210 CmdArgs.push_back("-fno-autolink");
4211
4212 // Add in -fdebug-compilation-dir if necessary.
4213 addDebugCompDirArg(Args, CmdArgs);
4214
Paul Robinson9b292b42018-07-10 15:15:24 +00004215 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004216
4217 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4218 options::OPT_ftemplate_depth_EQ)) {
4219 CmdArgs.push_back("-ftemplate-depth");
4220 CmdArgs.push_back(A->getValue());
4221 }
4222
4223 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4224 CmdArgs.push_back("-foperator-arrow-depth");
4225 CmdArgs.push_back(A->getValue());
4226 }
4227
4228 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4229 CmdArgs.push_back("-fconstexpr-depth");
4230 CmdArgs.push_back(A->getValue());
4231 }
4232
4233 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4234 CmdArgs.push_back("-fconstexpr-steps");
4235 CmdArgs.push_back(A->getValue());
4236 }
4237
4238 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4239 CmdArgs.push_back("-fbracket-depth");
4240 CmdArgs.push_back(A->getValue());
4241 }
4242
4243 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4244 options::OPT_Wlarge_by_value_copy_def)) {
4245 if (A->getNumValues()) {
4246 StringRef bytes = A->getValue();
4247 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4248 } else
4249 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4250 }
4251
4252 if (Args.hasArg(options::OPT_relocatable_pch))
4253 CmdArgs.push_back("-relocatable-pch");
4254
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004255 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4256 static const char *kCFABIs[] = {
4257 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4258 };
4259
4260 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4261 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4262 else
4263 A->render(Args, CmdArgs);
4264 }
4265
David L. Jonesf561aba2017-03-08 01:02:16 +00004266 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4267 CmdArgs.push_back("-fconstant-string-class");
4268 CmdArgs.push_back(A->getValue());
4269 }
4270
4271 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4272 CmdArgs.push_back("-ftabstop");
4273 CmdArgs.push_back(A->getValue());
4274 }
4275
Sean Eveson5110d4f2018-01-08 13:42:26 +00004276 if (Args.hasFlag(options::OPT_fstack_size_section,
4277 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4278 CmdArgs.push_back("-fstack-size-section");
4279
David L. Jonesf561aba2017-03-08 01:02:16 +00004280 CmdArgs.push_back("-ferror-limit");
4281 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4282 CmdArgs.push_back(A->getValue());
4283 else
4284 CmdArgs.push_back("19");
4285
4286 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4287 CmdArgs.push_back("-fmacro-backtrace-limit");
4288 CmdArgs.push_back(A->getValue());
4289 }
4290
4291 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4292 CmdArgs.push_back("-ftemplate-backtrace-limit");
4293 CmdArgs.push_back(A->getValue());
4294 }
4295
4296 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4297 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4298 CmdArgs.push_back(A->getValue());
4299 }
4300
4301 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4302 CmdArgs.push_back("-fspell-checking-limit");
4303 CmdArgs.push_back(A->getValue());
4304 }
4305
4306 // Pass -fmessage-length=.
4307 CmdArgs.push_back("-fmessage-length");
4308 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4309 CmdArgs.push_back(A->getValue());
4310 } else {
4311 // If -fmessage-length=N was not specified, determine whether this is a
4312 // terminal and, if so, implicitly define -fmessage-length appropriately.
4313 unsigned N = llvm::sys::Process::StandardErrColumns();
4314 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4315 }
4316
4317 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4318 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4319 options::OPT_fvisibility_ms_compat)) {
4320 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4321 CmdArgs.push_back("-fvisibility");
4322 CmdArgs.push_back(A->getValue());
4323 } else {
4324 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4325 CmdArgs.push_back("-fvisibility");
4326 CmdArgs.push_back("hidden");
4327 CmdArgs.push_back("-ftype-visibility");
4328 CmdArgs.push_back("default");
4329 }
4330 }
4331
4332 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004333 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004334
4335 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4336
David L. Jonesf561aba2017-03-08 01:02:16 +00004337 // Forward -f (flag) options which we can pass directly.
4338 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4339 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004340 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004341 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004342 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4343 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004344 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004345
David L. Jonesf561aba2017-03-08 01:02:16 +00004346 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004347 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004348 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004349
David L. Jonesf561aba2017-03-08 01:02:16 +00004350 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4351 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4352
4353 // Forward flags for OpenMP. We don't do this if the current action is an
4354 // device offloading action other than OpenMP.
4355 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4356 options::OPT_fno_openmp, false) &&
4357 (JA.isDeviceOffloading(Action::OFK_None) ||
4358 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004359 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004360 case Driver::OMPRT_OMP:
4361 case Driver::OMPRT_IOMP5:
4362 // Clang can generate useful OpenMP code for these two runtime libraries.
4363 CmdArgs.push_back("-fopenmp");
4364
4365 // If no option regarding the use of TLS in OpenMP codegeneration is
4366 // given, decide a default based on the target. Otherwise rely on the
4367 // options and pass the right information to the frontend.
4368 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4369 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4370 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004371 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4372 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004373 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004374 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4375 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00004376
4377 // When in OpenMP offloading mode with NVPTX target, forward
4378 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004379 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4380 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4381 CmdArgs.push_back("-fopenmp-cuda-mode");
4382
4383 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4384 // is required.
4385 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4386 options::OPT_fno_openmp_cuda_force_full_runtime,
4387 /*Default=*/false))
4388 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004389 break;
4390 default:
4391 // By default, if Clang doesn't know how to generate useful OpenMP code
4392 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4393 // down to the actual compilation.
4394 // FIXME: It would be better to have a mode which *only* omits IR
4395 // generation based on the OpenMP support so that we get consistent
4396 // semantic analysis, etc.
4397 break;
4398 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004399 } else {
4400 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4401 options::OPT_fno_openmp_simd);
4402 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004403 }
4404
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004405 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4406 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004407
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004408 const XRayArgs &XRay = TC.getXRayArgs();
4409 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004410
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004411 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004412 Args.AddLastArg(CmdArgs, options::OPT_pg);
4413
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004414 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004415 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4416
4417 // -flax-vector-conversions is default.
4418 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4419 options::OPT_fno_lax_vector_conversions))
4420 CmdArgs.push_back("-fno-lax-vector-conversions");
4421
4422 if (Args.getLastArg(options::OPT_fapple_kext) ||
4423 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4424 CmdArgs.push_back("-fapple-kext");
4425
4426 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4427 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4428 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4429 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4430 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4431
4432 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4433 CmdArgs.push_back("-ftrapv-handler");
4434 CmdArgs.push_back(A->getValue());
4435 }
4436
4437 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4438
4439 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4440 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4441 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4442 if (A->getOption().matches(options::OPT_fwrapv))
4443 CmdArgs.push_back("-fwrapv");
4444 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4445 options::OPT_fno_strict_overflow)) {
4446 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4447 CmdArgs.push_back("-fwrapv");
4448 }
4449
4450 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4451 options::OPT_fno_reroll_loops))
4452 if (A->getOption().matches(options::OPT_freroll_loops))
4453 CmdArgs.push_back("-freroll-loops");
4454
4455 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4456 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4457 options::OPT_fno_unroll_loops);
4458
4459 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4460
Zola Bridgesc8666792018-11-26 18:13:31 +00004461 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4462 false))
4463 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004464
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004465 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004466
4467 // Translate -mstackrealign
4468 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4469 false))
4470 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4471
4472 if (Args.hasArg(options::OPT_mstack_alignment)) {
4473 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4474 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4475 }
4476
4477 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4478 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4479
4480 if (!Size.empty())
4481 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4482 else
4483 CmdArgs.push_back("-mstack-probe-size=0");
4484 }
4485
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004486 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4487 options::OPT_mno_stack_arg_probe, true))
4488 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4489
David L. Jonesf561aba2017-03-08 01:02:16 +00004490 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4491 options::OPT_mno_restrict_it)) {
4492 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004493 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004494 CmdArgs.push_back("-arm-restrict-it");
4495 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004496 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004497 CmdArgs.push_back("-arm-no-restrict-it");
4498 }
4499 } else if (Triple.isOSWindows() &&
4500 (Triple.getArch() == llvm::Triple::arm ||
4501 Triple.getArch() == llvm::Triple::thumb)) {
4502 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004503 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004504 CmdArgs.push_back("-arm-restrict-it");
4505 }
4506
4507 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004508 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004509
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004510 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4511 CmdArgs.push_back(
4512 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4513 }
4514
David L. Jonesf561aba2017-03-08 01:02:16 +00004515 // Forward -f options with positive and negative forms; we translate
4516 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004517 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004518 StringRef fname = A->getValue();
4519 if (!llvm::sys::fs::exists(fname))
4520 D.Diag(diag::err_drv_no_such_file) << fname;
4521 else
4522 A->render(Args, CmdArgs);
4523 }
Richard Smith8654ae52018-10-10 23:13:35 +00004524 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004525
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004526 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004527
4528 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4529 options::OPT_fno_assume_sane_operator_new))
4530 CmdArgs.push_back("-fno-assume-sane-operator-new");
4531
4532 // -fblocks=0 is default.
4533 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004534 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004535 (Args.hasArg(options::OPT_fgnu_runtime) &&
4536 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4537 !Args.hasArg(options::OPT_fno_blocks))) {
4538 CmdArgs.push_back("-fblocks");
4539
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004540 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004541 CmdArgs.push_back("-fblocks-runtime-optional");
4542 }
4543
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004544 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004545 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004546 CmdArgs.push_back("-fencode-extended-block-signature");
4547
David L. Jonesf561aba2017-03-08 01:02:16 +00004548 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4549 false) &&
4550 types::isCXX(InputType)) {
4551 CmdArgs.push_back("-fcoroutines-ts");
4552 }
4553
Aaron Ballman61736552017-10-21 20:28:58 +00004554 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4555 options::OPT_fno_double_square_bracket_attributes);
4556
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004557 bool HaveModules = false;
4558 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004559
4560 // -faccess-control is default.
4561 if (Args.hasFlag(options::OPT_fno_access_control,
4562 options::OPT_faccess_control, false))
4563 CmdArgs.push_back("-fno-access-control");
4564
4565 // -felide-constructors is the default.
4566 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4567 options::OPT_felide_constructors, false))
4568 CmdArgs.push_back("-fno-elide-constructors");
4569
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004570 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004571
4572 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004573 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004574 CmdArgs.push_back("-fno-rtti");
4575
4576 // -fshort-enums=0 is default for all architectures except Hexagon.
4577 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004578 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004579 CmdArgs.push_back("-fshort-enums");
4580
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004581 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004582
4583 // -fuse-cxa-atexit is default.
4584 if (!Args.hasFlag(
4585 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004586 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004587 RawTriple.getOS() != llvm::Triple::Solaris &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004588 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004589 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4590 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004591 KernelOrKext)
4592 CmdArgs.push_back("-fno-use-cxa-atexit");
4593
Akira Hatanaka617e2612018-04-17 18:41:52 +00004594 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4595 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004596 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004597 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4598
David L. Jonesf561aba2017-03-08 01:02:16 +00004599 // -fms-extensions=0 is default.
4600 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4601 IsWindowsMSVC))
4602 CmdArgs.push_back("-fms-extensions");
4603
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004604 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004605 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004606 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004607 CmdArgs.push_back("-fuse-line-directives");
4608
4609 // -fms-compatibility=0 is default.
4610 if (Args.hasFlag(options::OPT_fms_compatibility,
4611 options::OPT_fno_ms_compatibility,
4612 (IsWindowsMSVC &&
4613 Args.hasFlag(options::OPT_fms_extensions,
4614 options::OPT_fno_ms_extensions, true))))
4615 CmdArgs.push_back("-fms-compatibility");
4616
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004617 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004618 if (!MSVT.empty())
4619 CmdArgs.push_back(
4620 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4621
4622 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4623 if (ImplyVCPPCXXVer) {
4624 StringRef LanguageStandard;
4625 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4626 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4627 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004628 .Case("c++17", "-std=c++17")
4629 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004630 .Default("");
4631 if (LanguageStandard.empty())
4632 D.Diag(clang::diag::warn_drv_unused_argument)
4633 << StdArg->getAsString(Args);
4634 }
4635
4636 if (LanguageStandard.empty()) {
4637 if (IsMSVC2015Compatible)
4638 LanguageStandard = "-std=c++14";
4639 else
4640 LanguageStandard = "-std=c++11";
4641 }
4642
4643 CmdArgs.push_back(LanguageStandard.data());
4644 }
4645
4646 // -fno-borland-extensions is default.
4647 if (Args.hasFlag(options::OPT_fborland_extensions,
4648 options::OPT_fno_borland_extensions, false))
4649 CmdArgs.push_back("-fborland-extensions");
4650
4651 // -fno-declspec is default, except for PS4.
4652 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004653 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004654 CmdArgs.push_back("-fdeclspec");
4655 else if (Args.hasArg(options::OPT_fno_declspec))
4656 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4657
4658 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4659 // than 19.
4660 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4661 options::OPT_fno_threadsafe_statics,
4662 !IsWindowsMSVC || IsMSVC2015Compatible))
4663 CmdArgs.push_back("-fno-threadsafe-statics");
4664
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004665 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004666 // Many old Windows SDK versions require this to parse.
4667 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4668 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004669 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4670 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4671 CmdArgs.push_back("-fdelayed-template-parsing");
4672
4673 // -fgnu-keywords default varies depending on language; only pass if
4674 // specified.
4675 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4676 options::OPT_fno_gnu_keywords))
4677 A->render(Args, CmdArgs);
4678
4679 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4680 false))
4681 CmdArgs.push_back("-fgnu89-inline");
4682
4683 if (Args.hasArg(options::OPT_fno_inline))
4684 CmdArgs.push_back("-fno-inline");
4685
4686 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4687 options::OPT_finline_hint_functions,
4688 options::OPT_fno_inline_functions))
4689 InlineArg->render(Args, CmdArgs);
4690
4691 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4692 options::OPT_fno_experimental_new_pass_manager);
4693
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004694 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004695 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4696 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004697
4698 if (Args.hasFlag(options::OPT_fapplication_extension,
4699 options::OPT_fno_application_extension, false))
4700 CmdArgs.push_back("-fapplication-extension");
4701
4702 // Handle GCC-style exception args.
4703 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004704 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004705
Martell Malonec950c652017-11-29 07:25:12 +00004706 // Handle exception personalities
4707 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4708 options::OPT_fseh_exceptions,
4709 options::OPT_fdwarf_exceptions);
4710 if (A) {
4711 const Option &Opt = A->getOption();
4712 if (Opt.matches(options::OPT_fsjlj_exceptions))
4713 CmdArgs.push_back("-fsjlj-exceptions");
4714 if (Opt.matches(options::OPT_fseh_exceptions))
4715 CmdArgs.push_back("-fseh-exceptions");
4716 if (Opt.matches(options::OPT_fdwarf_exceptions))
4717 CmdArgs.push_back("-fdwarf-exceptions");
4718 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004719 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004720 default:
4721 break;
4722 case llvm::ExceptionHandling::DwarfCFI:
4723 CmdArgs.push_back("-fdwarf-exceptions");
4724 break;
4725 case llvm::ExceptionHandling::SjLj:
4726 CmdArgs.push_back("-fsjlj-exceptions");
4727 break;
4728 case llvm::ExceptionHandling::WinEH:
4729 CmdArgs.push_back("-fseh-exceptions");
4730 break;
Martell Malonec950c652017-11-29 07:25:12 +00004731 }
4732 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004733
4734 // C++ "sane" operator new.
4735 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4736 options::OPT_fno_assume_sane_operator_new))
4737 CmdArgs.push_back("-fno-assume-sane-operator-new");
4738
4739 // -frelaxed-template-template-args is off by default, as it is a severe
4740 // breaking change until a corresponding change to template partial ordering
4741 // is provided.
4742 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4743 options::OPT_fno_relaxed_template_template_args, false))
4744 CmdArgs.push_back("-frelaxed-template-template-args");
4745
4746 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4747 // most platforms.
4748 if (Args.hasFlag(options::OPT_fsized_deallocation,
4749 options::OPT_fno_sized_deallocation, false))
4750 CmdArgs.push_back("-fsized-deallocation");
4751
4752 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4753 // by default.
4754 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4755 options::OPT_fno_aligned_allocation,
4756 options::OPT_faligned_new_EQ)) {
4757 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4758 CmdArgs.push_back("-fno-aligned-allocation");
4759 else
4760 CmdArgs.push_back("-faligned-allocation");
4761 }
4762
4763 // The default new alignment can be specified using a dedicated option or via
4764 // a GCC-compatible option that also turns on aligned allocation.
4765 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4766 options::OPT_faligned_new_EQ))
4767 CmdArgs.push_back(
4768 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4769
4770 // -fconstant-cfstrings is default, and may be subject to argument translation
4771 // on Darwin.
4772 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4773 options::OPT_fno_constant_cfstrings) ||
4774 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4775 options::OPT_mno_constant_cfstrings))
4776 CmdArgs.push_back("-fno-constant-cfstrings");
4777
David L. Jonesf561aba2017-03-08 01:02:16 +00004778 // -fno-pascal-strings is default, only pass non-default.
4779 if (Args.hasFlag(options::OPT_fpascal_strings,
4780 options::OPT_fno_pascal_strings, false))
4781 CmdArgs.push_back("-fpascal-strings");
4782
4783 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4784 // -fno-pack-struct doesn't apply to -fpack-struct=.
4785 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4786 std::string PackStructStr = "-fpack-struct=";
4787 PackStructStr += A->getValue();
4788 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4789 } else if (Args.hasFlag(options::OPT_fpack_struct,
4790 options::OPT_fno_pack_struct, false)) {
4791 CmdArgs.push_back("-fpack-struct=1");
4792 }
4793
4794 // Handle -fmax-type-align=N and -fno-type-align
4795 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4796 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4797 if (!SkipMaxTypeAlign) {
4798 std::string MaxTypeAlignStr = "-fmax-type-align=";
4799 MaxTypeAlignStr += A->getValue();
4800 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4801 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004802 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004803 if (!SkipMaxTypeAlign) {
4804 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4805 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4806 }
4807 }
4808
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004809 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4810 CmdArgs.push_back("-Qn");
4811
David L. Jonesf561aba2017-03-08 01:02:16 +00004812 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004813 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004814 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4815 !NoCommonDefault))
4816 CmdArgs.push_back("-fno-common");
4817
4818 // -fsigned-bitfields is default, and clang doesn't yet support
4819 // -funsigned-bitfields.
4820 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4821 options::OPT_funsigned_bitfields))
4822 D.Diag(diag::warn_drv_clang_unsupported)
4823 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4824
4825 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4826 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4827 D.Diag(diag::err_drv_clang_unsupported)
4828 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4829
4830 // -finput_charset=UTF-8 is default. Reject others
4831 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4832 StringRef value = inputCharset->getValue();
4833 if (!value.equals_lower("utf-8"))
4834 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4835 << value;
4836 }
4837
4838 // -fexec_charset=UTF-8 is default. Reject others
4839 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4840 StringRef value = execCharset->getValue();
4841 if (!value.equals_lower("utf-8"))
4842 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4843 << value;
4844 }
4845
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004846 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004847
4848 // -fno-asm-blocks is default.
4849 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4850 false))
4851 CmdArgs.push_back("-fasm-blocks");
4852
4853 // -fgnu-inline-asm is default.
4854 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4855 options::OPT_fno_gnu_inline_asm, true))
4856 CmdArgs.push_back("-fno-gnu-inline-asm");
4857
4858 // Enable vectorization per default according to the optimization level
4859 // selected. For optimization levels that want vectorization we use the alias
4860 // option to simplify the hasFlag logic.
4861 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4862 OptSpecifier VectorizeAliasOption =
4863 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4864 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4865 options::OPT_fno_vectorize, EnableVec))
4866 CmdArgs.push_back("-vectorize-loops");
4867
4868 // -fslp-vectorize is enabled based on the optimization level selected.
4869 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4870 OptSpecifier SLPVectAliasOption =
4871 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4872 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4873 options::OPT_fno_slp_vectorize, EnableSLPVec))
4874 CmdArgs.push_back("-vectorize-slp");
4875
Craig Topper9a724aa2017-12-11 21:09:19 +00004876 ParseMPreferVectorWidth(D, Args, CmdArgs);
4877
David L. Jonesf561aba2017-03-08 01:02:16 +00004878 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4879 A->render(Args, CmdArgs);
4880
4881 if (Arg *A = Args.getLastArg(
4882 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4883 A->render(Args, CmdArgs);
4884
4885 // -fdollars-in-identifiers default varies depending on platform and
4886 // language; only pass if specified.
4887 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4888 options::OPT_fno_dollars_in_identifiers)) {
4889 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4890 CmdArgs.push_back("-fdollars-in-identifiers");
4891 else
4892 CmdArgs.push_back("-fno-dollars-in-identifiers");
4893 }
4894
4895 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4896 // practical purposes.
4897 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4898 options::OPT_fno_unit_at_a_time)) {
4899 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4900 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4901 }
4902
4903 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4904 options::OPT_fno_apple_pragma_pack, false))
4905 CmdArgs.push_back("-fapple-pragma-pack");
4906
David L. Jonesf561aba2017-03-08 01:02:16 +00004907 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004908 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004909 options::OPT_fno_save_optimization_record, false)) {
4910 CmdArgs.push_back("-opt-record-file");
4911
4912 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4913 if (A) {
4914 CmdArgs.push_back(A->getValue());
4915 } else {
4916 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004917
4918 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4919 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4920 F = FinalOutput->getValue();
4921 }
4922
4923 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004924 // Use the input filename.
4925 F = llvm::sys::path::stem(Input.getBaseInput());
4926
4927 // If we're compiling for an offload architecture (i.e. a CUDA device),
4928 // we need to make the file name for the device compilation different
4929 // from the host compilation.
4930 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4931 !JA.isDeviceOffloading(Action::OFK_Host)) {
4932 llvm::sys::path::replace_extension(F, "");
4933 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4934 Triple.normalize());
4935 F += "-";
4936 F += JA.getOffloadingArch();
4937 }
4938 }
4939
4940 llvm::sys::path::replace_extension(F, "opt.yaml");
4941 CmdArgs.push_back(Args.MakeArgString(F));
4942 }
4943 }
4944
Richard Smith86a3ef52017-06-09 21:24:02 +00004945 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4946 options::OPT_fno_rewrite_imports, false);
4947 if (RewriteImports)
4948 CmdArgs.push_back("-frewrite-imports");
4949
David L. Jonesf561aba2017-03-08 01:02:16 +00004950 // Enable rewrite includes if the user's asked for it or if we're generating
4951 // diagnostics.
4952 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4953 // nice to enable this when doing a crashdump for modules as well.
4954 if (Args.hasFlag(options::OPT_frewrite_includes,
4955 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00004956 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00004957 CmdArgs.push_back("-frewrite-includes");
4958
4959 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4960 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4961 options::OPT_traditional_cpp)) {
4962 if (isa<PreprocessJobAction>(JA))
4963 CmdArgs.push_back("-traditional-cpp");
4964 else
4965 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4966 }
4967
4968 Args.AddLastArg(CmdArgs, options::OPT_dM);
4969 Args.AddLastArg(CmdArgs, options::OPT_dD);
4970
4971 // Handle serialized diagnostics.
4972 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4973 CmdArgs.push_back("-serialize-diagnostic-file");
4974 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4975 }
4976
4977 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4978 CmdArgs.push_back("-fretain-comments-from-system-headers");
4979
4980 // Forward -fcomment-block-commands to -cc1.
4981 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4982 // Forward -fparse-all-comments to -cc1.
4983 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4984
4985 // Turn -fplugin=name.so into -load name.so
4986 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4987 CmdArgs.push_back("-load");
4988 CmdArgs.push_back(A->getValue());
4989 A->claim();
4990 }
4991
4992 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004993 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4994 if (!StatsFile.empty())
4995 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004996
4997 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4998 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004999 // -finclude-default-header flag is for preprocessor,
5000 // do not pass it to other cc1 commands when save-temps is enabled
5001 if (C.getDriver().isSaveTempsEnabled() &&
5002 !isa<PreprocessJobAction>(JA)) {
5003 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5004 Arg->claim();
5005 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5006 CmdArgs.push_back(Arg->getValue());
5007 }
5008 }
5009 else {
5010 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5011 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005012 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5013 A->claim();
5014
5015 // We translate this by hand to the -cc1 argument, since nightly test uses
5016 // it and developers have been trained to spell it with -mllvm. Both
5017 // spellings are now deprecated and should be removed.
5018 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5019 CmdArgs.push_back("-disable-llvm-optzns");
5020 } else {
5021 A->render(Args, CmdArgs);
5022 }
5023 }
5024
5025 // With -save-temps, we want to save the unoptimized bitcode output from the
5026 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5027 // by the frontend.
5028 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5029 // has slightly different breakdown between stages.
5030 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5031 // pristine IR generated by the frontend. Ideally, a new compile action should
5032 // be added so both IR can be captured.
5033 if (C.getDriver().isSaveTempsEnabled() &&
5034 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5035 isa<CompileJobAction>(JA))
5036 CmdArgs.push_back("-disable-llvm-passes");
5037
5038 if (Output.getType() == types::TY_Dependencies) {
5039 // Handled with other dependency code.
5040 } else if (Output.isFilename()) {
5041 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00005042 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00005043 } else {
5044 assert(Output.isNothing() && "Invalid output.");
5045 }
5046
5047 addDashXForInput(Args, Input, CmdArgs);
5048
Richard Smithcd35eff2018-09-15 01:21:16 +00005049 ArrayRef<InputInfo> FrontendInputs = Input;
5050 if (IsHeaderModulePrecompile)
5051 FrontendInputs = ModuleHeaderInputs;
5052 else if (Input.isNothing())
5053 FrontendInputs = {};
5054
5055 for (const InputInfo &Input : FrontendInputs) {
5056 if (Input.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00005057 CmdArgs.push_back(Input.getFilename());
Richard Smithcd35eff2018-09-15 01:21:16 +00005058 else
5059 Input.getInputArg().renderAsInput(Args, CmdArgs);
5060 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005061
5062 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5063
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005064 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005065
Scott Linderde6beb02018-12-14 15:38:15 +00005066 // Optionally embed the -cc1 level arguments into the debug info or a
5067 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005068 // Also record command line arguments into the debug info if
5069 // -grecord-gcc-switches options is set on.
5070 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005071 auto GRecordSwitches =
5072 Args.hasFlag(options::OPT_grecord_command_line,
5073 options::OPT_gno_record_command_line, false);
5074 auto FRecordSwitches =
5075 Args.hasFlag(options::OPT_frecord_command_line,
5076 options::OPT_fno_record_command_line, false);
5077 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5078 D.Diag(diag::err_drv_unsupported_opt_for_target)
5079 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5080 << TripleStr;
5081 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005082 ArgStringList OriginalArgs;
5083 for (const auto &Arg : Args)
5084 Arg->render(Args, OriginalArgs);
5085
5086 SmallString<256> Flags;
5087 Flags += Exec;
5088 for (const char *OriginalArg : OriginalArgs) {
5089 SmallString<128> EscapedArg;
5090 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5091 Flags += " ";
5092 Flags += EscapedArg;
5093 }
Scott Linderde6beb02018-12-14 15:38:15 +00005094 auto FlagsArgString = Args.MakeArgString(Flags);
5095 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5096 CmdArgs.push_back("-dwarf-debug-flags");
5097 CmdArgs.push_back(FlagsArgString);
5098 }
5099 if (FRecordSwitches) {
5100 CmdArgs.push_back("-record-command-line");
5101 CmdArgs.push_back(FlagsArgString);
5102 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005103 }
5104
Yaxun Liu97670892018-10-02 17:48:54 +00005105 // Host-side cuda compilation receives all device-side outputs in a single
5106 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5107 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005108 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005109 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005110 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5111 CmdArgs.push_back("-fgpu-rdc");
5112 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005113
Yaxun Liu97670892018-10-02 17:48:54 +00005114 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005115 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5116 options::OPT_fno_cuda_short_ptr, false))
5117 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005118 }
5119
David L. Jonesf561aba2017-03-08 01:02:16 +00005120 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5121 // to specify the result of the compile phase on the host, so the meaningful
5122 // device declarations can be identified. Also, -fopenmp-is-device is passed
5123 // along to tell the frontend that it is generating code for a device, so that
5124 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005125 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005126 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005127 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005128 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005129 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005130 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005131 }
5132
5133 // For all the host OpenMP offloading compile jobs we need to pass the targets
5134 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005135 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005136 SmallString<128> TargetInfo("-fopenmp-targets=");
5137
5138 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5139 assert(Tgts && Tgts->getNumValues() &&
5140 "OpenMP offloading has to have targets specified.");
5141 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5142 if (i)
5143 TargetInfo += ',';
5144 // We need to get the string from the triple because it may be not exactly
5145 // the same as the one we get directly from the arguments.
5146 llvm::Triple T(Tgts->getValue(i));
5147 TargetInfo += T.getTriple();
5148 }
5149 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5150 }
5151
5152 bool WholeProgramVTables =
5153 Args.hasFlag(options::OPT_fwhole_program_vtables,
5154 options::OPT_fno_whole_program_vtables, false);
5155 if (WholeProgramVTables) {
5156 if (!D.isUsingLTO())
5157 D.Diag(diag::err_drv_argument_only_allowed_with)
5158 << "-fwhole-program-vtables"
5159 << "-flto";
5160 CmdArgs.push_back("-fwhole-program-vtables");
5161 }
5162
Amara Emerson4ee9f822018-01-26 00:27:22 +00005163 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5164 options::OPT_fno_experimental_isel)) {
5165 CmdArgs.push_back("-mllvm");
5166 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5167 CmdArgs.push_back("-global-isel=1");
5168
5169 // GISel is on by default on AArch64 -O0, so don't bother adding
5170 // the fallback remarks for it. Other combinations will add a warning of
5171 // some kind.
5172 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5173 bool IsOptLevelSupported = false;
5174
5175 Arg *A = Args.getLastArg(options::OPT_O_Group);
5176 if (Triple.getArch() == llvm::Triple::aarch64) {
5177 if (!A || A->getOption().matches(options::OPT_O0))
5178 IsOptLevelSupported = true;
5179 }
5180 if (!IsArchSupported || !IsOptLevelSupported) {
5181 CmdArgs.push_back("-mllvm");
5182 CmdArgs.push_back("-global-isel-abort=2");
5183
5184 if (!IsArchSupported)
5185 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5186 else
5187 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5188 }
5189 } else {
5190 CmdArgs.push_back("-global-isel=0");
5191 }
5192 }
5193
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005194 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5195 options::OPT_fno_force_enable_int128)) {
5196 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5197 CmdArgs.push_back("-fforce-enable-int128");
5198 }
5199
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005200 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5201 options::OPT_fno_complete_member_pointers, false))
5202 CmdArgs.push_back("-fcomplete-member-pointers");
5203
Erik Pilkington5a559e62018-08-21 17:24:06 +00005204 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5205 options::OPT_fno_cxx_static_destructors, true))
5206 CmdArgs.push_back("-fno-c++-static-destructors");
5207
Jessica Paquette36a25672018-06-29 18:06:10 +00005208 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5209 options::OPT_mno_outline)) {
5210 if (A->getOption().matches(options::OPT_moutline)) {
5211 // We only support -moutline in AArch64 right now. If we're not compiling
5212 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5213 // proper mllvm flags.
5214 if (Triple.getArch() != llvm::Triple::aarch64) {
5215 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5216 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005217 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005218 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005219 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005220 } else {
5221 // Disable all outlining behaviour.
5222 CmdArgs.push_back("-mllvm");
5223 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005224 }
5225 }
5226
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005227 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005228 (TC.getTriple().isOSBinFormatELF() ||
5229 TC.getTriple().isOSBinFormatCOFF()) &&
5230 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005231 CmdArgs.push_back("-faddrsig");
5232
David L. Jonesf561aba2017-03-08 01:02:16 +00005233 // Finally add the compile command to the compilation.
5234 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5235 Output.getType() == types::TY_Object &&
5236 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5237 auto CLCommand =
5238 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5239 C.addCommand(llvm::make_unique<FallbackCommand>(
5240 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5241 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5242 isa<PrecompileJobAction>(JA)) {
5243 // In /fallback builds, run the main compilation even if the pch generation
5244 // fails, so that the main compilation's fallback to cl.exe runs.
5245 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5246 CmdArgs, Inputs));
5247 } else {
5248 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5249 }
5250
Hans Wennborg2fe01042018-10-13 19:13:14 +00005251 // Make the compile command echo its inputs for /showFilenames.
5252 if (Output.getType() == types::TY_Object &&
5253 Args.hasFlag(options::OPT__SLASH_showFilenames,
5254 options::OPT__SLASH_showFilenames_, false)) {
5255 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5256 }
5257
David L. Jonesf561aba2017-03-08 01:02:16 +00005258 if (Arg *A = Args.getLastArg(options::OPT_pg))
David Blaikie5941da32018-09-18 20:11:45 +00005259 if (!shouldUseFramePointer(Args, Triple))
David L. Jonesf561aba2017-03-08 01:02:16 +00005260 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5261 << A->getAsString(Args);
5262
5263 // Claim some arguments which clang supports automatically.
5264
5265 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005266 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005267 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5268
5269 // Claim some arguments which clang doesn't support, but we don't
5270 // care to warn the user about.
5271 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5272 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5273
5274 // Disable warnings for clang -E -emit-llvm foo.c
5275 Args.ClaimAllArgs(options::OPT_emit_llvm);
5276}
5277
5278Clang::Clang(const ToolChain &TC)
5279 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5280 // as it is for other tools. Some operations on a Tool actually test
5281 // whether that tool is Clang based on the Tool's Name as a string.
5282 : Tool("clang", "clang frontend", TC, RF_Full) {}
5283
5284Clang::~Clang() {}
5285
5286/// Add options related to the Objective-C runtime/ABI.
5287///
5288/// Returns true if the runtime is non-fragile.
5289ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5290 ArgStringList &cmdArgs,
5291 RewriteKind rewriteKind) const {
5292 // Look for the controlling runtime option.
5293 Arg *runtimeArg =
5294 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5295 options::OPT_fobjc_runtime_EQ);
5296
5297 // Just forward -fobjc-runtime= to the frontend. This supercedes
5298 // options about fragility.
5299 if (runtimeArg &&
5300 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5301 ObjCRuntime runtime;
5302 StringRef value = runtimeArg->getValue();
5303 if (runtime.tryParse(value)) {
5304 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5305 << value;
5306 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005307 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5308 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005309 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5310 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005311 getToolChain().getDriver().Diag(
5312 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5313 << runtime.getVersion().getMajor();
5314 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005315
5316 runtimeArg->render(args, cmdArgs);
5317 return runtime;
5318 }
5319
5320 // Otherwise, we'll need the ABI "version". Version numbers are
5321 // slightly confusing for historical reasons:
5322 // 1 - Traditional "fragile" ABI
5323 // 2 - Non-fragile ABI, version 1
5324 // 3 - Non-fragile ABI, version 2
5325 unsigned objcABIVersion = 1;
5326 // If -fobjc-abi-version= is present, use that to set the version.
5327 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5328 StringRef value = abiArg->getValue();
5329 if (value == "1")
5330 objcABIVersion = 1;
5331 else if (value == "2")
5332 objcABIVersion = 2;
5333 else if (value == "3")
5334 objcABIVersion = 3;
5335 else
5336 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5337 } else {
5338 // Otherwise, determine if we are using the non-fragile ABI.
5339 bool nonFragileABIIsDefault =
5340 (rewriteKind == RK_NonFragile ||
5341 (rewriteKind == RK_None &&
5342 getToolChain().IsObjCNonFragileABIDefault()));
5343 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5344 options::OPT_fno_objc_nonfragile_abi,
5345 nonFragileABIIsDefault)) {
5346// Determine the non-fragile ABI version to use.
5347#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5348 unsigned nonFragileABIVersion = 1;
5349#else
5350 unsigned nonFragileABIVersion = 2;
5351#endif
5352
5353 if (Arg *abiArg =
5354 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5355 StringRef value = abiArg->getValue();
5356 if (value == "1")
5357 nonFragileABIVersion = 1;
5358 else if (value == "2")
5359 nonFragileABIVersion = 2;
5360 else
5361 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5362 << value;
5363 }
5364
5365 objcABIVersion = 1 + nonFragileABIVersion;
5366 } else {
5367 objcABIVersion = 1;
5368 }
5369 }
5370
5371 // We don't actually care about the ABI version other than whether
5372 // it's non-fragile.
5373 bool isNonFragile = objcABIVersion != 1;
5374
5375 // If we have no runtime argument, ask the toolchain for its default runtime.
5376 // However, the rewriter only really supports the Mac runtime, so assume that.
5377 ObjCRuntime runtime;
5378 if (!runtimeArg) {
5379 switch (rewriteKind) {
5380 case RK_None:
5381 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5382 break;
5383 case RK_Fragile:
5384 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5385 break;
5386 case RK_NonFragile:
5387 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5388 break;
5389 }
5390
5391 // -fnext-runtime
5392 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5393 // On Darwin, make this use the default behavior for the toolchain.
5394 if (getToolChain().getTriple().isOSDarwin()) {
5395 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5396
5397 // Otherwise, build for a generic macosx port.
5398 } else {
5399 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5400 }
5401
5402 // -fgnu-runtime
5403 } else {
5404 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5405 // Legacy behaviour is to target the gnustep runtime if we are in
5406 // non-fragile mode or the GCC runtime in fragile mode.
5407 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005408 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005409 else
5410 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5411 }
5412
5413 cmdArgs.push_back(
5414 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5415 return runtime;
5416}
5417
5418static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5419 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5420 I += HaveDash;
5421 return !HaveDash;
5422}
5423
5424namespace {
5425struct EHFlags {
5426 bool Synch = false;
5427 bool Asynch = false;
5428 bool NoUnwindC = false;
5429};
5430} // end anonymous namespace
5431
5432/// /EH controls whether to run destructor cleanups when exceptions are
5433/// thrown. There are three modifiers:
5434/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5435/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5436/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5437/// - c: Assume that extern "C" functions are implicitly nounwind.
5438/// The default is /EHs-c-, meaning cleanups are disabled.
5439static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5440 EHFlags EH;
5441
5442 std::vector<std::string> EHArgs =
5443 Args.getAllArgValues(options::OPT__SLASH_EH);
5444 for (auto EHVal : EHArgs) {
5445 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5446 switch (EHVal[I]) {
5447 case 'a':
5448 EH.Asynch = maybeConsumeDash(EHVal, I);
5449 if (EH.Asynch)
5450 EH.Synch = false;
5451 continue;
5452 case 'c':
5453 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5454 continue;
5455 case 's':
5456 EH.Synch = maybeConsumeDash(EHVal, I);
5457 if (EH.Synch)
5458 EH.Asynch = false;
5459 continue;
5460 default:
5461 break;
5462 }
5463 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5464 break;
5465 }
5466 }
5467 // The /GX, /GX- flags are only processed if there are not /EH flags.
5468 // The default is that /GX is not specified.
5469 if (EHArgs.empty() &&
5470 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5471 /*default=*/false)) {
5472 EH.Synch = true;
5473 EH.NoUnwindC = true;
5474 }
5475
5476 return EH;
5477}
5478
5479void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5480 ArgStringList &CmdArgs,
5481 codegenoptions::DebugInfoKind *DebugInfoKind,
5482 bool *EmitCodeView) const {
5483 unsigned RTOptionID = options::OPT__SLASH_MT;
5484
5485 if (Args.hasArg(options::OPT__SLASH_LDd))
5486 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5487 // but defining _DEBUG is sticky.
5488 RTOptionID = options::OPT__SLASH_MTd;
5489
5490 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5491 RTOptionID = A->getOption().getID();
5492
5493 StringRef FlagForCRT;
5494 switch (RTOptionID) {
5495 case options::OPT__SLASH_MD:
5496 if (Args.hasArg(options::OPT__SLASH_LDd))
5497 CmdArgs.push_back("-D_DEBUG");
5498 CmdArgs.push_back("-D_MT");
5499 CmdArgs.push_back("-D_DLL");
5500 FlagForCRT = "--dependent-lib=msvcrt";
5501 break;
5502 case options::OPT__SLASH_MDd:
5503 CmdArgs.push_back("-D_DEBUG");
5504 CmdArgs.push_back("-D_MT");
5505 CmdArgs.push_back("-D_DLL");
5506 FlagForCRT = "--dependent-lib=msvcrtd";
5507 break;
5508 case options::OPT__SLASH_MT:
5509 if (Args.hasArg(options::OPT__SLASH_LDd))
5510 CmdArgs.push_back("-D_DEBUG");
5511 CmdArgs.push_back("-D_MT");
5512 CmdArgs.push_back("-flto-visibility-public-std");
5513 FlagForCRT = "--dependent-lib=libcmt";
5514 break;
5515 case options::OPT__SLASH_MTd:
5516 CmdArgs.push_back("-D_DEBUG");
5517 CmdArgs.push_back("-D_MT");
5518 CmdArgs.push_back("-flto-visibility-public-std");
5519 FlagForCRT = "--dependent-lib=libcmtd";
5520 break;
5521 default:
5522 llvm_unreachable("Unexpected option ID.");
5523 }
5524
5525 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5526 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5527 } else {
5528 CmdArgs.push_back(FlagForCRT.data());
5529
5530 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5531 // users want. The /Za flag to cl.exe turns this off, but it's not
5532 // implemented in clang.
5533 CmdArgs.push_back("--dependent-lib=oldnames");
5534 }
5535
Erich Keane425f48d2018-05-04 15:58:31 +00005536 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5537 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005538
5539 // This controls whether or not we emit RTTI data for polymorphic types.
5540 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5541 /*default=*/false))
5542 CmdArgs.push_back("-fno-rtti-data");
5543
5544 // This controls whether or not we emit stack-protector instrumentation.
5545 // In MSVC, Buffer Security Check (/GS) is on by default.
5546 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5547 /*default=*/true)) {
5548 CmdArgs.push_back("-stack-protector");
5549 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5550 }
5551
5552 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5553 if (Arg *DebugInfoArg =
5554 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5555 options::OPT_gline_tables_only)) {
5556 *EmitCodeView = true;
5557 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5558 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5559 else
5560 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005561 } else {
5562 *EmitCodeView = false;
5563 }
5564
5565 const Driver &D = getToolChain().getDriver();
5566 EHFlags EH = parseClangCLEHFlags(D, Args);
5567 if (EH.Synch || EH.Asynch) {
5568 if (types::isCXX(InputType))
5569 CmdArgs.push_back("-fcxx-exceptions");
5570 CmdArgs.push_back("-fexceptions");
5571 }
5572 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5573 CmdArgs.push_back("-fexternc-nounwind");
5574
5575 // /EP should expand to -E -P.
5576 if (Args.hasArg(options::OPT__SLASH_EP)) {
5577 CmdArgs.push_back("-E");
5578 CmdArgs.push_back("-P");
5579 }
5580
5581 unsigned VolatileOptionID;
5582 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5583 getToolChain().getArch() == llvm::Triple::x86)
5584 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5585 else
5586 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5587
5588 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5589 VolatileOptionID = A->getOption().getID();
5590
5591 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5592 CmdArgs.push_back("-fms-volatile");
5593
Takuto Ikuta302c6432018-11-03 06:45:00 +00005594 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5595 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005596 false)) {
5597 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5598 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5599 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005600 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005601 }
5602 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005603
David L. Jonesf561aba2017-03-08 01:02:16 +00005604 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5605 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5606 if (MostGeneralArg && BestCaseArg)
5607 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5608 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5609
5610 if (MostGeneralArg) {
5611 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5612 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5613 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5614
5615 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5616 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5617 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5618 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5619 << FirstConflict->getAsString(Args)
5620 << SecondConflict->getAsString(Args);
5621
5622 if (SingleArg)
5623 CmdArgs.push_back("-fms-memptr-rep=single");
5624 else if (MultipleArg)
5625 CmdArgs.push_back("-fms-memptr-rep=multiple");
5626 else
5627 CmdArgs.push_back("-fms-memptr-rep=virtual");
5628 }
5629
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005630 // Parse the default calling convention options.
5631 if (Arg *CCArg =
5632 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005633 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5634 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005635 unsigned DCCOptId = CCArg->getOption().getID();
5636 const char *DCCFlag = nullptr;
5637 bool ArchSupported = true;
5638 llvm::Triple::ArchType Arch = getToolChain().getArch();
5639 switch (DCCOptId) {
5640 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005641 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005642 break;
5643 case options::OPT__SLASH_Gr:
5644 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005645 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005646 break;
5647 case options::OPT__SLASH_Gz:
5648 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005649 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005650 break;
5651 case options::OPT__SLASH_Gv:
5652 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005653 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005654 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005655 case options::OPT__SLASH_Gregcall:
5656 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5657 DCCFlag = "-fdefault-calling-conv=regcall";
5658 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005659 }
5660
5661 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5662 if (ArchSupported && DCCFlag)
5663 CmdArgs.push_back(DCCFlag);
5664 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005665
5666 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5667 A->render(Args, CmdArgs);
5668
5669 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5670 CmdArgs.push_back("-fdiagnostics-format");
5671 if (Args.hasArg(options::OPT__SLASH_fallback))
5672 CmdArgs.push_back("msvc-fallback");
5673 else
5674 CmdArgs.push_back("msvc");
5675 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005676
Hans Wennborga912e3e2018-08-10 09:49:21 +00005677 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5678 SmallVector<StringRef, 1> SplitArgs;
5679 StringRef(A->getValue()).split(SplitArgs, ",");
5680 bool Instrument = false;
5681 bool NoChecks = false;
5682 for (StringRef Arg : SplitArgs) {
5683 if (Arg.equals_lower("cf"))
5684 Instrument = true;
5685 else if (Arg.equals_lower("cf-"))
5686 Instrument = false;
5687 else if (Arg.equals_lower("nochecks"))
5688 NoChecks = true;
5689 else if (Arg.equals_lower("nochecks-"))
5690 NoChecks = false;
5691 else
5692 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5693 }
5694 // Currently there's no support emitting CFG instrumentation; the flag only
5695 // emits the table of address-taken functions.
5696 if (Instrument || NoChecks)
5697 CmdArgs.push_back("-cfguard");
5698 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005699}
5700
5701visualstudio::Compiler *Clang::getCLFallback() const {
5702 if (!CLFallback)
5703 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5704 return CLFallback.get();
5705}
5706
5707
5708const char *Clang::getBaseInputName(const ArgList &Args,
5709 const InputInfo &Input) {
5710 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5711}
5712
5713const char *Clang::getBaseInputStem(const ArgList &Args,
5714 const InputInfoList &Inputs) {
5715 const char *Str = getBaseInputName(Args, Inputs[0]);
5716
5717 if (const char *End = strrchr(Str, '.'))
5718 return Args.MakeArgString(std::string(Str, End));
5719
5720 return Str;
5721}
5722
5723const char *Clang::getDependencyFileName(const ArgList &Args,
5724 const InputInfoList &Inputs) {
5725 // FIXME: Think about this more.
5726 std::string Res;
5727
5728 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5729 std::string Str(OutputOpt->getValue());
5730 Res = Str.substr(0, Str.rfind('.'));
5731 } else {
5732 Res = getBaseInputStem(Args, Inputs);
5733 }
5734 return Args.MakeArgString(Res + ".d");
5735}
5736
5737// Begin ClangAs
5738
5739void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5740 ArgStringList &CmdArgs) const {
5741 StringRef CPUName;
5742 StringRef ABIName;
5743 const llvm::Triple &Triple = getToolChain().getTriple();
5744 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5745
5746 CmdArgs.push_back("-target-abi");
5747 CmdArgs.push_back(ABIName.data());
5748}
5749
5750void ClangAs::AddX86TargetArgs(const ArgList &Args,
5751 ArgStringList &CmdArgs) const {
5752 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5753 StringRef Value = A->getValue();
5754 if (Value == "intel" || Value == "att") {
5755 CmdArgs.push_back("-mllvm");
5756 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5757 } else {
5758 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5759 << A->getOption().getName() << Value;
5760 }
5761 }
5762}
5763
5764void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5765 const InputInfo &Output, const InputInfoList &Inputs,
5766 const ArgList &Args,
5767 const char *LinkingOutput) const {
5768 ArgStringList CmdArgs;
5769
5770 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5771 const InputInfo &Input = Inputs[0];
5772
Martin Storsjob547ef22018-10-26 08:33:29 +00005773 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00005774 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00005775 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005776
5777 // Don't warn about "clang -w -c foo.s"
5778 Args.ClaimAllArgs(options::OPT_w);
5779 // and "clang -emit-llvm -c foo.s"
5780 Args.ClaimAllArgs(options::OPT_emit_llvm);
5781
5782 claimNoWarnArgs(Args);
5783
5784 // Invoke ourselves in -cc1as mode.
5785 //
5786 // FIXME: Implement custom jobs for internal actions.
5787 CmdArgs.push_back("-cc1as");
5788
5789 // Add the "effective" target triple.
5790 CmdArgs.push_back("-triple");
5791 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5792
5793 // Set the output mode, we currently only expect to be used as a real
5794 // assembler.
5795 CmdArgs.push_back("-filetype");
5796 CmdArgs.push_back("obj");
5797
5798 // Set the main file name, so that debug info works even with
5799 // -save-temps or preprocessed assembly.
5800 CmdArgs.push_back("-main-file-name");
5801 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5802
5803 // Add the target cpu
5804 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5805 if (!CPU.empty()) {
5806 CmdArgs.push_back("-target-cpu");
5807 CmdArgs.push_back(Args.MakeArgString(CPU));
5808 }
5809
5810 // Add the target features
5811 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5812
5813 // Ignore explicit -force_cpusubtype_ALL option.
5814 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5815
5816 // Pass along any -I options so we get proper .include search paths.
5817 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5818
5819 // Determine the original source input.
5820 const Action *SourceAction = &JA;
5821 while (SourceAction->getKind() != Action::InputClass) {
5822 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5823 SourceAction = SourceAction->getInputs()[0];
5824 }
5825
5826 // Forward -g and handle debug info related flags, assuming we are dealing
5827 // with an actual assembly file.
5828 bool WantDebug = false;
5829 unsigned DwarfVersion = 0;
5830 Args.ClaimAllArgs(options::OPT_g_Group);
5831 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5832 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5833 !A->getOption().matches(options::OPT_ggdb0);
5834 if (WantDebug)
5835 DwarfVersion = DwarfVersionNum(A->getSpelling());
5836 }
5837 if (DwarfVersion == 0)
5838 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5839
5840 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5841
5842 if (SourceAction->getType() == types::TY_Asm ||
5843 SourceAction->getType() == types::TY_PP_Asm) {
5844 // You might think that it would be ok to set DebugInfoKind outside of
5845 // the guard for source type, however there is a test which asserts
5846 // that some assembler invocation receives no -debug-info-kind,
5847 // and it's not clear whether that test is just overly restrictive.
5848 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5849 : codegenoptions::NoDebugInfo);
5850 // Add the -fdebug-compilation-dir flag if needed.
5851 addDebugCompDirArg(Args, CmdArgs);
5852
Paul Robinson9b292b42018-07-10 15:15:24 +00005853 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5854
David L. Jonesf561aba2017-03-08 01:02:16 +00005855 // Set the AT_producer to the clang version when using the integrated
5856 // assembler on assembly source files.
5857 CmdArgs.push_back("-dwarf-debug-producer");
5858 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5859
5860 // And pass along -I options
5861 Args.AddAllArgs(CmdArgs, options::OPT_I);
5862 }
5863 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5864 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00005865 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005866
David L. Jonesf561aba2017-03-08 01:02:16 +00005867
5868 // Handle -fPIC et al -- the relocation-model affects the assembler
5869 // for some targets.
5870 llvm::Reloc::Model RelocationModel;
5871 unsigned PICLevel;
5872 bool IsPIE;
5873 std::tie(RelocationModel, PICLevel, IsPIE) =
5874 ParsePICArgs(getToolChain(), Args);
5875
5876 const char *RMName = RelocationModelName(RelocationModel);
5877 if (RMName) {
5878 CmdArgs.push_back("-mrelocation-model");
5879 CmdArgs.push_back(RMName);
5880 }
5881
5882 // Optionally embed the -cc1as level arguments into the debug info, for build
5883 // analysis.
5884 if (getToolChain().UseDwarfDebugFlags()) {
5885 ArgStringList OriginalArgs;
5886 for (const auto &Arg : Args)
5887 Arg->render(Args, OriginalArgs);
5888
5889 SmallString<256> Flags;
5890 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5891 Flags += Exec;
5892 for (const char *OriginalArg : OriginalArgs) {
5893 SmallString<128> EscapedArg;
5894 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5895 Flags += " ";
5896 Flags += EscapedArg;
5897 }
5898 CmdArgs.push_back("-dwarf-debug-flags");
5899 CmdArgs.push_back(Args.MakeArgString(Flags));
5900 }
5901
5902 // FIXME: Add -static support, once we have it.
5903
5904 // Add target specific flags.
5905 switch (getToolChain().getArch()) {
5906 default:
5907 break;
5908
5909 case llvm::Triple::mips:
5910 case llvm::Triple::mipsel:
5911 case llvm::Triple::mips64:
5912 case llvm::Triple::mips64el:
5913 AddMIPSTargetArgs(Args, CmdArgs);
5914 break;
5915
5916 case llvm::Triple::x86:
5917 case llvm::Triple::x86_64:
5918 AddX86TargetArgs(Args, CmdArgs);
5919 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005920
5921 case llvm::Triple::arm:
5922 case llvm::Triple::armeb:
5923 case llvm::Triple::thumb:
5924 case llvm::Triple::thumbeb:
5925 // This isn't in AddARMTargetArgs because we want to do this for assembly
5926 // only, not C/C++.
5927 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5928 options::OPT_mno_default_build_attributes, true)) {
5929 CmdArgs.push_back("-mllvm");
5930 CmdArgs.push_back("-arm-add-build-attributes");
5931 }
5932 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005933 }
5934
5935 // Consume all the warning flags. Usually this would be handled more
5936 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5937 // doesn't handle that so rather than warning about unused flags that are
5938 // actually used, we'll lie by omission instead.
5939 // FIXME: Stop lying and consume only the appropriate driver flags
5940 Args.ClaimAllArgs(options::OPT_W_Group);
5941
5942 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5943 getToolChain().getDriver());
5944
5945 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5946
5947 assert(Output.isFilename() && "Unexpected lipo output.");
5948 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00005949 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00005950
Petr Hosekd3265352018-10-15 21:30:32 +00005951 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00005952 Arg *A;
5953 if ((getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split) &&
Petr Hosekd3265352018-10-15 21:30:32 +00005954 (T.isOSLinux() || T.isOSFuchsia())) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00005955 CmdArgs.push_back("-split-dwarf-file");
George Rimarab090332018-12-05 11:09:10 +00005956 CmdArgs.push_back(SplitDebugName(Args, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00005957 }
5958
David L. Jonesf561aba2017-03-08 01:02:16 +00005959 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00005960 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00005961
5962 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5963 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005964}
5965
5966// Begin OffloadBundler
5967
5968void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5969 const InputInfo &Output,
5970 const InputInfoList &Inputs,
5971 const llvm::opt::ArgList &TCArgs,
5972 const char *LinkingOutput) const {
5973 // The version with only one output is expected to refer to a bundling job.
5974 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5975
5976 // The bundling command looks like this:
5977 // clang-offload-bundler -type=bc
5978 // -targets=host-triple,openmp-triple1,openmp-triple2
5979 // -outputs=input_file
5980 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5981
5982 ArgStringList CmdArgs;
5983
5984 // Get the type.
5985 CmdArgs.push_back(TCArgs.MakeArgString(
5986 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5987
5988 assert(JA.getInputs().size() == Inputs.size() &&
5989 "Not have inputs for all dependence actions??");
5990
5991 // Get the targets.
5992 SmallString<128> Triples;
5993 Triples += "-targets=";
5994 for (unsigned I = 0; I < Inputs.size(); ++I) {
5995 if (I)
5996 Triples += ',';
5997
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005998 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005999 Action::OffloadKind CurKind = Action::OFK_Host;
6000 const ToolChain *CurTC = &getToolChain();
6001 const Action *CurDep = JA.getInputs()[I];
6002
6003 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006004 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006005 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006006 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006007 CurKind = A->getOffloadingDeviceKind();
6008 CurTC = TC;
6009 });
6010 }
6011 Triples += Action::GetOffloadKindName(CurKind);
6012 Triples += '-';
6013 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006014 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6015 Triples += '-';
6016 Triples += CurDep->getOffloadingArch();
6017 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006018 }
6019 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6020
6021 // Get bundled file command.
6022 CmdArgs.push_back(
6023 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6024
6025 // Get unbundled files command.
6026 SmallString<128> UB;
6027 UB += "-inputs=";
6028 for (unsigned I = 0; I < Inputs.size(); ++I) {
6029 if (I)
6030 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006031
6032 // Find ToolChain for this input.
6033 const ToolChain *CurTC = &getToolChain();
6034 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6035 CurTC = nullptr;
6036 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6037 assert(CurTC == nullptr && "Expected one dependence!");
6038 CurTC = TC;
6039 });
6040 }
6041 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006042 }
6043 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6044
6045 // All the inputs are encoded as commands.
6046 C.addCommand(llvm::make_unique<Command>(
6047 JA, *this,
6048 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6049 CmdArgs, None));
6050}
6051
6052void OffloadBundler::ConstructJobMultipleOutputs(
6053 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6054 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6055 const char *LinkingOutput) const {
6056 // The version with multiple outputs is expected to refer to a unbundling job.
6057 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6058
6059 // The unbundling command looks like this:
6060 // clang-offload-bundler -type=bc
6061 // -targets=host-triple,openmp-triple1,openmp-triple2
6062 // -inputs=input_file
6063 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6064 // -unbundle
6065
6066 ArgStringList CmdArgs;
6067
6068 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6069 InputInfo Input = Inputs.front();
6070
6071 // Get the type.
6072 CmdArgs.push_back(TCArgs.MakeArgString(
6073 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6074
6075 // Get the targets.
6076 SmallString<128> Triples;
6077 Triples += "-targets=";
6078 auto DepInfo = UA.getDependentActionsInfo();
6079 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6080 if (I)
6081 Triples += ',';
6082
6083 auto &Dep = DepInfo[I];
6084 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6085 Triples += '-';
6086 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006087 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6088 !Dep.DependentBoundArch.empty()) {
6089 Triples += '-';
6090 Triples += Dep.DependentBoundArch;
6091 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006092 }
6093
6094 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6095
6096 // Get bundled file command.
6097 CmdArgs.push_back(
6098 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6099
6100 // Get unbundled files command.
6101 SmallString<128> UB;
6102 UB += "-outputs=";
6103 for (unsigned I = 0; I < Outputs.size(); ++I) {
6104 if (I)
6105 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006106 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006107 }
6108 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6109 CmdArgs.push_back("-unbundle");
6110
6111 // All the inputs are encoded as commands.
6112 C.addCommand(llvm::make_unique<Command>(
6113 JA, *this,
6114 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6115 CmdArgs, None));
6116}