blob: e7b15c7ad820d9b11877a53f31e1de99a4317624 [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;
496 return codegenoptions::LimitedDebugInfo;
497}
498
499static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
500 switch (Triple.getArch()){
501 default:
502 return false;
503 case llvm::Triple::arm:
504 case llvm::Triple::thumb:
505 // ARM Darwin targets require a frame pointer to be always present to aid
506 // offline debugging via backtraces.
507 return Triple.isOSDarwin();
508 }
509}
510
511static bool useFramePointerForTargetByDefault(const ArgList &Args,
512 const llvm::Triple &Triple) {
513 switch (Triple.getArch()) {
514 case llvm::Triple::xcore:
515 case llvm::Triple::wasm32:
516 case llvm::Triple::wasm64:
517 // XCore never wants frame pointers, regardless of OS.
518 // WebAssembly never wants frame pointers.
519 return false;
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000520 case llvm::Triple::riscv32:
521 case llvm::Triple::riscv64:
522 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000523 default:
524 break;
525 }
526
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000527 if (Triple.getOS() == llvm::Triple::NetBSD) {
528 return !areOptimizationsEnabled(Args);
529 }
530
David L. Jonesf561aba2017-03-08 01:02:16 +0000531 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
532 switch (Triple.getArch()) {
533 // Don't use a frame pointer on linux if optimizing for certain targets.
534 case llvm::Triple::mips64:
535 case llvm::Triple::mips64el:
536 case llvm::Triple::mips:
537 case llvm::Triple::mipsel:
538 case llvm::Triple::ppc:
539 case llvm::Triple::ppc64:
540 case llvm::Triple::ppc64le:
541 case llvm::Triple::systemz:
542 case llvm::Triple::x86:
543 case llvm::Triple::x86_64:
544 return !areOptimizationsEnabled(Args);
545 default:
546 return true;
547 }
548 }
549
550 if (Triple.isOSWindows()) {
551 switch (Triple.getArch()) {
552 case llvm::Triple::x86:
553 return !areOptimizationsEnabled(Args);
554 case llvm::Triple::x86_64:
555 return Triple.isOSBinFormatMachO();
556 case llvm::Triple::arm:
557 case llvm::Triple::thumb:
558 // Windows on ARM builds with FPO disabled to aid fast stack walking
559 return true;
560 default:
561 // All other supported Windows ISAs use xdata unwind information, so frame
562 // pointers are not generally useful.
563 return false;
564 }
565 }
566
567 return true;
568}
569
570static bool shouldUseFramePointer(const ArgList &Args,
571 const llvm::Triple &Triple) {
572 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
573 options::OPT_fomit_frame_pointer))
574 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
575 mustUseNonLeafFramePointerForTarget(Triple);
576
577 if (Args.hasArg(options::OPT_pg))
578 return true;
579
580 return useFramePointerForTargetByDefault(Args, Triple);
581}
582
583static bool shouldUseLeafFramePointer(const ArgList &Args,
584 const llvm::Triple &Triple) {
585 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
586 options::OPT_momit_leaf_frame_pointer))
587 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
588
589 if (Args.hasArg(options::OPT_pg))
590 return true;
591
592 if (Triple.isPS4CPU())
593 return false;
594
595 return useFramePointerForTargetByDefault(Args, Triple);
596}
597
598/// Add a CC1 option to specify the debug compilation directory.
599static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
600 SmallString<128> cwd;
601 if (!llvm::sys::fs::current_path(cwd)) {
602 CmdArgs.push_back("-fdebug-compilation-dir");
603 CmdArgs.push_back(Args.MakeArgString(cwd));
604 }
605}
606
Paul Robinson9b292b42018-07-10 15:15:24 +0000607/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
608static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
609 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
610 StringRef Map = A->getValue();
611 if (Map.find('=') == StringRef::npos)
612 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
613 else
614 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
615 A->claim();
616 }
617}
618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000619/// Vectorize at all optimization levels greater than 1 except for -Oz.
David L. Jonesf561aba2017-03-08 01:02:16 +0000620/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
621static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
622 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
623 if (A->getOption().matches(options::OPT_O4) ||
624 A->getOption().matches(options::OPT_Ofast))
625 return true;
626
627 if (A->getOption().matches(options::OPT_O0))
628 return false;
629
630 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
631
632 // Vectorize -Os.
633 StringRef S(A->getValue());
634 if (S == "s")
635 return true;
636
637 // Don't vectorize -Oz, unless it's the slp vectorizer.
638 if (S == "z")
639 return isSlpVec;
640
641 unsigned OptLevel = 0;
642 if (S.getAsInteger(10, OptLevel))
643 return false;
644
645 return OptLevel > 1;
646 }
647
648 return false;
649}
650
651/// Add -x lang to \p CmdArgs for \p Input.
652static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
653 ArgStringList &CmdArgs) {
654 // When using -verify-pch, we don't want to provide the type
655 // 'precompiled-header' if it was inferred from the file extension
656 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
657 return;
658
659 CmdArgs.push_back("-x");
660 if (Args.hasArg(options::OPT_rewrite_objc))
661 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000662 else {
663 // Map the driver type to the frontend type. This is mostly an identity
664 // mapping, except that the distinction between module interface units
665 // and other source files does not exist at the frontend layer.
666 const char *ClangType;
667 switch (Input.getType()) {
668 case types::TY_CXXModule:
669 ClangType = "c++";
670 break;
671 case types::TY_PP_CXXModule:
672 ClangType = "c++-cpp-output";
673 break;
674 default:
675 ClangType = types::getTypeName(Input.getType());
676 break;
677 }
678 CmdArgs.push_back(ClangType);
679 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000680}
681
682static void appendUserToPath(SmallVectorImpl<char> &Result) {
683#ifdef LLVM_ON_UNIX
684 const char *Username = getenv("LOGNAME");
685#else
686 const char *Username = getenv("USERNAME");
687#endif
688 if (Username) {
689 // Validate that LoginName can be used in a path, and get its length.
690 size_t Len = 0;
691 for (const char *P = Username; *P; ++P, ++Len) {
692 if (!clang::isAlphanumeric(*P) && *P != '_') {
693 Username = nullptr;
694 break;
695 }
696 }
697
698 if (Username && Len > 0) {
699 Result.append(Username, Username + Len);
700 return;
701 }
702 }
703
704// Fallback to user id.
705#ifdef LLVM_ON_UNIX
706 std::string UID = llvm::utostr(getuid());
707#else
708 // FIXME: Windows seems to have an 'SID' that might work.
709 std::string UID = "9999";
710#endif
711 Result.append(UID.begin(), UID.end());
712}
713
714static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
715 const InputInfo &Output, const ArgList &Args,
716 ArgStringList &CmdArgs) {
717
718 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
719 options::OPT_fprofile_generate_EQ,
720 options::OPT_fno_profile_generate);
721 if (PGOGenerateArg &&
722 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
723 PGOGenerateArg = nullptr;
724
725 auto *ProfileGenerateArg = Args.getLastArg(
726 options::OPT_fprofile_instr_generate,
727 options::OPT_fprofile_instr_generate_EQ,
728 options::OPT_fno_profile_instr_generate);
729 if (ProfileGenerateArg &&
730 ProfileGenerateArg->getOption().matches(
731 options::OPT_fno_profile_instr_generate))
732 ProfileGenerateArg = nullptr;
733
734 if (PGOGenerateArg && ProfileGenerateArg)
735 D.Diag(diag::err_drv_argument_not_allowed_with)
736 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
737
738 auto *ProfileUseArg = getLastProfileUseArg(Args);
739
740 if (PGOGenerateArg && ProfileUseArg)
741 D.Diag(diag::err_drv_argument_not_allowed_with)
742 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
743
744 if (ProfileGenerateArg && ProfileUseArg)
745 D.Diag(diag::err_drv_argument_not_allowed_with)
746 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
747
748 if (ProfileGenerateArg) {
749 if (ProfileGenerateArg->getOption().matches(
750 options::OPT_fprofile_instr_generate_EQ))
751 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
752 ProfileGenerateArg->getValue()));
753 // The default is to use Clang Instrumentation.
754 CmdArgs.push_back("-fprofile-instrument=clang");
755 }
756
757 if (PGOGenerateArg) {
758 CmdArgs.push_back("-fprofile-instrument=llvm");
759 if (PGOGenerateArg->getOption().matches(
760 options::OPT_fprofile_generate_EQ)) {
761 SmallString<128> Path(PGOGenerateArg->getValue());
762 llvm::sys::path::append(Path, "default_%m.profraw");
763 CmdArgs.push_back(
764 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
765 }
766 }
767
768 if (ProfileUseArg) {
769 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
770 CmdArgs.push_back(Args.MakeArgString(
771 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
772 else if ((ProfileUseArg->getOption().matches(
773 options::OPT_fprofile_use_EQ) ||
774 ProfileUseArg->getOption().matches(
775 options::OPT_fprofile_instr_use))) {
776 SmallString<128> Path(
777 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
778 if (Path.empty() || llvm::sys::fs::is_directory(Path))
779 llvm::sys::path::append(Path, "default.profdata");
780 CmdArgs.push_back(
781 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
782 }
783 }
784
785 if (Args.hasArg(options::OPT_ftest_coverage) ||
786 Args.hasArg(options::OPT_coverage))
787 CmdArgs.push_back("-femit-coverage-notes");
788 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
789 false) ||
790 Args.hasArg(options::OPT_coverage))
791 CmdArgs.push_back("-femit-coverage-data");
792
793 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000794 options::OPT_fno_coverage_mapping, false)) {
795 if (!ProfileGenerateArg)
796 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
797 << "-fcoverage-mapping"
798 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000799
David L. Jonesf561aba2017-03-08 01:02:16 +0000800 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000801 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000802
803 if (C.getArgs().hasArg(options::OPT_c) ||
804 C.getArgs().hasArg(options::OPT_S)) {
805 if (Output.isFilename()) {
806 CmdArgs.push_back("-coverage-notes-file");
807 SmallString<128> OutputFilename;
808 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
809 OutputFilename = FinalOutput->getValue();
810 else
811 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
812 SmallString<128> CoverageFilename = OutputFilename;
813 if (llvm::sys::path::is_relative(CoverageFilename)) {
814 SmallString<128> Pwd;
815 if (!llvm::sys::fs::current_path(Pwd)) {
816 llvm::sys::path::append(Pwd, CoverageFilename);
817 CoverageFilename.swap(Pwd);
818 }
819 }
820 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
821 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
822
823 // Leave -fprofile-dir= an unused argument unless .gcda emission is
824 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
825 // the flag used. There is no -fno-profile-dir, so the user has no
826 // targeted way to suppress the warning.
827 if (Args.hasArg(options::OPT_fprofile_arcs) ||
828 Args.hasArg(options::OPT_coverage)) {
829 CmdArgs.push_back("-coverage-data-file");
830 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
831 CoverageFilename = FProfileDir->getValue();
832 llvm::sys::path::append(CoverageFilename, OutputFilename);
833 }
834 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
835 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
836 }
837 }
838 }
839}
840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000841/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000842static bool ContainsCompileAction(const Action *A) {
843 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
844 return true;
845
846 for (const auto &AI : A->inputs())
847 if (ContainsCompileAction(AI))
848 return true;
849
850 return false;
851}
852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000853/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000854/// This is done by default when compiling non-assembler source with -O0.
855static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
856 bool RelaxDefault = true;
857
858 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
859 RelaxDefault = A->getOption().matches(options::OPT_O0);
860
861 if (RelaxDefault) {
862 RelaxDefault = false;
863 for (const auto &Act : C.getActions()) {
864 if (ContainsCompileAction(Act)) {
865 RelaxDefault = true;
866 break;
867 }
868 }
869 }
870
871 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
872 RelaxDefault);
873}
874
875// Extract the integer N from a string spelled "-dwarf-N", returning 0
876// on mismatch. The StringRef input (rather than an Arg) allows
877// for use by the "-Xassembler" option parser.
878static unsigned DwarfVersionNum(StringRef ArgValue) {
879 return llvm::StringSwitch<unsigned>(ArgValue)
880 .Case("-gdwarf-2", 2)
881 .Case("-gdwarf-3", 3)
882 .Case("-gdwarf-4", 4)
883 .Case("-gdwarf-5", 5)
884 .Default(0);
885}
886
887static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
888 codegenoptions::DebugInfoKind DebugInfoKind,
889 unsigned DwarfVersion,
890 llvm::DebuggerKind DebuggerTuning) {
891 switch (DebugInfoKind) {
892 case codegenoptions::DebugLineTablesOnly:
893 CmdArgs.push_back("-debug-info-kind=line-tables-only");
894 break;
895 case codegenoptions::LimitedDebugInfo:
896 CmdArgs.push_back("-debug-info-kind=limited");
897 break;
898 case codegenoptions::FullDebugInfo:
899 CmdArgs.push_back("-debug-info-kind=standalone");
900 break;
901 default:
902 break;
903 }
904 if (DwarfVersion > 0)
905 CmdArgs.push_back(
906 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
907 switch (DebuggerTuning) {
908 case llvm::DebuggerKind::GDB:
909 CmdArgs.push_back("-debugger-tuning=gdb");
910 break;
911 case llvm::DebuggerKind::LLDB:
912 CmdArgs.push_back("-debugger-tuning=lldb");
913 break;
914 case llvm::DebuggerKind::SCE:
915 CmdArgs.push_back("-debugger-tuning=sce");
916 break;
917 default:
918 break;
919 }
920}
921
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000922static void RenderDebugInfoCompressionArgs(const ArgList &Args,
923 ArgStringList &CmdArgs,
924 const Driver &D) {
925 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
926 if (!A)
927 return;
928
929 if (A->getOption().getID() == options::OPT_gz) {
930 if (llvm::zlib::isAvailable())
931 CmdArgs.push_back("-compress-debug-sections");
932 else
933 D.Diag(diag::warn_debug_compression_unavailable);
934 return;
935 }
936
937 StringRef Value = A->getValue();
938 if (Value == "none") {
939 CmdArgs.push_back("-compress-debug-sections=none");
940 } else if (Value == "zlib" || Value == "zlib-gnu") {
941 if (llvm::zlib::isAvailable()) {
942 CmdArgs.push_back(
943 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
944 } else {
945 D.Diag(diag::warn_debug_compression_unavailable);
946 }
947 } else {
948 D.Diag(diag::err_drv_unsupported_option_argument)
949 << A->getOption().getName() << Value;
950 }
951}
952
David L. Jonesf561aba2017-03-08 01:02:16 +0000953static const char *RelocationModelName(llvm::Reloc::Model Model) {
954 switch (Model) {
955 case llvm::Reloc::Static:
956 return "static";
957 case llvm::Reloc::PIC_:
958 return "pic";
959 case llvm::Reloc::DynamicNoPIC:
960 return "dynamic-no-pic";
961 case llvm::Reloc::ROPI:
962 return "ropi";
963 case llvm::Reloc::RWPI:
964 return "rwpi";
965 case llvm::Reloc::ROPI_RWPI:
966 return "ropi-rwpi";
967 }
968 llvm_unreachable("Unknown Reloc::Model kind");
969}
970
971void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
972 const Driver &D, const ArgList &Args,
973 ArgStringList &CmdArgs,
974 const InputInfo &Output,
975 const InputInfoList &Inputs) const {
976 Arg *A;
977 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
978
979 CheckPreprocessingOptions(D, Args);
980
981 Args.AddLastArg(CmdArgs, options::OPT_C);
982 Args.AddLastArg(CmdArgs, options::OPT_CC);
983
984 // Handle dependency file generation.
985 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
986 (A = Args.getLastArg(options::OPT_MD)) ||
987 (A = Args.getLastArg(options::OPT_MMD))) {
988 // Determine the output location.
989 const char *DepFile;
990 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
991 DepFile = MF->getValue();
992 C.addFailureResultFile(DepFile, &JA);
993 } else if (Output.getType() == types::TY_Dependencies) {
994 DepFile = Output.getFilename();
995 } else if (A->getOption().matches(options::OPT_M) ||
996 A->getOption().matches(options::OPT_MM)) {
997 DepFile = "-";
998 } else {
999 DepFile = getDependencyFileName(Args, Inputs);
1000 C.addFailureResultFile(DepFile, &JA);
1001 }
1002 CmdArgs.push_back("-dependency-file");
1003 CmdArgs.push_back(DepFile);
1004
1005 // Add a default target if one wasn't specified.
1006 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1007 const char *DepTarget;
1008
1009 // If user provided -o, that is the dependency target, except
1010 // when we are only generating a dependency file.
1011 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1012 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1013 DepTarget = OutputOpt->getValue();
1014 } else {
1015 // Otherwise derive from the base input.
1016 //
1017 // FIXME: This should use the computed output file location.
1018 SmallString<128> P(Inputs[0].getBaseInput());
1019 llvm::sys::path::replace_extension(P, "o");
1020 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1021 }
1022
Yuka Takahashicdb53482017-06-16 16:01:13 +00001023 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1024 CmdArgs.push_back("-w");
1025 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001026 CmdArgs.push_back("-MT");
1027 SmallString<128> Quoted;
1028 QuoteTarget(DepTarget, Quoted);
1029 CmdArgs.push_back(Args.MakeArgString(Quoted));
1030 }
1031
1032 if (A->getOption().matches(options::OPT_M) ||
1033 A->getOption().matches(options::OPT_MD))
1034 CmdArgs.push_back("-sys-header-deps");
1035 if ((isa<PrecompileJobAction>(JA) &&
1036 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1037 Args.hasArg(options::OPT_fmodule_file_deps))
1038 CmdArgs.push_back("-module-file-deps");
1039 }
1040
1041 if (Args.hasArg(options::OPT_MG)) {
1042 if (!A || A->getOption().matches(options::OPT_MD) ||
1043 A->getOption().matches(options::OPT_MMD))
1044 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1045 CmdArgs.push_back("-MG");
1046 }
1047
1048 Args.AddLastArg(CmdArgs, options::OPT_MP);
1049 Args.AddLastArg(CmdArgs, options::OPT_MV);
1050
1051 // Convert all -MQ <target> args to -MT <quoted target>
1052 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1053 A->claim();
1054
1055 if (A->getOption().matches(options::OPT_MQ)) {
1056 CmdArgs.push_back("-MT");
1057 SmallString<128> Quoted;
1058 QuoteTarget(A->getValue(), Quoted);
1059 CmdArgs.push_back(Args.MakeArgString(Quoted));
1060
1061 // -MT flag - no change
1062 } else {
1063 A->render(Args, CmdArgs);
1064 }
1065 }
1066
1067 // Add offload include arguments specific for CUDA. This must happen before
1068 // we -I or -include anything else, because we must pick up the CUDA headers
1069 // from the particular CUDA installation, rather than from e.g.
1070 // /usr/local/include.
1071 if (JA.isOffloading(Action::OFK_Cuda))
1072 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1073
1074 // Add -i* options, and automatically translate to
1075 // -include-pch/-include-pth for transparent PCH support. It's
1076 // wonky, but we include looking for .gch so we can support seamless
1077 // replacement into a build system already set up to be generating
1078 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001079
1080 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001081 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1082 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001083 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1084 JA.getKind() <= Action::AssembleJobClass) {
1085 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001086 }
Erich Keane76675de2018-07-05 17:22:13 +00001087 if (YcArg || YuArg) {
1088 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1089 if (!isa<PrecompileJobAction>(JA)) {
1090 CmdArgs.push_back("-include-pch");
1091 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(C, ThroughHeader)));
1092 }
1093 CmdArgs.push_back(
1094 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1095 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001096 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001097
1098 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001099 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001100 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001101 // Handling of gcc-style gch precompiled headers.
1102 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1103 RenderedImplicitInclude = true;
1104
1105 // Use PCH if the user requested it.
1106 bool UsePCH = D.CCCUsePCH;
1107
1108 bool FoundPTH = false;
1109 bool FoundPCH = false;
1110 SmallString<128> P(A->getValue());
1111 // We want the files to have a name like foo.h.pch. Add a dummy extension
1112 // so that replace_extension does the right thing.
1113 P += ".dummy";
1114 if (UsePCH) {
1115 llvm::sys::path::replace_extension(P, "pch");
1116 if (llvm::sys::fs::exists(P))
1117 FoundPCH = true;
1118 }
1119
1120 if (!FoundPCH) {
1121 llvm::sys::path::replace_extension(P, "pth");
1122 if (llvm::sys::fs::exists(P))
1123 FoundPTH = true;
1124 }
1125
1126 if (!FoundPCH && !FoundPTH) {
1127 llvm::sys::path::replace_extension(P, "gch");
1128 if (llvm::sys::fs::exists(P)) {
1129 FoundPCH = UsePCH;
1130 FoundPTH = !UsePCH;
1131 }
1132 }
1133
1134 if (FoundPCH || FoundPTH) {
1135 if (IsFirstImplicitInclude) {
1136 A->claim();
1137 if (UsePCH)
1138 CmdArgs.push_back("-include-pch");
1139 else
1140 CmdArgs.push_back("-include-pth");
1141 CmdArgs.push_back(Args.MakeArgString(P));
1142 continue;
1143 } else {
1144 // Ignore the PCH if not first on command line and emit warning.
1145 D.Diag(diag::warn_drv_pch_not_first_include) << P
1146 << A->getAsString(Args);
1147 }
1148 }
1149 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1150 // Handling of paths which must come late. These entries are handled by
1151 // the toolchain itself after the resource dir is inserted in the right
1152 // search order.
1153 // Do not claim the argument so that the use of the argument does not
1154 // silently go unnoticed on toolchains which do not honour the option.
1155 continue;
1156 }
1157
1158 // Not translated, render as usual.
1159 A->claim();
1160 A->render(Args, CmdArgs);
1161 }
1162
1163 Args.AddAllArgs(CmdArgs,
1164 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1165 options::OPT_F, options::OPT_index_header_map});
1166
1167 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1168
1169 // FIXME: There is a very unfortunate problem here, some troubled
1170 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1171 // really support that we would have to parse and then translate
1172 // those options. :(
1173 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1174 options::OPT_Xpreprocessor);
1175
1176 // -I- is a deprecated GCC feature, reject it.
1177 if (Arg *A = Args.getLastArg(options::OPT_I_))
1178 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1179
1180 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1181 // -isysroot to the CC1 invocation.
1182 StringRef sysroot = C.getSysRoot();
1183 if (sysroot != "") {
1184 if (!Args.hasArg(options::OPT_isysroot)) {
1185 CmdArgs.push_back("-isysroot");
1186 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1187 }
1188 }
1189
1190 // Parse additional include paths from environment variables.
1191 // FIXME: We should probably sink the logic for handling these from the
1192 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1193 // CPATH - included following the user specified includes (but prior to
1194 // builtin and standard includes).
1195 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1196 // C_INCLUDE_PATH - system includes enabled when compiling C.
1197 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1198 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1199 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1200 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1201 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1202 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1203 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1204
1205 // While adding the include arguments, we also attempt to retrieve the
1206 // arguments of related offloading toolchains or arguments that are specific
1207 // of an offloading programming model.
1208
1209 // Add C++ include arguments, if needed.
1210 if (types::isCXX(Inputs[0].getType()))
1211 forAllAssociatedToolChains(C, JA, getToolChain(),
1212 [&Args, &CmdArgs](const ToolChain &TC) {
1213 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1214 });
1215
1216 // Add system include arguments for all targets but IAMCU.
1217 if (!IsIAMCU)
1218 forAllAssociatedToolChains(C, JA, getToolChain(),
1219 [&Args, &CmdArgs](const ToolChain &TC) {
1220 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1221 });
1222 else {
1223 // For IAMCU add special include arguments.
1224 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1225 }
1226}
1227
1228// FIXME: Move to target hook.
1229static bool isSignedCharDefault(const llvm::Triple &Triple) {
1230 switch (Triple.getArch()) {
1231 default:
1232 return true;
1233
1234 case llvm::Triple::aarch64:
1235 case llvm::Triple::aarch64_be:
1236 case llvm::Triple::arm:
1237 case llvm::Triple::armeb:
1238 case llvm::Triple::thumb:
1239 case llvm::Triple::thumbeb:
1240 if (Triple.isOSDarwin() || Triple.isOSWindows())
1241 return true;
1242 return false;
1243
1244 case llvm::Triple::ppc:
1245 case llvm::Triple::ppc64:
1246 if (Triple.isOSDarwin())
1247 return true;
1248 return false;
1249
1250 case llvm::Triple::hexagon:
1251 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001252 case llvm::Triple::riscv32:
1253 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001254 case llvm::Triple::systemz:
1255 case llvm::Triple::xcore:
1256 return false;
1257 }
1258}
1259
1260static bool isNoCommonDefault(const llvm::Triple &Triple) {
1261 switch (Triple.getArch()) {
1262 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001263 if (Triple.isOSFuchsia())
1264 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001265 return false;
1266
1267 case llvm::Triple::xcore:
1268 case llvm::Triple::wasm32:
1269 case llvm::Triple::wasm64:
1270 return true;
1271 }
1272}
1273
1274void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1275 ArgStringList &CmdArgs, bool KernelOrKext) const {
1276 // Select the ABI to use.
1277 // FIXME: Support -meabi.
1278 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1279 const char *ABIName = nullptr;
Eric Christopher53b2cb72017-06-30 00:03:56 +00001280 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
David L. Jonesf561aba2017-03-08 01:02:16 +00001281 ABIName = A->getValue();
Eric Christopher53b2cb72017-06-30 00:03:56 +00001282 else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001283 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001284 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001285 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001286
David L. Jonesf561aba2017-03-08 01:02:16 +00001287 CmdArgs.push_back("-target-abi");
1288 CmdArgs.push_back(ABIName);
1289
1290 // Determine floating point ABI from the options & target defaults.
1291 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1292 if (ABI == arm::FloatABI::Soft) {
1293 // Floating point operations and argument passing are soft.
1294 // FIXME: This changes CPP defines, we need -target-soft-float.
1295 CmdArgs.push_back("-msoft-float");
1296 CmdArgs.push_back("-mfloat-abi");
1297 CmdArgs.push_back("soft");
1298 } else if (ABI == arm::FloatABI::SoftFP) {
1299 // Floating point operations are hard, but argument passing is soft.
1300 CmdArgs.push_back("-mfloat-abi");
1301 CmdArgs.push_back("soft");
1302 } else {
1303 // Floating point operations and argument passing are hard.
1304 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1305 CmdArgs.push_back("-mfloat-abi");
1306 CmdArgs.push_back("hard");
1307 }
1308
1309 // Forward the -mglobal-merge option for explicit control over the pass.
1310 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1311 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001312 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001313 if (A->getOption().matches(options::OPT_mno_global_merge))
1314 CmdArgs.push_back("-arm-global-merge=false");
1315 else
1316 CmdArgs.push_back("-arm-global-merge=true");
1317 }
1318
1319 if (!Args.hasFlag(options::OPT_mimplicit_float,
1320 options::OPT_mno_implicit_float, true))
1321 CmdArgs.push_back("-no-implicit-float");
1322}
1323
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001324void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1325 const ArgList &Args, bool KernelOrKext,
1326 ArgStringList &CmdArgs) const {
1327 const ToolChain &TC = getToolChain();
1328
1329 // Add the target features
1330 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1331
1332 // Add target specific flags.
1333 switch (TC.getArch()) {
1334 default:
1335 break;
1336
1337 case llvm::Triple::arm:
1338 case llvm::Triple::armeb:
1339 case llvm::Triple::thumb:
1340 case llvm::Triple::thumbeb:
1341 // Use the effective triple, which takes into account the deployment target.
1342 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1343 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1344 break;
1345
1346 case llvm::Triple::aarch64:
1347 case llvm::Triple::aarch64_be:
1348 AddAArch64TargetArgs(Args, CmdArgs);
1349 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1350 break;
1351
1352 case llvm::Triple::mips:
1353 case llvm::Triple::mipsel:
1354 case llvm::Triple::mips64:
1355 case llvm::Triple::mips64el:
1356 AddMIPSTargetArgs(Args, CmdArgs);
1357 break;
1358
1359 case llvm::Triple::ppc:
1360 case llvm::Triple::ppc64:
1361 case llvm::Triple::ppc64le:
1362 AddPPCTargetArgs(Args, CmdArgs);
1363 break;
1364
Alex Bradbury71f45452018-01-11 13:36:56 +00001365 case llvm::Triple::riscv32:
1366 case llvm::Triple::riscv64:
1367 AddRISCVTargetArgs(Args, CmdArgs);
1368 break;
1369
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001370 case llvm::Triple::sparc:
1371 case llvm::Triple::sparcel:
1372 case llvm::Triple::sparcv9:
1373 AddSparcTargetArgs(Args, CmdArgs);
1374 break;
1375
1376 case llvm::Triple::systemz:
1377 AddSystemZTargetArgs(Args, CmdArgs);
1378 break;
1379
1380 case llvm::Triple::x86:
1381 case llvm::Triple::x86_64:
1382 AddX86TargetArgs(Args, CmdArgs);
1383 break;
1384
1385 case llvm::Triple::lanai:
1386 AddLanaiTargetArgs(Args, CmdArgs);
1387 break;
1388
1389 case llvm::Triple::hexagon:
1390 AddHexagonTargetArgs(Args, CmdArgs);
1391 break;
1392
1393 case llvm::Triple::wasm32:
1394 case llvm::Triple::wasm64:
1395 AddWebAssemblyTargetArgs(Args, CmdArgs);
1396 break;
1397 }
1398}
1399
David L. Jonesf561aba2017-03-08 01:02:16 +00001400void Clang::AddAArch64TargetArgs(const ArgList &Args,
1401 ArgStringList &CmdArgs) const {
1402 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1403
1404 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1405 Args.hasArg(options::OPT_mkernel) ||
1406 Args.hasArg(options::OPT_fapple_kext))
1407 CmdArgs.push_back("-disable-red-zone");
1408
1409 if (!Args.hasFlag(options::OPT_mimplicit_float,
1410 options::OPT_mno_implicit_float, true))
1411 CmdArgs.push_back("-no-implicit-float");
1412
1413 const char *ABIName = nullptr;
1414 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1415 ABIName = A->getValue();
1416 else if (Triple.isOSDarwin())
1417 ABIName = "darwinpcs";
1418 else
1419 ABIName = "aapcs";
1420
1421 CmdArgs.push_back("-target-abi");
1422 CmdArgs.push_back(ABIName);
1423
1424 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1425 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001426 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001427 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1428 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1429 else
1430 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1431 } else if (Triple.isAndroid()) {
1432 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001433 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001434 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1435 }
1436
1437 // Forward the -mglobal-merge option for explicit control over the pass.
1438 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1439 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001440 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001441 if (A->getOption().matches(options::OPT_mno_global_merge))
1442 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1443 else
1444 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1445 }
1446}
1447
1448void Clang::AddMIPSTargetArgs(const ArgList &Args,
1449 ArgStringList &CmdArgs) const {
1450 const Driver &D = getToolChain().getDriver();
1451 StringRef CPUName;
1452 StringRef ABIName;
1453 const llvm::Triple &Triple = getToolChain().getTriple();
1454 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1455
1456 CmdArgs.push_back("-target-abi");
1457 CmdArgs.push_back(ABIName.data());
1458
1459 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1460 if (ABI == mips::FloatABI::Soft) {
1461 // Floating point operations and argument passing are soft.
1462 CmdArgs.push_back("-msoft-float");
1463 CmdArgs.push_back("-mfloat-abi");
1464 CmdArgs.push_back("soft");
1465 } else {
1466 // Floating point operations and argument passing are hard.
1467 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1468 CmdArgs.push_back("-mfloat-abi");
1469 CmdArgs.push_back("hard");
1470 }
1471
1472 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1473 if (A->getOption().matches(options::OPT_mxgot)) {
1474 CmdArgs.push_back("-mllvm");
1475 CmdArgs.push_back("-mxgot");
1476 }
1477 }
1478
1479 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1480 options::OPT_mno_ldc1_sdc1)) {
1481 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1482 CmdArgs.push_back("-mllvm");
1483 CmdArgs.push_back("-mno-ldc1-sdc1");
1484 }
1485 }
1486
1487 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1488 options::OPT_mno_check_zero_division)) {
1489 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1490 CmdArgs.push_back("-mllvm");
1491 CmdArgs.push_back("-mno-check-zero-division");
1492 }
1493 }
1494
1495 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1496 StringRef v = A->getValue();
1497 CmdArgs.push_back("-mllvm");
1498 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1499 A->claim();
1500 }
1501
Simon Dardis31636a12017-07-20 14:04:12 +00001502 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1503 Arg *ABICalls =
1504 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1505
1506 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1507 // -mgpopt is the default for static, -fno-pic environments but these two
1508 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1509 // the only case where -mllvm -mgpopt is passed.
1510 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1511 // passed explicitly when compiling something with -mabicalls
1512 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001513 //
1514 // When the ABI in use is N64, we also need to determine the PIC mode that
1515 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001516 bool NoABICalls =
1517 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001518
1519 llvm::Reloc::Model RelocationModel;
1520 unsigned PICLevel;
1521 bool IsPIE;
1522 std::tie(RelocationModel, PICLevel, IsPIE) =
1523 ParsePICArgs(getToolChain(), Args);
1524
1525 NoABICalls = NoABICalls ||
1526 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1527
Simon Dardis31636a12017-07-20 14:04:12 +00001528 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1529 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1530 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1531 CmdArgs.push_back("-mllvm");
1532 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001533
1534 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1535 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001536 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001537 options::OPT_mno_extern_sdata);
1538 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1539 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001540 if (LocalSData) {
1541 CmdArgs.push_back("-mllvm");
1542 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1543 CmdArgs.push_back("-mlocal-sdata=1");
1544 } else {
1545 CmdArgs.push_back("-mlocal-sdata=0");
1546 }
1547 LocalSData->claim();
1548 }
1549
Simon Dardis7d318782017-07-24 14:02:09 +00001550 if (ExternSData) {
1551 CmdArgs.push_back("-mllvm");
1552 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1553 CmdArgs.push_back("-mextern-sdata=1");
1554 } else {
1555 CmdArgs.push_back("-mextern-sdata=0");
1556 }
1557 ExternSData->claim();
1558 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001559
1560 if (EmbeddedData) {
1561 CmdArgs.push_back("-mllvm");
1562 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1563 CmdArgs.push_back("-membedded-data=1");
1564 } else {
1565 CmdArgs.push_back("-membedded-data=0");
1566 }
1567 EmbeddedData->claim();
1568 }
1569
Simon Dardis31636a12017-07-20 14:04:12 +00001570 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1571 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1572
1573 if (GPOpt)
1574 GPOpt->claim();
1575
David L. Jonesf561aba2017-03-08 01:02:16 +00001576 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1577 StringRef Val = StringRef(A->getValue());
1578 if (mips::hasCompactBranches(CPUName)) {
1579 if (Val == "never" || Val == "always" || Val == "optimal") {
1580 CmdArgs.push_back("-mllvm");
1581 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1582 } else
1583 D.Diag(diag::err_drv_unsupported_option_argument)
1584 << A->getOption().getName() << Val;
1585 } else
1586 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1587 }
1588}
1589
1590void Clang::AddPPCTargetArgs(const ArgList &Args,
1591 ArgStringList &CmdArgs) const {
1592 // Select the ABI to use.
1593 const char *ABIName = nullptr;
1594 if (getToolChain().getTriple().isOSLinux())
1595 switch (getToolChain().getArch()) {
1596 case llvm::Triple::ppc64: {
1597 // When targeting a processor that supports QPX, or if QPX is
1598 // specifically enabled, default to using the ABI that supports QPX (so
1599 // long as it is not specifically disabled).
1600 bool HasQPX = false;
1601 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1602 HasQPX = A->getValue() == StringRef("a2q");
1603 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1604 if (HasQPX) {
1605 ABIName = "elfv1-qpx";
1606 break;
1607 }
1608
1609 ABIName = "elfv1";
1610 break;
1611 }
1612 case llvm::Triple::ppc64le:
1613 ABIName = "elfv2";
1614 break;
1615 default:
1616 break;
1617 }
1618
1619 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1620 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1621 // the option if given as we don't have backend support for any targets
1622 // that don't use the altivec abi.
1623 if (StringRef(A->getValue()) != "altivec")
1624 ABIName = A->getValue();
1625
1626 ppc::FloatABI FloatABI =
1627 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1628
1629 if (FloatABI == ppc::FloatABI::Soft) {
1630 // Floating point operations and argument passing are soft.
1631 CmdArgs.push_back("-msoft-float");
1632 CmdArgs.push_back("-mfloat-abi");
1633 CmdArgs.push_back("soft");
1634 } else {
1635 // Floating point operations and argument passing are hard.
1636 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1637 CmdArgs.push_back("-mfloat-abi");
1638 CmdArgs.push_back("hard");
1639 }
1640
1641 if (ABIName) {
1642 CmdArgs.push_back("-target-abi");
1643 CmdArgs.push_back(ABIName);
1644 }
1645}
1646
Alex Bradbury71f45452018-01-11 13:36:56 +00001647void Clang::AddRISCVTargetArgs(const ArgList &Args,
1648 ArgStringList &CmdArgs) const {
1649 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001650 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001651 const char *ABIName = nullptr;
1652 const llvm::Triple &Triple = getToolChain().getTriple();
1653 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1654 ABIName = A->getValue();
1655 else if (Triple.getArch() == llvm::Triple::riscv32)
1656 ABIName = "ilp32";
1657 else if (Triple.getArch() == llvm::Triple::riscv64)
1658 ABIName = "lp64";
1659 else
1660 llvm_unreachable("Unexpected triple!");
1661
1662 CmdArgs.push_back("-target-abi");
1663 CmdArgs.push_back(ABIName);
1664}
1665
David L. Jonesf561aba2017-03-08 01:02:16 +00001666void Clang::AddSparcTargetArgs(const ArgList &Args,
1667 ArgStringList &CmdArgs) const {
1668 sparc::FloatABI FloatABI =
1669 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1670
1671 if (FloatABI == sparc::FloatABI::Soft) {
1672 // Floating point operations and argument passing are soft.
1673 CmdArgs.push_back("-msoft-float");
1674 CmdArgs.push_back("-mfloat-abi");
1675 CmdArgs.push_back("soft");
1676 } else {
1677 // Floating point operations and argument passing are hard.
1678 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1679 CmdArgs.push_back("-mfloat-abi");
1680 CmdArgs.push_back("hard");
1681 }
1682}
1683
1684void Clang::AddSystemZTargetArgs(const ArgList &Args,
1685 ArgStringList &CmdArgs) const {
1686 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1687 CmdArgs.push_back("-mbackchain");
1688}
1689
1690void Clang::AddX86TargetArgs(const ArgList &Args,
1691 ArgStringList &CmdArgs) const {
1692 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1693 Args.hasArg(options::OPT_mkernel) ||
1694 Args.hasArg(options::OPT_fapple_kext))
1695 CmdArgs.push_back("-disable-red-zone");
1696
1697 // Default to avoid implicit floating-point for kernel/kext code, but allow
1698 // that to be overridden with -mno-soft-float.
1699 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1700 Args.hasArg(options::OPT_fapple_kext));
1701 if (Arg *A = Args.getLastArg(
1702 options::OPT_msoft_float, options::OPT_mno_soft_float,
1703 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1704 const Option &O = A->getOption();
1705 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1706 O.matches(options::OPT_msoft_float));
1707 }
1708 if (NoImplicitFloat)
1709 CmdArgs.push_back("-no-implicit-float");
1710
1711 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1712 StringRef Value = A->getValue();
1713 if (Value == "intel" || Value == "att") {
1714 CmdArgs.push_back("-mllvm");
1715 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1716 } else {
1717 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1718 << A->getOption().getName() << Value;
1719 }
Nico Webere3712cf2018-01-17 13:34:20 +00001720 } else if (getToolChain().getDriver().IsCLMode()) {
1721 CmdArgs.push_back("-mllvm");
1722 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001723 }
1724
1725 // Set flags to support MCU ABI.
1726 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1727 CmdArgs.push_back("-mfloat-abi");
1728 CmdArgs.push_back("soft");
1729 CmdArgs.push_back("-mstack-alignment=4");
1730 }
1731}
1732
1733void Clang::AddHexagonTargetArgs(const ArgList &Args,
1734 ArgStringList &CmdArgs) const {
1735 CmdArgs.push_back("-mqdsp6-compat");
1736 CmdArgs.push_back("-Wreturn-type");
1737
1738 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001739 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001740 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1741 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001742 }
1743
1744 if (!Args.hasArg(options::OPT_fno_short_enums))
1745 CmdArgs.push_back("-fshort-enums");
1746 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1747 CmdArgs.push_back("-mllvm");
1748 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1749 }
1750 CmdArgs.push_back("-mllvm");
1751 CmdArgs.push_back("-machine-sink-split=0");
1752}
1753
1754void Clang::AddLanaiTargetArgs(const ArgList &Args,
1755 ArgStringList &CmdArgs) const {
1756 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1757 StringRef CPUName = A->getValue();
1758
1759 CmdArgs.push_back("-target-cpu");
1760 CmdArgs.push_back(Args.MakeArgString(CPUName));
1761 }
1762 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1763 StringRef Value = A->getValue();
1764 // Only support mregparm=4 to support old usage. Report error for all other
1765 // cases.
1766 int Mregparm;
1767 if (Value.getAsInteger(10, Mregparm)) {
1768 if (Mregparm != 4) {
1769 getToolChain().getDriver().Diag(
1770 diag::err_drv_unsupported_option_argument)
1771 << A->getOption().getName() << Value;
1772 }
1773 }
1774 }
1775}
1776
1777void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1778 ArgStringList &CmdArgs) const {
1779 // Default to "hidden" visibility.
1780 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1781 options::OPT_fvisibility_ms_compat)) {
1782 CmdArgs.push_back("-fvisibility");
1783 CmdArgs.push_back("hidden");
1784 }
1785}
1786
1787void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1788 StringRef Target, const InputInfo &Output,
1789 const InputInfo &Input, const ArgList &Args) const {
1790 // If this is a dry run, do not create the compilation database file.
1791 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1792 return;
1793
1794 using llvm::yaml::escape;
1795 const Driver &D = getToolChain().getDriver();
1796
1797 if (!CompilationDatabase) {
1798 std::error_code EC;
1799 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1800 if (EC) {
1801 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1802 << EC.message();
1803 return;
1804 }
1805 CompilationDatabase = std::move(File);
1806 }
1807 auto &CDB = *CompilationDatabase;
1808 SmallString<128> Buf;
1809 if (llvm::sys::fs::current_path(Buf))
1810 Buf = ".";
1811 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1812 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1813 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1814 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1815 Buf = "-x";
1816 Buf += types::getTypeName(Input.getType());
1817 CDB << ", \"" << escape(Buf) << "\"";
1818 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1819 Buf = "--sysroot=";
1820 Buf += D.SysRoot;
1821 CDB << ", \"" << escape(Buf) << "\"";
1822 }
1823 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1824 for (auto &A: Args) {
1825 auto &O = A->getOption();
1826 // Skip language selection, which is positional.
1827 if (O.getID() == options::OPT_x)
1828 continue;
1829 // Skip writing dependency output and the compilation database itself.
1830 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1831 continue;
1832 // Skip inputs.
1833 if (O.getKind() == Option::InputClass)
1834 continue;
1835 // All other arguments are quoted and appended.
1836 ArgStringList ASL;
1837 A->render(Args, ASL);
1838 for (auto &it: ASL)
1839 CDB << ", \"" << escape(it) << "\"";
1840 }
1841 Buf = "--target=";
1842 Buf += Target;
1843 CDB << ", \"" << escape(Buf) << "\"]},\n";
1844}
1845
1846static void CollectArgsForIntegratedAssembler(Compilation &C,
1847 const ArgList &Args,
1848 ArgStringList &CmdArgs,
1849 const Driver &D) {
1850 if (UseRelaxAll(C, Args))
1851 CmdArgs.push_back("-mrelax-all");
1852
1853 // Only default to -mincremental-linker-compatible if we think we are
1854 // targeting the MSVC linker.
1855 bool DefaultIncrementalLinkerCompatible =
1856 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1857 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1858 options::OPT_mno_incremental_linker_compatible,
1859 DefaultIncrementalLinkerCompatible))
1860 CmdArgs.push_back("-mincremental-linker-compatible");
1861
1862 switch (C.getDefaultToolChain().getArch()) {
1863 case llvm::Triple::arm:
1864 case llvm::Triple::armeb:
1865 case llvm::Triple::thumb:
1866 case llvm::Triple::thumbeb:
1867 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1868 StringRef Value = A->getValue();
1869 if (Value == "always" || Value == "never" || Value == "arm" ||
1870 Value == "thumb") {
1871 CmdArgs.push_back("-mllvm");
1872 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1873 } else {
1874 D.Diag(diag::err_drv_unsupported_option_argument)
1875 << A->getOption().getName() << Value;
1876 }
1877 }
1878 break;
1879 default:
1880 break;
1881 }
1882
1883 // When passing -I arguments to the assembler we sometimes need to
1884 // unconditionally take the next argument. For example, when parsing
1885 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1886 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1887 // arg after parsing the '-I' arg.
1888 bool TakeNextArg = false;
1889
Petr Hosek5668d832017-11-22 01:38:31 +00001890 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001891 const char *MipsTargetFeature = nullptr;
1892 for (const Arg *A :
1893 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1894 A->claim();
1895
1896 for (StringRef Value : A->getValues()) {
1897 if (TakeNextArg) {
1898 CmdArgs.push_back(Value.data());
1899 TakeNextArg = false;
1900 continue;
1901 }
1902
1903 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1904 Value == "-mbig-obj")
1905 continue; // LLVM handles bigobj automatically
1906
1907 switch (C.getDefaultToolChain().getArch()) {
1908 default:
1909 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001910 case llvm::Triple::thumb:
1911 case llvm::Triple::thumbeb:
1912 case llvm::Triple::arm:
1913 case llvm::Triple::armeb:
1914 if (Value == "-mthumb")
1915 // -mthumb has already been processed in ComputeLLVMTriple()
1916 // recognize but skip over here.
1917 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001918 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001919 case llvm::Triple::mips:
1920 case llvm::Triple::mipsel:
1921 case llvm::Triple::mips64:
1922 case llvm::Triple::mips64el:
1923 if (Value == "--trap") {
1924 CmdArgs.push_back("-target-feature");
1925 CmdArgs.push_back("+use-tcc-in-div");
1926 continue;
1927 }
1928 if (Value == "--break") {
1929 CmdArgs.push_back("-target-feature");
1930 CmdArgs.push_back("-use-tcc-in-div");
1931 continue;
1932 }
1933 if (Value.startswith("-msoft-float")) {
1934 CmdArgs.push_back("-target-feature");
1935 CmdArgs.push_back("+soft-float");
1936 continue;
1937 }
1938 if (Value.startswith("-mhard-float")) {
1939 CmdArgs.push_back("-target-feature");
1940 CmdArgs.push_back("-soft-float");
1941 continue;
1942 }
1943
1944 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1945 .Case("-mips1", "+mips1")
1946 .Case("-mips2", "+mips2")
1947 .Case("-mips3", "+mips3")
1948 .Case("-mips4", "+mips4")
1949 .Case("-mips5", "+mips5")
1950 .Case("-mips32", "+mips32")
1951 .Case("-mips32r2", "+mips32r2")
1952 .Case("-mips32r3", "+mips32r3")
1953 .Case("-mips32r5", "+mips32r5")
1954 .Case("-mips32r6", "+mips32r6")
1955 .Case("-mips64", "+mips64")
1956 .Case("-mips64r2", "+mips64r2")
1957 .Case("-mips64r3", "+mips64r3")
1958 .Case("-mips64r5", "+mips64r5")
1959 .Case("-mips64r6", "+mips64r6")
1960 .Default(nullptr);
1961 if (MipsTargetFeature)
1962 continue;
1963 }
1964
1965 if (Value == "-force_cpusubtype_ALL") {
1966 // Do nothing, this is the default and we don't support anything else.
1967 } else if (Value == "-L") {
1968 CmdArgs.push_back("-msave-temp-labels");
1969 } else if (Value == "--fatal-warnings") {
1970 CmdArgs.push_back("-massembler-fatal-warnings");
1971 } else if (Value == "--noexecstack") {
1972 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001973 } else if (Value.startswith("-compress-debug-sections") ||
1974 Value.startswith("--compress-debug-sections") ||
1975 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00001976 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001977 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00001978 } else if (Value == "-mrelax-relocations=yes" ||
1979 Value == "--mrelax-relocations=yes") {
1980 UseRelaxRelocations = true;
1981 } else if (Value == "-mrelax-relocations=no" ||
1982 Value == "--mrelax-relocations=no") {
1983 UseRelaxRelocations = false;
1984 } else if (Value.startswith("-I")) {
1985 CmdArgs.push_back(Value.data());
1986 // We need to consume the next argument if the current arg is a plain
1987 // -I. The next arg will be the include directory.
1988 if (Value == "-I")
1989 TakeNextArg = true;
1990 } else if (Value.startswith("-gdwarf-")) {
1991 // "-gdwarf-N" options are not cc1as options.
1992 unsigned DwarfVersion = DwarfVersionNum(Value);
1993 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
1994 CmdArgs.push_back(Value.data());
1995 } else {
1996 RenderDebugEnablingArgs(Args, CmdArgs,
1997 codegenoptions::LimitedDebugInfo,
1998 DwarfVersion, llvm::DebuggerKind::Default);
1999 }
2000 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2001 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2002 // Do nothing, we'll validate it later.
2003 } else if (Value == "-defsym") {
2004 if (A->getNumValues() != 2) {
2005 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2006 break;
2007 }
2008 const char *S = A->getValue(1);
2009 auto Pair = StringRef(S).split('=');
2010 auto Sym = Pair.first;
2011 auto SVal = Pair.second;
2012
2013 if (Sym.empty() || SVal.empty()) {
2014 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2015 break;
2016 }
2017 int64_t IVal;
2018 if (SVal.getAsInteger(0, IVal)) {
2019 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2020 break;
2021 }
2022 CmdArgs.push_back(Value.data());
2023 TakeNextArg = true;
2024 } else {
2025 D.Diag(diag::err_drv_unsupported_option_argument)
2026 << A->getOption().getName() << Value;
2027 }
2028 }
2029 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002030 if (UseRelaxRelocations)
2031 CmdArgs.push_back("--mrelax-relocations");
2032 if (MipsTargetFeature != nullptr) {
2033 CmdArgs.push_back("-target-feature");
2034 CmdArgs.push_back(MipsTargetFeature);
2035 }
2036}
2037
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002038static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2039 bool OFastEnabled, const ArgList &Args,
2040 ArgStringList &CmdArgs) {
2041 // Handle various floating point optimization flags, mapping them to the
2042 // appropriate LLVM code generation flags. This is complicated by several
2043 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002044 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002045 // LLVM flags based on the final state.
2046 bool HonorINFs = true;
2047 bool HonorNaNs = true;
2048 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2049 bool MathErrno = TC.IsMathErrnoDefault();
2050 bool AssociativeMath = false;
2051 bool ReciprocalMath = false;
2052 bool SignedZeros = true;
2053 bool TrappingMath = true;
2054 StringRef DenormalFPMath = "";
2055 StringRef FPContract = "";
2056
2057 for (const Arg *A : Args) {
2058 switch (A->getOption().getID()) {
2059 // If this isn't an FP option skip the claim below
2060 default: continue;
2061
2062 // Options controlling individual features
2063 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2064 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2065 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2066 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2067 case options::OPT_fmath_errno: MathErrno = true; break;
2068 case options::OPT_fno_math_errno: MathErrno = false; break;
2069 case options::OPT_fassociative_math: AssociativeMath = true; break;
2070 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2071 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2072 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2073 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2074 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2075 case options::OPT_ftrapping_math: TrappingMath = true; break;
2076 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2077
2078 case options::OPT_fdenormal_fp_math_EQ:
2079 DenormalFPMath = A->getValue();
2080 break;
2081
2082 // Validate and pass through -fp-contract option.
2083 case options::OPT_ffp_contract: {
2084 StringRef Val = A->getValue();
2085 if (Val == "fast" || Val == "on" || Val == "off")
2086 FPContract = Val;
2087 else
2088 D.Diag(diag::err_drv_unsupported_option_argument)
2089 << A->getOption().getName() << Val;
2090 break;
2091 }
2092
2093 case options::OPT_ffinite_math_only:
2094 HonorINFs = false;
2095 HonorNaNs = false;
2096 break;
2097 case options::OPT_fno_finite_math_only:
2098 HonorINFs = true;
2099 HonorNaNs = true;
2100 break;
2101
2102 case options::OPT_funsafe_math_optimizations:
2103 AssociativeMath = true;
2104 ReciprocalMath = true;
2105 SignedZeros = false;
2106 TrappingMath = false;
2107 break;
2108 case options::OPT_fno_unsafe_math_optimizations:
2109 AssociativeMath = false;
2110 ReciprocalMath = false;
2111 SignedZeros = true;
2112 TrappingMath = true;
2113 // -fno_unsafe_math_optimizations restores default denormal handling
2114 DenormalFPMath = "";
2115 break;
2116
2117 case options::OPT_Ofast:
2118 // If -Ofast is the optimization level, then -ffast-math should be enabled
2119 if (!OFastEnabled)
2120 continue;
2121 LLVM_FALLTHROUGH;
2122 case options::OPT_ffast_math:
2123 HonorINFs = false;
2124 HonorNaNs = false;
2125 MathErrno = false;
2126 AssociativeMath = true;
2127 ReciprocalMath = true;
2128 SignedZeros = false;
2129 TrappingMath = false;
2130 // If fast-math is set then set the fp-contract mode to fast.
2131 FPContract = "fast";
2132 break;
2133 case options::OPT_fno_fast_math:
2134 HonorINFs = true;
2135 HonorNaNs = true;
2136 // Turning on -ffast-math (with either flag) removes the need for
2137 // MathErrno. However, turning *off* -ffast-math merely restores the
2138 // toolchain default (which may be false).
2139 MathErrno = TC.IsMathErrnoDefault();
2140 AssociativeMath = false;
2141 ReciprocalMath = false;
2142 SignedZeros = true;
2143 TrappingMath = true;
2144 // -fno_fast_math restores default denormal and fpcontract handling
2145 DenormalFPMath = "";
2146 FPContract = "";
2147 break;
2148 }
2149
2150 // If we handled this option claim it
2151 A->claim();
2152 }
2153
2154 if (!HonorINFs)
2155 CmdArgs.push_back("-menable-no-infs");
2156
2157 if (!HonorNaNs)
2158 CmdArgs.push_back("-menable-no-nans");
2159
2160 if (MathErrno)
2161 CmdArgs.push_back("-fmath-errno");
2162
2163 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2164 !TrappingMath)
2165 CmdArgs.push_back("-menable-unsafe-fp-math");
2166
2167 if (!SignedZeros)
2168 CmdArgs.push_back("-fno-signed-zeros");
2169
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002170 if (AssociativeMath && !SignedZeros && !TrappingMath)
2171 CmdArgs.push_back("-mreassociate");
2172
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002173 if (ReciprocalMath)
2174 CmdArgs.push_back("-freciprocal-math");
2175
2176 if (!TrappingMath)
2177 CmdArgs.push_back("-fno-trapping-math");
2178
2179 if (!DenormalFPMath.empty())
2180 CmdArgs.push_back(
2181 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2182
2183 if (!FPContract.empty())
2184 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2185
2186 ParseMRecip(D, Args, CmdArgs);
2187
2188 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2189 // individual features enabled by -ffast-math instead of the option itself as
2190 // that's consistent with gcc's behaviour.
2191 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2192 ReciprocalMath && !SignedZeros && !TrappingMath)
2193 CmdArgs.push_back("-ffast-math");
2194
2195 // Handle __FINITE_MATH_ONLY__ similarly.
2196 if (!HonorINFs && !HonorNaNs)
2197 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002198
2199 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2200 CmdArgs.push_back("-mfpmath");
2201 CmdArgs.push_back(A->getValue());
2202 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002203
2204 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002205 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2206 options::OPT_fstrict_float_cast_overflow, false))
2207 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002208}
2209
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002210static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2211 const llvm::Triple &Triple,
2212 const InputInfo &Input) {
2213 // Enable region store model by default.
2214 CmdArgs.push_back("-analyzer-store=region");
2215
2216 // Treat blocks as analysis entry points.
2217 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2218
2219 CmdArgs.push_back("-analyzer-eagerly-assume");
2220
2221 // Add default argument set.
2222 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2223 CmdArgs.push_back("-analyzer-checker=core");
2224 CmdArgs.push_back("-analyzer-checker=apiModeling");
2225
2226 if (!Triple.isWindowsMSVCEnvironment()) {
2227 CmdArgs.push_back("-analyzer-checker=unix");
2228 } else {
2229 // Enable "unix" checkers that also work on Windows.
2230 CmdArgs.push_back("-analyzer-checker=unix.API");
2231 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2232 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2233 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2234 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2235 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2236 }
2237
2238 // Disable some unix checkers for PS4.
2239 if (Triple.isPS4CPU()) {
2240 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2241 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2242 }
2243
2244 if (Triple.isOSDarwin())
2245 CmdArgs.push_back("-analyzer-checker=osx");
2246
2247 CmdArgs.push_back("-analyzer-checker=deadcode");
2248
2249 if (types::isCXX(Input.getType()))
2250 CmdArgs.push_back("-analyzer-checker=cplusplus");
2251
2252 if (!Triple.isPS4CPU()) {
2253 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2254 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2255 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2256 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2257 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2258 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2259 }
2260
2261 // Default nullability checks.
2262 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2263 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2264 }
2265
2266 // Set the output format. The default is plist, for (lame) historical reasons.
2267 CmdArgs.push_back("-analyzer-output");
2268 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2269 CmdArgs.push_back(A->getValue());
2270 else
2271 CmdArgs.push_back("plist");
2272
2273 // Disable the presentation of standard compiler warnings when using
2274 // --analyze. We only want to show static analyzer diagnostics or frontend
2275 // errors.
2276 CmdArgs.push_back("-w");
2277
2278 // Add -Xanalyzer arguments when running as analyzer.
2279 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2280}
2281
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002282static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002283 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002284 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2285
2286 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2287 // doesn't even have a stack!
2288 if (EffectiveTriple.isNVPTX())
2289 return;
2290
2291 // -stack-protector=0 is default.
2292 unsigned StackProtectorLevel = 0;
2293 unsigned DefaultStackProtectorLevel =
2294 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2295
2296 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2297 options::OPT_fstack_protector_all,
2298 options::OPT_fstack_protector_strong,
2299 options::OPT_fstack_protector)) {
2300 if (A->getOption().matches(options::OPT_fstack_protector))
2301 StackProtectorLevel =
2302 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2303 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2304 StackProtectorLevel = LangOptions::SSPStrong;
2305 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2306 StackProtectorLevel = LangOptions::SSPReq;
2307 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002308 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002309 }
2310
2311 if (StackProtectorLevel) {
2312 CmdArgs.push_back("-stack-protector");
2313 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2314 }
2315
2316 // --param ssp-buffer-size=
2317 for (const Arg *A : Args.filtered(options::OPT__param)) {
2318 StringRef Str(A->getValue());
2319 if (Str.startswith("ssp-buffer-size=")) {
2320 if (StackProtectorLevel) {
2321 CmdArgs.push_back("-stack-protector-buffer-size");
2322 // FIXME: Verify the argument is a valid integer.
2323 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2324 }
2325 A->claim();
2326 }
2327 }
2328}
2329
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002330static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2331 const unsigned ForwardedArguments[] = {
2332 options::OPT_cl_opt_disable,
2333 options::OPT_cl_strict_aliasing,
2334 options::OPT_cl_single_precision_constant,
2335 options::OPT_cl_finite_math_only,
2336 options::OPT_cl_kernel_arg_info,
2337 options::OPT_cl_unsafe_math_optimizations,
2338 options::OPT_cl_fast_relaxed_math,
2339 options::OPT_cl_mad_enable,
2340 options::OPT_cl_no_signed_zeros,
2341 options::OPT_cl_denorms_are_zero,
2342 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002343 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002344 };
2345
2346 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2347 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2348 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2349 }
2350
2351 for (const auto &Arg : ForwardedArguments)
2352 if (const auto *A = Args.getLastArg(Arg))
2353 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2354}
2355
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002356static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2357 ArgStringList &CmdArgs) {
2358 bool ARCMTEnabled = false;
2359 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2360 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2361 options::OPT_ccc_arcmt_modify,
2362 options::OPT_ccc_arcmt_migrate)) {
2363 ARCMTEnabled = true;
2364 switch (A->getOption().getID()) {
2365 default: llvm_unreachable("missed a case");
2366 case options::OPT_ccc_arcmt_check:
2367 CmdArgs.push_back("-arcmt-check");
2368 break;
2369 case options::OPT_ccc_arcmt_modify:
2370 CmdArgs.push_back("-arcmt-modify");
2371 break;
2372 case options::OPT_ccc_arcmt_migrate:
2373 CmdArgs.push_back("-arcmt-migrate");
2374 CmdArgs.push_back("-mt-migrate-directory");
2375 CmdArgs.push_back(A->getValue());
2376
2377 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2378 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2379 break;
2380 }
2381 }
2382 } else {
2383 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2384 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2385 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2386 }
2387
2388 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2389 if (ARCMTEnabled)
2390 D.Diag(diag::err_drv_argument_not_allowed_with)
2391 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2392
2393 CmdArgs.push_back("-mt-migrate-directory");
2394 CmdArgs.push_back(A->getValue());
2395
2396 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2397 options::OPT_objcmt_migrate_subscripting,
2398 options::OPT_objcmt_migrate_property)) {
2399 // None specified, means enable them all.
2400 CmdArgs.push_back("-objcmt-migrate-literals");
2401 CmdArgs.push_back("-objcmt-migrate-subscripting");
2402 CmdArgs.push_back("-objcmt-migrate-property");
2403 } else {
2404 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2405 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2406 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2407 }
2408 } else {
2409 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2410 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2411 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2412 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2413 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2414 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2415 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2416 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2417 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2418 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2419 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2420 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2421 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2422 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2423 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2424 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2425 }
2426}
2427
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002428static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2429 const ArgList &Args, ArgStringList &CmdArgs) {
2430 // -fbuiltin is default unless -mkernel is used.
2431 bool UseBuiltins =
2432 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2433 !Args.hasArg(options::OPT_mkernel));
2434 if (!UseBuiltins)
2435 CmdArgs.push_back("-fno-builtin");
2436
2437 // -ffreestanding implies -fno-builtin.
2438 if (Args.hasArg(options::OPT_ffreestanding))
2439 UseBuiltins = false;
2440
2441 // Process the -fno-builtin-* options.
2442 for (const auto &Arg : Args) {
2443 const Option &O = Arg->getOption();
2444 if (!O.matches(options::OPT_fno_builtin_))
2445 continue;
2446
2447 Arg->claim();
2448
2449 // If -fno-builtin is specified, then there's no need to pass the option to
2450 // the frontend.
2451 if (!UseBuiltins)
2452 continue;
2453
2454 StringRef FuncName = Arg->getValue();
2455 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2456 }
2457
2458 // le32-specific flags:
2459 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2460 // by default.
2461 if (TC.getArch() == llvm::Triple::le32)
2462 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002463}
2464
Adrian Prantl70599032018-02-09 18:43:10 +00002465void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2466 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2467 llvm::sys::path::append(Result, "org.llvm.clang.");
2468 appendUserToPath(Result);
2469 llvm::sys::path::append(Result, "ModuleCache");
2470}
2471
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002472static void RenderModulesOptions(Compilation &C, const Driver &D,
2473 const ArgList &Args, const InputInfo &Input,
2474 const InputInfo &Output,
2475 ArgStringList &CmdArgs, bool &HaveModules) {
2476 // -fmodules enables the use of precompiled modules (off by default).
2477 // Users can pass -fno-cxx-modules to turn off modules support for
2478 // C++/Objective-C++ programs.
2479 bool HaveClangModules = false;
2480 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2481 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2482 options::OPT_fno_cxx_modules, true);
2483 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2484 CmdArgs.push_back("-fmodules");
2485 HaveClangModules = true;
2486 }
2487 }
2488
2489 HaveModules = HaveClangModules;
2490 if (Args.hasArg(options::OPT_fmodules_ts)) {
2491 CmdArgs.push_back("-fmodules-ts");
2492 HaveModules = true;
2493 }
2494
2495 // -fmodule-maps enables implicit reading of module map files. By default,
2496 // this is enabled if we are using Clang's flavor of precompiled modules.
2497 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2498 options::OPT_fno_implicit_module_maps, HaveClangModules))
2499 CmdArgs.push_back("-fimplicit-module-maps");
2500
2501 // -fmodules-decluse checks that modules used are declared so (off by default)
2502 if (Args.hasFlag(options::OPT_fmodules_decluse,
2503 options::OPT_fno_modules_decluse, false))
2504 CmdArgs.push_back("-fmodules-decluse");
2505
2506 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2507 // all #included headers are part of modules.
2508 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2509 options::OPT_fno_modules_strict_decluse, false))
2510 CmdArgs.push_back("-fmodules-strict-decluse");
2511
2512 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002513 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002514 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2515 options::OPT_fno_implicit_modules, HaveClangModules)) {
2516 if (HaveModules)
2517 CmdArgs.push_back("-fno-implicit-modules");
2518 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002519 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002520 // -fmodule-cache-path specifies where our implicitly-built module files
2521 // should be written.
2522 SmallString<128> Path;
2523 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2524 Path = A->getValue();
2525
2526 if (C.isForDiagnostics()) {
2527 // When generating crash reports, we want to emit the modules along with
2528 // the reproduction sources, so we ignore any provided module path.
2529 Path = Output.getFilename();
2530 llvm::sys::path::replace_extension(Path, ".cache");
2531 llvm::sys::path::append(Path, "modules");
2532 } else if (Path.empty()) {
2533 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002534 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002535 }
2536
2537 const char Arg[] = "-fmodules-cache-path=";
2538 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2539 CmdArgs.push_back(Args.MakeArgString(Path));
2540 }
2541
2542 if (HaveModules) {
2543 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2544 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2545 CmdArgs.push_back(Args.MakeArgString(
2546 std::string("-fprebuilt-module-path=") + A->getValue()));
2547 A->claim();
2548 }
2549 }
2550
2551 // -fmodule-name specifies the module that is currently being built (or
2552 // used for header checking by -fmodule-maps).
2553 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2554
2555 // -fmodule-map-file can be used to specify files containing module
2556 // definitions.
2557 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2558
2559 // -fbuiltin-module-map can be used to load the clang
2560 // builtin headers modulemap file.
2561 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2562 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2563 llvm::sys::path::append(BuiltinModuleMap, "include");
2564 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2565 if (llvm::sys::fs::exists(BuiltinModuleMap))
2566 CmdArgs.push_back(
2567 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2568 }
2569
2570 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2571 // names to precompiled module files (the module is loaded only if used).
2572 // The -fmodule-file=<file> form can be used to unconditionally load
2573 // precompiled module files (whether used or not).
2574 if (HaveModules)
2575 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2576 else
2577 Args.ClaimAllArgs(options::OPT_fmodule_file);
2578
2579 // When building modules and generating crashdumps, we need to dump a module
2580 // dependency VFS alongside the output.
2581 if (HaveClangModules && C.isForDiagnostics()) {
2582 SmallString<128> VFSDir(Output.getFilename());
2583 llvm::sys::path::replace_extension(VFSDir, ".cache");
2584 // Add the cache directory as a temp so the crash diagnostics pick it up.
2585 C.addTempFile(Args.MakeArgString(VFSDir));
2586
2587 llvm::sys::path::append(VFSDir, "vfs");
2588 CmdArgs.push_back("-module-dependency-dir");
2589 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2590 }
2591
2592 if (HaveClangModules)
2593 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2594
2595 // Pass through all -fmodules-ignore-macro arguments.
2596 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2597 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2598 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2599
2600 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2601
2602 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2603 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2604 D.Diag(diag::err_drv_argument_not_allowed_with)
2605 << A->getAsString(Args) << "-fbuild-session-timestamp";
2606
2607 llvm::sys::fs::file_status Status;
2608 if (llvm::sys::fs::status(A->getValue(), Status))
2609 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2610 CmdArgs.push_back(
2611 Args.MakeArgString("-fbuild-session-timestamp=" +
2612 Twine((uint64_t)Status.getLastModificationTime()
2613 .time_since_epoch()
2614 .count())));
2615 }
2616
2617 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2618 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2619 options::OPT_fbuild_session_file))
2620 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2621
2622 Args.AddLastArg(CmdArgs,
2623 options::OPT_fmodules_validate_once_per_build_session);
2624 }
2625
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002626 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2627 options::OPT_fno_modules_validate_system_headers,
2628 ImplicitModules))
2629 CmdArgs.push_back("-fmodules-validate-system-headers");
2630
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002631 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2632}
2633
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002634static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2635 ArgStringList &CmdArgs) {
2636 // -fsigned-char is default.
2637 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2638 options::OPT_fno_signed_char,
2639 options::OPT_funsigned_char,
2640 options::OPT_fno_unsigned_char)) {
2641 if (A->getOption().matches(options::OPT_funsigned_char) ||
2642 A->getOption().matches(options::OPT_fno_signed_char)) {
2643 CmdArgs.push_back("-fno-signed-char");
2644 }
2645 } else if (!isSignedCharDefault(T)) {
2646 CmdArgs.push_back("-fno-signed-char");
2647 }
2648
Richard Smith3a8244d2018-05-01 05:02:45 +00002649 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2650 CmdArgs.push_back("-fchar8_t");
2651
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002652 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2653 options::OPT_fno_short_wchar)) {
2654 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2655 CmdArgs.push_back("-fwchar-type=short");
2656 CmdArgs.push_back("-fno-signed-wchar");
2657 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002658 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002659 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002660 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2661 T.getOS() == llvm::Triple::OpenBSD))
2662 CmdArgs.push_back("-fno-signed-wchar");
2663 else
2664 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002665 }
2666 }
2667}
2668
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002669static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2670 const llvm::Triple &T, const ArgList &Args,
2671 ObjCRuntime &Runtime, bool InferCovariantReturns,
2672 const InputInfo &Input, ArgStringList &CmdArgs) {
2673 const llvm::Triple::ArchType Arch = TC.getArch();
2674
2675 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2676 // is the default. Except for deployment target of 10.5, next runtime is
2677 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2678 if (Runtime.isNonFragile()) {
2679 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2680 options::OPT_fno_objc_legacy_dispatch,
2681 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2682 if (TC.UseObjCMixedDispatch())
2683 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2684 else
2685 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2686 }
2687 }
2688
2689 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2690 // to do Array/Dictionary subscripting by default.
2691 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2692 !T.isMacOSXVersionLT(10, 7) &&
2693 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2694 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2695
2696 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2697 // NOTE: This logic is duplicated in ToolChains.cpp.
2698 if (isObjCAutoRefCount(Args)) {
2699 TC.CheckObjCARC();
2700
2701 CmdArgs.push_back("-fobjc-arc");
2702
2703 // FIXME: It seems like this entire block, and several around it should be
2704 // wrapped in isObjC, but for now we just use it here as this is where it
2705 // was being used previously.
2706 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2707 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2708 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2709 else
2710 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2711 }
2712
2713 // Allow the user to enable full exceptions code emission.
2714 // We default off for Objective-C, on for Objective-C++.
2715 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2716 options::OPT_fno_objc_arc_exceptions,
2717 /*default=*/types::isCXX(Input.getType())))
2718 CmdArgs.push_back("-fobjc-arc-exceptions");
2719 }
2720
2721 // Silence warning for full exception code emission options when explicitly
2722 // set to use no ARC.
2723 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2724 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2725 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2726 }
2727
2728 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2729 // rewriter.
2730 if (InferCovariantReturns)
2731 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2732
2733 // Pass down -fobjc-weak or -fno-objc-weak if present.
2734 if (types::isObjC(Input.getType())) {
2735 auto WeakArg =
2736 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2737 if (!WeakArg) {
2738 // nothing to do
2739 } else if (!Runtime.allowsWeak()) {
2740 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2741 D.Diag(diag::err_objc_weak_unsupported);
2742 } else {
2743 WeakArg->render(Args, CmdArgs);
2744 }
2745 }
2746}
2747
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002748static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2749 ArgStringList &CmdArgs) {
2750 bool CaretDefault = true;
2751 bool ColumnDefault = true;
2752
2753 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2754 options::OPT__SLASH_diagnostics_column,
2755 options::OPT__SLASH_diagnostics_caret)) {
2756 switch (A->getOption().getID()) {
2757 case options::OPT__SLASH_diagnostics_caret:
2758 CaretDefault = true;
2759 ColumnDefault = true;
2760 break;
2761 case options::OPT__SLASH_diagnostics_column:
2762 CaretDefault = false;
2763 ColumnDefault = true;
2764 break;
2765 case options::OPT__SLASH_diagnostics_classic:
2766 CaretDefault = false;
2767 ColumnDefault = false;
2768 break;
2769 }
2770 }
2771
2772 // -fcaret-diagnostics is default.
2773 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2774 options::OPT_fno_caret_diagnostics, CaretDefault))
2775 CmdArgs.push_back("-fno-caret-diagnostics");
2776
2777 // -fdiagnostics-fixit-info is default, only pass non-default.
2778 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2779 options::OPT_fno_diagnostics_fixit_info))
2780 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2781
2782 // Enable -fdiagnostics-show-option by default.
2783 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2784 options::OPT_fno_diagnostics_show_option))
2785 CmdArgs.push_back("-fdiagnostics-show-option");
2786
2787 if (const Arg *A =
2788 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2789 CmdArgs.push_back("-fdiagnostics-show-category");
2790 CmdArgs.push_back(A->getValue());
2791 }
2792
2793 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2794 options::OPT_fno_diagnostics_show_hotness, false))
2795 CmdArgs.push_back("-fdiagnostics-show-hotness");
2796
2797 if (const Arg *A =
2798 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2799 std::string Opt =
2800 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2801 CmdArgs.push_back(Args.MakeArgString(Opt));
2802 }
2803
2804 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2805 CmdArgs.push_back("-fdiagnostics-format");
2806 CmdArgs.push_back(A->getValue());
2807 }
2808
2809 if (const Arg *A = Args.getLastArg(
2810 options::OPT_fdiagnostics_show_note_include_stack,
2811 options::OPT_fno_diagnostics_show_note_include_stack)) {
2812 const Option &O = A->getOption();
2813 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2814 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2815 else
2816 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2817 }
2818
2819 // Color diagnostics are parsed by the driver directly from argv and later
2820 // re-parsed to construct this job; claim any possible color diagnostic here
2821 // to avoid warn_drv_unused_argument and diagnose bad
2822 // OPT_fdiagnostics_color_EQ values.
2823 for (const Arg *A : Args) {
2824 const Option &O = A->getOption();
2825 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2826 !O.matches(options::OPT_fdiagnostics_color) &&
2827 !O.matches(options::OPT_fno_color_diagnostics) &&
2828 !O.matches(options::OPT_fno_diagnostics_color) &&
2829 !O.matches(options::OPT_fdiagnostics_color_EQ))
2830 continue;
2831
2832 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2833 StringRef Value(A->getValue());
2834 if (Value != "always" && Value != "never" && Value != "auto")
2835 D.Diag(diag::err_drv_clang_unsupported)
2836 << ("-fdiagnostics-color=" + Value).str();
2837 }
2838 A->claim();
2839 }
2840
2841 if (D.getDiags().getDiagnosticOptions().ShowColors)
2842 CmdArgs.push_back("-fcolor-diagnostics");
2843
2844 if (Args.hasArg(options::OPT_fansi_escape_codes))
2845 CmdArgs.push_back("-fansi-escape-codes");
2846
2847 if (!Args.hasFlag(options::OPT_fshow_source_location,
2848 options::OPT_fno_show_source_location))
2849 CmdArgs.push_back("-fno-show-source-location");
2850
2851 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2852 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2853
2854 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2855 ColumnDefault))
2856 CmdArgs.push_back("-fno-show-column");
2857
2858 if (!Args.hasFlag(options::OPT_fspell_checking,
2859 options::OPT_fno_spell_checking))
2860 CmdArgs.push_back("-fno-spell-checking");
2861}
2862
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002863static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2864 const llvm::Triple &T, const ArgList &Args,
2865 bool EmitCodeView, bool IsWindowsMSVC,
2866 ArgStringList &CmdArgs,
2867 codegenoptions::DebugInfoKind &DebugInfoKind,
2868 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002869 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2870 options::OPT_fno_debug_info_for_profiling, false))
2871 CmdArgs.push_back("-fdebug-info-for-profiling");
2872
2873 // The 'g' groups options involve a somewhat intricate sequence of decisions
2874 // about what to pass from the driver to the frontend, but by the time they
2875 // reach cc1 they've been factored into three well-defined orthogonal choices:
2876 // * what level of debug info to generate
2877 // * what dwarf version to write
2878 // * what debugger tuning to use
2879 // This avoids having to monkey around further in cc1 other than to disable
2880 // codeview if not running in a Windows environment. Perhaps even that
2881 // decision should be made in the driver as well though.
2882 unsigned DWARFVersion = 0;
2883 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2884
2885 bool SplitDWARFInlining =
2886 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2887 options::OPT_fno_split_dwarf_inlining, true);
2888
2889 Args.ClaimAllArgs(options::OPT_g_Group);
2890
2891 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2892
2893 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2894 // If the last option explicitly specified a debug-info level, use it.
2895 if (A->getOption().matches(options::OPT_gN_Group)) {
2896 DebugInfoKind = DebugLevelToInfoKind(*A);
2897 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2898 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2899 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2900 // This gets a bit more complicated if you've disabled inline info in the
2901 // skeleton CUs (SplitDWARFInlining) - then there's value in composing
2902 // split-dwarf and line-tables-only, so let those compose naturally in
2903 // that case.
2904 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2905 if (SplitDWARFArg) {
2906 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2907 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2908 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2909 SplitDWARFInlining))
2910 SplitDWARFArg = nullptr;
2911 } else if (SplitDWARFInlining)
2912 DebugInfoKind = codegenoptions::NoDebugInfo;
2913 }
2914 } else {
2915 // For any other 'g' option, use Limited.
2916 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2917 }
2918 }
2919
2920 // If a debugger tuning argument appeared, remember it.
2921 if (const Arg *A =
2922 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2923 if (A->getOption().matches(options::OPT_glldb))
2924 DebuggerTuning = llvm::DebuggerKind::LLDB;
2925 else if (A->getOption().matches(options::OPT_gsce))
2926 DebuggerTuning = llvm::DebuggerKind::SCE;
2927 else
2928 DebuggerTuning = llvm::DebuggerKind::GDB;
2929 }
2930
2931 // If a -gdwarf argument appeared, remember it.
2932 if (const Arg *A =
2933 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2934 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2935 DWARFVersion = DwarfVersionNum(A->getSpelling());
2936
2937 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2938 // argument parsing.
Reid Kleckner54af3e72018-02-26 22:55:33 +00002939 if (EmitCodeView) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002940 // DWARFVersion remains at 0 if no explicit choice was made.
2941 CmdArgs.push_back("-gcodeview");
2942 } else if (DWARFVersion == 0 &&
2943 DebugInfoKind != codegenoptions::NoDebugInfo) {
2944 DWARFVersion = TC.GetDefaultDwarfVersion();
2945 }
2946
2947 // We ignore flag -gstrict-dwarf for now.
2948 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2949 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2950
Paul Robinsona8280812017-09-29 21:25:07 +00002951 // Column info is included by default for everything except SCE and CodeView.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002952 // Clang doesn't track end columns, just starting columns, which, in theory,
2953 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2954 // debuggers don't handle missing end columns well, so it's better not to
2955 // include any column info.
2956 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00002957 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00002958 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002959 CmdArgs.push_back("-dwarf-column-info");
2960
2961 // FIXME: Move backend command line options to the module.
2962 // If -gline-tables-only is the last option it wins.
2963 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2964 Args.hasArg(options::OPT_gmodules)) {
2965 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2966 CmdArgs.push_back("-dwarf-ext-refs");
2967 CmdArgs.push_back("-fmodule-format=obj");
2968 }
2969
2970 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2971 // splitting and extraction.
2972 // FIXME: Currently only works on Linux.
2973 if (T.isOSLinux()) {
2974 if (!SplitDWARFInlining)
2975 CmdArgs.push_back("-fno-split-dwarf-inlining");
2976
2977 if (SplitDWARFArg) {
2978 if (DebugInfoKind == codegenoptions::NoDebugInfo)
2979 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2980 CmdArgs.push_back("-enable-split-dwarf");
2981 }
2982 }
2983
2984 // After we've dealt with all combinations of things that could
2985 // make DebugInfoKind be other than None or DebugLineTablesOnly,
2986 // figure out if we need to "upgrade" it to standalone debug info.
2987 // We parse these two '-f' options whether or not they will be used,
2988 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2989 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2990 options::OPT_fno_standalone_debug,
2991 TC.GetDefaultStandaloneDebug());
2992 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2993 DebugInfoKind = codegenoptions::FullDebugInfo;
2994
Scott Lindera2fbcef2018-02-26 17:32:31 +00002995 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, false)) {
2996 // Source embedding is a vendor extension to DWARF v5. By now we have
2997 // checked if a DWARF version was stated explicitly, and have otherwise
2998 // fallen back to the target default, so if this is still not at least 5 we
2999 // emit an error.
3000 if (DWARFVersion < 5)
3001 D.Diag(diag::err_drv_argument_only_allowed_with)
3002 << Args.getLastArg(options::OPT_gembed_source)->getAsString(Args)
3003 << "-gdwarf-5";
3004 CmdArgs.push_back("-gembed-source");
3005 }
3006
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003007 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3008 DebuggerTuning);
3009
3010 // -fdebug-macro turns on macro debug info generation.
3011 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3012 false))
3013 CmdArgs.push_back("-debug-info-macro");
3014
3015 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikiecb7b6af2018-06-28 22:58:04 +00003016 if (Args.hasFlag(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3017 false))
Peter Collingbourneb52e2362017-09-12 21:50:41 +00003018 CmdArgs.push_back("-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003019
3020 // -gdwarf-aranges turns on the emission of the aranges section in the
3021 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003022 // Always enabled for SCE tuning.
3023 if (Args.hasArg(options::OPT_gdwarf_aranges) ||
3024 DebuggerTuning == llvm::DebuggerKind::SCE) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003025 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003026 CmdArgs.push_back("-generate-arange-section");
3027 }
3028
3029 if (Args.hasFlag(options::OPT_fdebug_types_section,
3030 options::OPT_fno_debug_types_section, false)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003031 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003032 CmdArgs.push_back("-generate-type-units");
3033 }
3034
Paul Robinson1787f812017-09-28 18:37:02 +00003035 // Decide how to render forward declarations of template instantiations.
3036 // SCE wants full descriptions, others just get them in the name.
3037 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3038 CmdArgs.push_back("-debug-forward-template-params");
3039
Paul Robinsona8280812017-09-29 21:25:07 +00003040 // Do we need to explicitly import anonymous namespaces into the parent scope?
3041 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3042 CmdArgs.push_back("-dwarf-explicit-import");
3043
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003044 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
3045}
3046
David L. Jonesf561aba2017-03-08 01:02:16 +00003047void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3048 const InputInfo &Output, const InputInfoList &Inputs,
3049 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003050 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003051 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3052 const std::string &TripleStr = Triple.getTriple();
3053
3054 bool KernelOrKext =
3055 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3056 const Driver &D = getToolChain().getDriver();
3057 ArgStringList CmdArgs;
3058
3059 // Check number of inputs for sanity. We need at least one input.
3060 assert(Inputs.size() >= 1 && "Must have at least one input.");
3061 const InputInfo &Input = Inputs[0];
Yaxun Liu398612b2018-05-08 21:02:12 +00003062 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003063 // device-side compilations). OpenMP device jobs also take the host IR as a
3064 // second input. All other jobs are expected to have exactly one
3065 // input.
3066 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003067 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003068 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Yaxun Liu398612b2018-05-08 21:02:12 +00003069 assert((IsCuda || IsHIP || (IsOpenMPDevice && Inputs.size() == 2) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003070 Inputs.size() == 1) &&
3071 "Unable to handle multiple inputs.");
3072
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003073 const llvm::Triple *AuxTriple =
3074 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3075
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003076 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3077 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3078 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003079 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003080
Yaxun Liu398612b2018-05-08 21:02:12 +00003081 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3082 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3083 // Windows), we need to pass Windows-specific flags to cc1.
3084 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003085 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3086 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3087 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3088 }
3089
3090 // C++ is not supported for IAMCU.
3091 if (IsIAMCU && types::isCXX(Input.getType()))
3092 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3093
3094 // Invoke ourselves in -cc1 mode.
3095 //
3096 // FIXME: Implement custom jobs for internal actions.
3097 CmdArgs.push_back("-cc1");
3098
3099 // Add the "effective" target triple.
3100 CmdArgs.push_back("-triple");
3101 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3102
3103 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3104 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3105 Args.ClaimAllArgs(options::OPT_MJ);
3106 }
3107
Yaxun Liu398612b2018-05-08 21:02:12 +00003108 if (IsCuda || IsHIP) {
3109 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3110 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003111 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003112 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3113 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003114 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3115 ->getTriple()
3116 .normalize();
3117 else
Yaxun Liu398612b2018-05-08 21:02:12 +00003118 NormalizedTriple =
3119 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3120 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3121 ->getTriple()
3122 .normalize();
David L. Jonesf561aba2017-03-08 01:02:16 +00003123
3124 CmdArgs.push_back("-aux-triple");
3125 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3126 }
3127
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003128 if (IsOpenMPDevice) {
3129 // We have to pass the triple of the host if compiling for an OpenMP device.
3130 std::string NormalizedTriple =
3131 C.getSingleOffloadToolChain<Action::OFK_Host>()
3132 ->getTriple()
3133 .normalize();
3134 CmdArgs.push_back("-aux-triple");
3135 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3136 }
3137
David L. Jonesf561aba2017-03-08 01:02:16 +00003138 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3139 Triple.getArch() == llvm::Triple::thumb)) {
3140 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3141 unsigned Version;
3142 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3143 if (Version < 7)
3144 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3145 << TripleStr;
3146 }
3147
3148 // Push all default warning arguments that are specific to
3149 // the given target. These come before user provided warning options
3150 // are provided.
3151 getToolChain().addClangWarningOptions(CmdArgs);
3152
3153 // Select the appropriate action.
3154 RewriteKind rewriteKind = RK_None;
3155
3156 if (isa<AnalyzeJobAction>(JA)) {
3157 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3158 CmdArgs.push_back("-analyze");
3159 } else if (isa<MigrateJobAction>(JA)) {
3160 CmdArgs.push_back("-migrate");
3161 } else if (isa<PreprocessJobAction>(JA)) {
3162 if (Output.getType() == types::TY_Dependencies)
3163 CmdArgs.push_back("-Eonly");
3164 else {
3165 CmdArgs.push_back("-E");
3166 if (Args.hasArg(options::OPT_rewrite_objc) &&
3167 !Args.hasArg(options::OPT_g_Group))
3168 CmdArgs.push_back("-P");
3169 }
3170 } else if (isa<AssembleJobAction>(JA)) {
3171 CmdArgs.push_back("-emit-obj");
3172
3173 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3174
3175 // Also ignore explicit -force_cpusubtype_ALL option.
3176 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3177 } else if (isa<PrecompileJobAction>(JA)) {
3178 // Use PCH if the user requested it.
3179 bool UsePCH = D.CCCUsePCH;
3180
3181 if (JA.getType() == types::TY_Nothing)
3182 CmdArgs.push_back("-fsyntax-only");
3183 else if (JA.getType() == types::TY_ModuleFile)
3184 CmdArgs.push_back("-emit-module-interface");
3185 else if (UsePCH)
3186 CmdArgs.push_back("-emit-pch");
3187 else
3188 CmdArgs.push_back("-emit-pth");
3189 } else if (isa<VerifyPCHJobAction>(JA)) {
3190 CmdArgs.push_back("-verify-pch");
3191 } else {
3192 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3193 "Invalid action for clang tool.");
3194 if (JA.getType() == types::TY_Nothing) {
3195 CmdArgs.push_back("-fsyntax-only");
3196 } else if (JA.getType() == types::TY_LLVM_IR ||
3197 JA.getType() == types::TY_LTO_IR) {
3198 CmdArgs.push_back("-emit-llvm");
3199 } else if (JA.getType() == types::TY_LLVM_BC ||
3200 JA.getType() == types::TY_LTO_BC) {
3201 CmdArgs.push_back("-emit-llvm-bc");
3202 } else if (JA.getType() == types::TY_PP_Asm) {
3203 CmdArgs.push_back("-S");
3204 } else if (JA.getType() == types::TY_AST) {
3205 CmdArgs.push_back("-emit-pch");
3206 } else if (JA.getType() == types::TY_ModuleFile) {
3207 CmdArgs.push_back("-module-file-info");
3208 } else if (JA.getType() == types::TY_RewrittenObjC) {
3209 CmdArgs.push_back("-rewrite-objc");
3210 rewriteKind = RK_NonFragile;
3211 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3212 CmdArgs.push_back("-rewrite-objc");
3213 rewriteKind = RK_Fragile;
3214 } else {
3215 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3216 }
3217
3218 // Preserve use-list order by default when emitting bitcode, so that
3219 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3220 // same result as running passes here. For LTO, we don't need to preserve
3221 // the use-list order, since serialization to bitcode is part of the flow.
3222 if (JA.getType() == types::TY_LLVM_BC)
3223 CmdArgs.push_back("-emit-llvm-uselists");
3224
Artem Belevichecb178b2018-03-21 22:22:59 +00003225 // Device-side jobs do not support LTO.
3226 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3227 JA.isDeviceOffloading(Action::OFK_Host));
3228
3229 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003230 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3231
Paul Robinsond23f2a82017-07-13 21:25:47 +00003232 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3233 // does not support LTO unit features (CFI, whole program vtable opt)
3234 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003235 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003236 D.getLTOMode() == LTOK_Full)
3237 CmdArgs.push_back("-flto-unit");
3238 }
3239 }
3240
3241 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3242 if (!types::isLLVMIR(Input.getType()))
3243 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3244 << "-x ir";
3245 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3246 }
3247
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003248 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003249 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3250
David L. Jonesf561aba2017-03-08 01:02:16 +00003251 // Embed-bitcode option.
3252 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3253 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3254 // Add flags implied by -fembed-bitcode.
3255 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3256 // Disable all llvm IR level optimizations.
3257 CmdArgs.push_back("-disable-llvm-passes");
3258 }
3259 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3260 CmdArgs.push_back("-fembed-bitcode=marker");
3261
3262 // We normally speed up the clang process a bit by skipping destructors at
3263 // exit, but when we're generating diagnostics we can rely on some of the
3264 // cleanup.
3265 if (!C.isForDiagnostics())
3266 CmdArgs.push_back("-disable-free");
3267
David L. Jonesf561aba2017-03-08 01:02:16 +00003268#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003269 const bool IsAssertBuild = false;
3270#else
3271 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003272#endif
3273
Eric Fiselier123c7492018-02-07 18:36:51 +00003274 // Disable the verification pass in -asserts builds.
3275 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003276 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003277
3278 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003279 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3280 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003281 CmdArgs.push_back("-discard-value-names");
3282
David L. Jonesf561aba2017-03-08 01:02:16 +00003283 // Set the main file name, so that debug info works even with
3284 // -save-temps.
3285 CmdArgs.push_back("-main-file-name");
3286 CmdArgs.push_back(getBaseInputName(Args, Input));
3287
3288 // Some flags which affect the language (via preprocessor
3289 // defines).
3290 if (Args.hasArg(options::OPT_static))
3291 CmdArgs.push_back("-static-define");
3292
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003293 if (isa<AnalyzeJobAction>(JA))
3294 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003295
3296 CheckCodeGenerationOptions(D, Args);
3297
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003298 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3299 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3300 if (FunctionAlignment) {
3301 CmdArgs.push_back("-function-alignment");
3302 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3303 }
3304
David L. Jonesf561aba2017-03-08 01:02:16 +00003305 llvm::Reloc::Model RelocationModel;
3306 unsigned PICLevel;
3307 bool IsPIE;
3308 std::tie(RelocationModel, PICLevel, IsPIE) =
3309 ParsePICArgs(getToolChain(), Args);
3310
3311 const char *RMName = RelocationModelName(RelocationModel);
3312
3313 if ((RelocationModel == llvm::Reloc::ROPI ||
3314 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3315 types::isCXX(Input.getType()) &&
3316 !Args.hasArg(options::OPT_fallow_unsupported))
3317 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3318
3319 if (RMName) {
3320 CmdArgs.push_back("-mrelocation-model");
3321 CmdArgs.push_back(RMName);
3322 }
3323 if (PICLevel > 0) {
3324 CmdArgs.push_back("-pic-level");
3325 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3326 if (IsPIE)
3327 CmdArgs.push_back("-pic-is-pie");
3328 }
3329
3330 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3331 CmdArgs.push_back("-meabi");
3332 CmdArgs.push_back(A->getValue());
3333 }
3334
3335 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003336 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3337 if (!getToolChain().isThreadModelSupported(A->getValue()))
3338 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3339 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003340 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003341 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003342 else
3343 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3344
3345 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3346
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003347 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3348 options::OPT_fno_merge_all_constants, false))
3349 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003350
3351 // LLVM Code Generator Options.
3352
3353 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3354 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3355 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3356 options::OPT_frewrite_map_file_EQ)) {
3357 StringRef Map = A->getValue();
3358 if (!llvm::sys::fs::exists(Map)) {
3359 D.Diag(diag::err_drv_no_such_file) << Map;
3360 } else {
3361 CmdArgs.push_back("-frewrite-map-file");
3362 CmdArgs.push_back(A->getValue());
3363 A->claim();
3364 }
3365 }
3366 }
3367
3368 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3369 StringRef v = A->getValue();
3370 CmdArgs.push_back("-mllvm");
3371 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3372 A->claim();
3373 }
3374
3375 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3376 true))
3377 CmdArgs.push_back("-fno-jump-tables");
3378
Dehao Chen5e97f232017-08-24 21:37:33 +00003379 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3380 options::OPT_fno_profile_sample_accurate, false))
3381 CmdArgs.push_back("-fprofile-sample-accurate");
3382
David L. Jonesf561aba2017-03-08 01:02:16 +00003383 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3384 options::OPT_fno_preserve_as_comments, true))
3385 CmdArgs.push_back("-fno-preserve-as-comments");
3386
3387 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3388 CmdArgs.push_back("-mregparm");
3389 CmdArgs.push_back(A->getValue());
3390 }
3391
3392 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3393 options::OPT_freg_struct_return)) {
3394 if (getToolChain().getArch() != llvm::Triple::x86) {
3395 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003396 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003397 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3398 CmdArgs.push_back("-fpcc-struct-return");
3399 } else {
3400 assert(A->getOption().matches(options::OPT_freg_struct_return));
3401 CmdArgs.push_back("-freg-struct-return");
3402 }
3403 }
3404
3405 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3406 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3407
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003408 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003409 CmdArgs.push_back("-mdisable-fp-elim");
3410 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3411 options::OPT_fno_zero_initialized_in_bss))
3412 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3413
3414 bool OFastEnabled = isOptimizationLevelFast(Args);
3415 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3416 // enabled. This alias option is being used to simplify the hasFlag logic.
3417 OptSpecifier StrictAliasingAliasOption =
3418 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3419 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3420 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003421 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003422 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3423 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3424 CmdArgs.push_back("-relaxed-aliasing");
3425 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3426 options::OPT_fno_struct_path_tbaa))
3427 CmdArgs.push_back("-no-struct-path-tbaa");
3428 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3429 false))
3430 CmdArgs.push_back("-fstrict-enums");
3431 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3432 true))
3433 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003434 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3435 options::OPT_fno_allow_editor_placeholders, false))
3436 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003437 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3438 options::OPT_fno_strict_vtable_pointers,
3439 false))
3440 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003441 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3442 options::OPT_fno_force_emit_vtables,
3443 false))
3444 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003445 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3446 options::OPT_fno_optimize_sibling_calls))
3447 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003448 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003449 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003450 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003451
Wei Mi9b3d6272017-10-16 16:50:27 +00003452 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3453 options::OPT_fno_fine_grained_bitfield_accesses);
3454
David L. Jonesf561aba2017-03-08 01:02:16 +00003455 // Handle segmented stacks.
3456 if (Args.hasArg(options::OPT_fsplit_stack))
3457 CmdArgs.push_back("-split-stacks");
3458
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003459 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003460
3461 // Decide whether to use verbose asm. Verbose assembly is the default on
3462 // toolchains which have the integrated assembler on by default.
3463 bool IsIntegratedAssemblerDefault =
3464 getToolChain().IsIntegratedAssemblerDefault();
3465 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3466 IsIntegratedAssemblerDefault) ||
3467 Args.hasArg(options::OPT_dA))
3468 CmdArgs.push_back("-masm-verbose");
3469
Peter Collingbourned86ca942018-06-14 00:03:41 +00003470 if (!getToolChain().useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00003471 CmdArgs.push_back("-no-integrated-as");
3472
3473 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3474 CmdArgs.push_back("-mdebug-pass");
3475 CmdArgs.push_back("Structure");
3476 }
3477 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3478 CmdArgs.push_back("-mdebug-pass");
3479 CmdArgs.push_back("Arguments");
3480 }
3481
3482 // Enable -mconstructor-aliases except on darwin, where we have to work around
3483 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3484 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003485 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003486 CmdArgs.push_back("-mconstructor-aliases");
3487
3488 // Darwin's kernel doesn't support guard variables; just die if we
3489 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003490 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003491 CmdArgs.push_back("-fforbid-guard-variables");
3492
3493 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3494 false)) {
3495 CmdArgs.push_back("-mms-bitfields");
3496 }
3497
3498 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3499 options::OPT_mno_pie_copy_relocations,
3500 false)) {
3501 CmdArgs.push_back("-mpie-copy-relocations");
3502 }
3503
Sriraman Tallam5c651482017-11-07 19:37:51 +00003504 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3505 CmdArgs.push_back("-fno-plt");
3506 }
3507
Vedant Kumardf502592017-09-12 22:51:53 +00003508 // -fhosted is default.
3509 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3510 // use Freestanding.
3511 bool Freestanding =
3512 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3513 KernelOrKext;
3514 if (Freestanding)
3515 CmdArgs.push_back("-ffreestanding");
3516
David L. Jonesf561aba2017-03-08 01:02:16 +00003517 // This is a coarse approximation of what llvm-gcc actually does, both
3518 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3519 // complicated ways.
3520 bool AsynchronousUnwindTables =
3521 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3522 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003523 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003524 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003525 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003526 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3527 AsynchronousUnwindTables))
3528 CmdArgs.push_back("-munwind-tables");
3529
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003530 getToolChain().addClangTargetOptions(Args, CmdArgs,
3531 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003532
3533 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3534 CmdArgs.push_back("-mlimit-float-precision");
3535 CmdArgs.push_back(A->getValue());
3536 }
3537
3538 // FIXME: Handle -mtune=.
3539 (void)Args.hasArg(options::OPT_mtune_EQ);
3540
3541 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3542 CmdArgs.push_back("-mcode-model");
3543 CmdArgs.push_back(A->getValue());
3544 }
3545
3546 // Add the target cpu
3547 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3548 if (!CPU.empty()) {
3549 CmdArgs.push_back("-target-cpu");
3550 CmdArgs.push_back(Args.MakeArgString(CPU));
3551 }
3552
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003553 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003554
David L. Jonesf561aba2017-03-08 01:02:16 +00003555 // These two are potentially updated by AddClangCLArgs.
3556 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3557 bool EmitCodeView = false;
3558
3559 // Add clang-cl arguments.
3560 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003561 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003562 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
Reid Kleckner54af3e72018-02-26 22:55:33 +00003563 else
3564 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
David L. Jonesf561aba2017-03-08 01:02:16 +00003565
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003566 const Arg *SplitDWARFArg = nullptr;
3567 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3568 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3569
3570 // Add the split debug info name to the command lines here so we
3571 // can propagate it to the backend.
3572 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3573 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3574 isa<BackendJobAction>(JA));
3575 const char *SplitDWARFOut;
3576 if (SplitDWARF) {
3577 CmdArgs.push_back("-split-dwarf-file");
3578 SplitDWARFOut = SplitDebugName(Args, Input);
3579 CmdArgs.push_back(SplitDWARFOut);
3580 }
3581
David L. Jonesf561aba2017-03-08 01:02:16 +00003582 // Pass the linker version in use.
3583 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3584 CmdArgs.push_back("-target-linker-version");
3585 CmdArgs.push_back(A->getValue());
3586 }
3587
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003588 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003589 CmdArgs.push_back("-momit-leaf-frame-pointer");
3590
3591 // Explicitly error on some things we know we don't support and can't just
3592 // ignore.
3593 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3594 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003595 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003596 getToolChain().getArch() == llvm::Triple::x86) {
3597 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3598 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3599 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3600 << Unsupported->getOption().getName();
3601 }
Eric Christopher758aad72017-03-21 22:06:18 +00003602 // The faltivec option has been superseded by the maltivec option.
3603 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3604 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3605 << Unsupported->getOption().getName()
3606 << "please use -maltivec and include altivec.h explicitly";
3607 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3608 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3609 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003610 }
3611
3612 Args.AddAllArgs(CmdArgs, options::OPT_v);
3613 Args.AddLastArg(CmdArgs, options::OPT_H);
3614 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3615 CmdArgs.push_back("-header-include-file");
3616 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3617 : "-");
3618 }
3619 Args.AddLastArg(CmdArgs, options::OPT_P);
3620 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3621
3622 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3623 CmdArgs.push_back("-diagnostic-log-file");
3624 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3625 : "-");
3626 }
3627
David L. Jonesf561aba2017-03-08 01:02:16 +00003628 bool UseSeparateSections = isUseSeparateSections(Triple);
3629
3630 if (Args.hasFlag(options::OPT_ffunction_sections,
3631 options::OPT_fno_function_sections, UseSeparateSections)) {
3632 CmdArgs.push_back("-ffunction-sections");
3633 }
3634
3635 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3636 UseSeparateSections)) {
3637 CmdArgs.push_back("-fdata-sections");
3638 }
3639
3640 if (!Args.hasFlag(options::OPT_funique_section_names,
3641 options::OPT_fno_unique_section_names, true))
3642 CmdArgs.push_back("-fno-unique-section-names");
3643
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003644 if (auto *A = Args.getLastArg(
3645 options::OPT_finstrument_functions,
3646 options::OPT_finstrument_functions_after_inlining,
3647 options::OPT_finstrument_function_entry_bare))
3648 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003649
Artem Belevichc30bcad2018-01-24 17:41:02 +00003650 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3651 // sampling, overhead of call arc collection is way too high and there's no
3652 // way to collect the output.
3653 if (!Triple.isNVPTX())
3654 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003655
Richard Smithf667ad52017-08-26 01:04:35 +00003656 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3657 ABICompatArg->render(Args, CmdArgs);
3658
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003659 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
3660 if (RawTriple.isPS4CPU()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003661 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003662 PS4cpu::addSanitizerArgs(getToolChain(), CmdArgs);
3663 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003664
3665 // Pass options for controlling the default header search paths.
3666 if (Args.hasArg(options::OPT_nostdinc)) {
3667 CmdArgs.push_back("-nostdsysteminc");
3668 CmdArgs.push_back("-nobuiltininc");
3669 } else {
3670 if (Args.hasArg(options::OPT_nostdlibinc))
3671 CmdArgs.push_back("-nostdsysteminc");
3672 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3673 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3674 }
3675
3676 // Pass the path to compiler resource files.
3677 CmdArgs.push_back("-resource-dir");
3678 CmdArgs.push_back(D.ResourceDir.c_str());
3679
3680 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3681
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003682 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003683
3684 // Add preprocessing options like -I, -D, etc. if we are using the
3685 // preprocessor.
3686 //
3687 // FIXME: Support -fpreprocessed
3688 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3689 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3690
3691 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3692 // that "The compiler can only warn and ignore the option if not recognized".
3693 // When building with ccache, it will pass -D options to clang even on
3694 // preprocessed inputs and configure concludes that -fPIC is not supported.
3695 Args.ClaimAllArgs(options::OPT_D);
3696
3697 // Manually translate -O4 to -O3; let clang reject others.
3698 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3699 if (A->getOption().matches(options::OPT_O4)) {
3700 CmdArgs.push_back("-O3");
3701 D.Diag(diag::warn_O4_is_O3);
3702 } else {
3703 A->render(Args, CmdArgs);
3704 }
3705 }
3706
3707 // Warn about ignored options to clang.
3708 for (const Arg *A :
3709 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3710 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3711 A->claim();
3712 }
3713
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003714 for (const Arg *A :
3715 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3716 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3717 A->claim();
3718 }
3719
David L. Jonesf561aba2017-03-08 01:02:16 +00003720 claimNoWarnArgs(Args);
3721
3722 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3723
3724 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3725 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3726 CmdArgs.push_back("-pedantic");
3727 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3728 Args.AddLastArg(CmdArgs, options::OPT_w);
3729
Leonard Chanf921d852018-06-04 16:07:52 +00003730 // Fixed point flags
3731 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
3732 /*Default=*/false))
3733 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
3734
David L. Jonesf561aba2017-03-08 01:02:16 +00003735 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3736 // (-ansi is equivalent to -std=c89 or -std=c++98).
3737 //
3738 // If a std is supplied, only add -trigraphs if it follows the
3739 // option.
3740 bool ImplyVCPPCXXVer = false;
3741 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3742 if (Std->getOption().matches(options::OPT_ansi))
3743 if (types::isCXX(InputType))
3744 CmdArgs.push_back("-std=c++98");
3745 else
3746 CmdArgs.push_back("-std=c89");
3747 else
3748 Std->render(Args, CmdArgs);
3749
3750 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3751 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3752 options::OPT_ftrigraphs,
3753 options::OPT_fno_trigraphs))
3754 if (A != Std)
3755 A->render(Args, CmdArgs);
3756 } else {
3757 // Honor -std-default.
3758 //
3759 // FIXME: Clang doesn't correctly handle -std= when the input language
3760 // doesn't match. For the time being just ignore this for C++ inputs;
3761 // eventually we want to do all the standard defaulting here instead of
3762 // splitting it between the driver and clang -cc1.
3763 if (!types::isCXX(InputType))
3764 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3765 /*Joined=*/true);
3766 else if (IsWindowsMSVC)
3767 ImplyVCPPCXXVer = true;
3768
3769 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3770 options::OPT_fno_trigraphs);
3771 }
3772
3773 // GCC's behavior for -Wwrite-strings is a bit strange:
3774 // * In C, this "warning flag" changes the types of string literals from
3775 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3776 // for the discarded qualifier.
3777 // * In C++, this is just a normal warning flag.
3778 //
3779 // Implementing this warning correctly in C is hard, so we follow GCC's
3780 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3781 // a non-const char* in C, rather than using this crude hack.
3782 if (!types::isCXX(InputType)) {
3783 // FIXME: This should behave just like a warning flag, and thus should also
3784 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3785 Arg *WriteStrings =
3786 Args.getLastArg(options::OPT_Wwrite_strings,
3787 options::OPT_Wno_write_strings, options::OPT_w);
3788 if (WriteStrings &&
3789 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3790 CmdArgs.push_back("-fconst-strings");
3791 }
3792
3793 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3794 // during C++ compilation, which it is by default. GCC keeps this define even
3795 // in the presence of '-w', match this behavior bug-for-bug.
3796 if (types::isCXX(InputType) &&
3797 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3798 true)) {
3799 CmdArgs.push_back("-fdeprecated-macro");
3800 }
3801
3802 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3803 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3804 if (Asm->getOption().matches(options::OPT_fasm))
3805 CmdArgs.push_back("-fgnu-keywords");
3806 else
3807 CmdArgs.push_back("-fno-gnu-keywords");
3808 }
3809
3810 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3811 CmdArgs.push_back("-fno-dwarf-directory-asm");
3812
3813 if (ShouldDisableAutolink(Args, getToolChain()))
3814 CmdArgs.push_back("-fno-autolink");
3815
3816 // Add in -fdebug-compilation-dir if necessary.
3817 addDebugCompDirArg(Args, CmdArgs);
3818
Paul Robinson9b292b42018-07-10 15:15:24 +00003819 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003820
3821 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3822 options::OPT_ftemplate_depth_EQ)) {
3823 CmdArgs.push_back("-ftemplate-depth");
3824 CmdArgs.push_back(A->getValue());
3825 }
3826
3827 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3828 CmdArgs.push_back("-foperator-arrow-depth");
3829 CmdArgs.push_back(A->getValue());
3830 }
3831
3832 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3833 CmdArgs.push_back("-fconstexpr-depth");
3834 CmdArgs.push_back(A->getValue());
3835 }
3836
3837 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3838 CmdArgs.push_back("-fconstexpr-steps");
3839 CmdArgs.push_back(A->getValue());
3840 }
3841
3842 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3843 CmdArgs.push_back("-fbracket-depth");
3844 CmdArgs.push_back(A->getValue());
3845 }
3846
3847 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3848 options::OPT_Wlarge_by_value_copy_def)) {
3849 if (A->getNumValues()) {
3850 StringRef bytes = A->getValue();
3851 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3852 } else
3853 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3854 }
3855
3856 if (Args.hasArg(options::OPT_relocatable_pch))
3857 CmdArgs.push_back("-relocatable-pch");
3858
3859 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3860 CmdArgs.push_back("-fconstant-string-class");
3861 CmdArgs.push_back(A->getValue());
3862 }
3863
3864 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3865 CmdArgs.push_back("-ftabstop");
3866 CmdArgs.push_back(A->getValue());
3867 }
3868
Sean Eveson5110d4f2018-01-08 13:42:26 +00003869 if (Args.hasFlag(options::OPT_fstack_size_section,
3870 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3871 CmdArgs.push_back("-fstack-size-section");
3872
David L. Jonesf561aba2017-03-08 01:02:16 +00003873 CmdArgs.push_back("-ferror-limit");
3874 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3875 CmdArgs.push_back(A->getValue());
3876 else
3877 CmdArgs.push_back("19");
3878
3879 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3880 CmdArgs.push_back("-fmacro-backtrace-limit");
3881 CmdArgs.push_back(A->getValue());
3882 }
3883
3884 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3885 CmdArgs.push_back("-ftemplate-backtrace-limit");
3886 CmdArgs.push_back(A->getValue());
3887 }
3888
3889 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3890 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3891 CmdArgs.push_back(A->getValue());
3892 }
3893
3894 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3895 CmdArgs.push_back("-fspell-checking-limit");
3896 CmdArgs.push_back(A->getValue());
3897 }
3898
3899 // Pass -fmessage-length=.
3900 CmdArgs.push_back("-fmessage-length");
3901 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3902 CmdArgs.push_back(A->getValue());
3903 } else {
3904 // If -fmessage-length=N was not specified, determine whether this is a
3905 // terminal and, if so, implicitly define -fmessage-length appropriately.
3906 unsigned N = llvm::sys::Process::StandardErrColumns();
3907 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3908 }
3909
3910 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3911 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3912 options::OPT_fvisibility_ms_compat)) {
3913 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3914 CmdArgs.push_back("-fvisibility");
3915 CmdArgs.push_back(A->getValue());
3916 } else {
3917 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3918 CmdArgs.push_back("-fvisibility");
3919 CmdArgs.push_back("hidden");
3920 CmdArgs.push_back("-ftype-visibility");
3921 CmdArgs.push_back("default");
3922 }
3923 }
3924
3925 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3926
3927 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3928
David L. Jonesf561aba2017-03-08 01:02:16 +00003929 // Forward -f (flag) options which we can pass directly.
3930 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3931 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00003932 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003933 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00003934 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
3935 options::OPT_fno_emulated_tls);
3936
David L. Jonesf561aba2017-03-08 01:02:16 +00003937 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003938 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003939 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003940
David L. Jonesf561aba2017-03-08 01:02:16 +00003941 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3942 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3943
3944 // Forward flags for OpenMP. We don't do this if the current action is an
3945 // device offloading action other than OpenMP.
3946 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3947 options::OPT_fno_openmp, false) &&
3948 (JA.isDeviceOffloading(Action::OFK_None) ||
3949 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003950 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003951 case Driver::OMPRT_OMP:
3952 case Driver::OMPRT_IOMP5:
3953 // Clang can generate useful OpenMP code for these two runtime libraries.
3954 CmdArgs.push_back("-fopenmp");
3955
3956 // If no option regarding the use of TLS in OpenMP codegeneration is
3957 // given, decide a default based on the target. Otherwise rely on the
3958 // options and pass the right information to the frontend.
3959 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3960 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3961 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00003962 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
3963 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00003964 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00003965
3966 // When in OpenMP offloading mode with NVPTX target, forward
3967 // cuda-mode flag
3968 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
3969 options::OPT_fno_openmp_cuda_mode);
David L. Jonesf561aba2017-03-08 01:02:16 +00003970 break;
3971 default:
3972 // By default, if Clang doesn't know how to generate useful OpenMP code
3973 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3974 // down to the actual compilation.
3975 // FIXME: It would be better to have a mode which *only* omits IR
3976 // generation based on the OpenMP support so that we get consistent
3977 // semantic analysis, etc.
3978 break;
3979 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00003980 } else {
3981 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
3982 options::OPT_fno_openmp_simd);
3983 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00003984 }
3985
3986 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3987 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3988
Dean Michael Berris835832d2017-03-30 00:29:36 +00003989 const XRayArgs &XRay = getToolChain().getXRayArgs();
3990 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
3991
David L. Jonesf561aba2017-03-08 01:02:16 +00003992 if (getToolChain().SupportsProfiling())
3993 Args.AddLastArg(CmdArgs, options::OPT_pg);
3994
3995 if (getToolChain().SupportsProfiling())
3996 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3997
3998 // -flax-vector-conversions is default.
3999 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4000 options::OPT_fno_lax_vector_conversions))
4001 CmdArgs.push_back("-fno-lax-vector-conversions");
4002
4003 if (Args.getLastArg(options::OPT_fapple_kext) ||
4004 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4005 CmdArgs.push_back("-fapple-kext");
4006
4007 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4008 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4009 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4010 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4011 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4012
4013 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4014 CmdArgs.push_back("-ftrapv-handler");
4015 CmdArgs.push_back(A->getValue());
4016 }
4017
4018 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4019
4020 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4021 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4022 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4023 if (A->getOption().matches(options::OPT_fwrapv))
4024 CmdArgs.push_back("-fwrapv");
4025 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4026 options::OPT_fno_strict_overflow)) {
4027 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4028 CmdArgs.push_back("-fwrapv");
4029 }
4030
4031 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4032 options::OPT_fno_reroll_loops))
4033 if (A->getOption().matches(options::OPT_freroll_loops))
4034 CmdArgs.push_back("-freroll-loops");
4035
4036 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4037 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4038 options::OPT_fno_unroll_loops);
4039
4040 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4041
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004042 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004043
4044 // Translate -mstackrealign
4045 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4046 false))
4047 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4048
4049 if (Args.hasArg(options::OPT_mstack_alignment)) {
4050 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4051 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4052 }
4053
4054 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4055 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4056
4057 if (!Size.empty())
4058 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4059 else
4060 CmdArgs.push_back("-mstack-probe-size=0");
4061 }
4062
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004063 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4064 options::OPT_mno_stack_arg_probe, true))
4065 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4066
David L. Jonesf561aba2017-03-08 01:02:16 +00004067 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4068 options::OPT_mno_restrict_it)) {
4069 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004070 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004071 CmdArgs.push_back("-arm-restrict-it");
4072 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004073 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004074 CmdArgs.push_back("-arm-no-restrict-it");
4075 }
4076 } else if (Triple.isOSWindows() &&
4077 (Triple.getArch() == llvm::Triple::arm ||
4078 Triple.getArch() == llvm::Triple::thumb)) {
4079 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004080 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004081 CmdArgs.push_back("-arm-restrict-it");
4082 }
4083
4084 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004085 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004086
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004087 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4088 CmdArgs.push_back(
4089 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4090 }
4091
David L. Jonesf561aba2017-03-08 01:02:16 +00004092 // Forward -f options with positive and negative forms; we translate
4093 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004094 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004095 StringRef fname = A->getValue();
4096 if (!llvm::sys::fs::exists(fname))
4097 D.Diag(diag::err_drv_no_such_file) << fname;
4098 else
4099 A->render(Args, CmdArgs);
4100 }
4101
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004102 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004103
4104 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4105 options::OPT_fno_assume_sane_operator_new))
4106 CmdArgs.push_back("-fno-assume-sane-operator-new");
4107
4108 // -fblocks=0 is default.
4109 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4110 getToolChain().IsBlocksDefault()) ||
4111 (Args.hasArg(options::OPT_fgnu_runtime) &&
4112 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4113 !Args.hasArg(options::OPT_fno_blocks))) {
4114 CmdArgs.push_back("-fblocks");
4115
4116 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4117 !getToolChain().hasBlocksRuntime())
4118 CmdArgs.push_back("-fblocks-runtime-optional");
4119 }
4120
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004121 // -fencode-extended-block-signature=1 is default.
4122 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4123 CmdArgs.push_back("-fencode-extended-block-signature");
4124
David L. Jonesf561aba2017-03-08 01:02:16 +00004125 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4126 false) &&
4127 types::isCXX(InputType)) {
4128 CmdArgs.push_back("-fcoroutines-ts");
4129 }
4130
Aaron Ballman61736552017-10-21 20:28:58 +00004131 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4132 options::OPT_fno_double_square_bracket_attributes);
4133
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004134 bool HaveModules = false;
4135 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004136
4137 // -faccess-control is default.
4138 if (Args.hasFlag(options::OPT_fno_access_control,
4139 options::OPT_faccess_control, false))
4140 CmdArgs.push_back("-fno-access-control");
4141
4142 // -felide-constructors is the default.
4143 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4144 options::OPT_felide_constructors, false))
4145 CmdArgs.push_back("-fno-elide-constructors");
4146
4147 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4148
4149 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004150 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004151 CmdArgs.push_back("-fno-rtti");
4152
4153 // -fshort-enums=0 is default for all architectures except Hexagon.
4154 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4155 getToolChain().getArch() == llvm::Triple::hexagon))
4156 CmdArgs.push_back("-fshort-enums");
4157
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004158 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004159
4160 // -fuse-cxa-atexit is default.
4161 if (!Args.hasFlag(
4162 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004163 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004164 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004165 getToolChain().getArch() != llvm::Triple::hexagon &&
4166 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004167 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4168 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004169 KernelOrKext)
4170 CmdArgs.push_back("-fno-use-cxa-atexit");
4171
Akira Hatanaka617e2612018-04-17 18:41:52 +00004172 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4173 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004174 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004175 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4176
David L. Jonesf561aba2017-03-08 01:02:16 +00004177 // -fms-extensions=0 is default.
4178 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4179 IsWindowsMSVC))
4180 CmdArgs.push_back("-fms-extensions");
4181
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004182 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004183 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004184 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004185 CmdArgs.push_back("-fuse-line-directives");
4186
4187 // -fms-compatibility=0 is default.
4188 if (Args.hasFlag(options::OPT_fms_compatibility,
4189 options::OPT_fno_ms_compatibility,
4190 (IsWindowsMSVC &&
4191 Args.hasFlag(options::OPT_fms_extensions,
4192 options::OPT_fno_ms_extensions, true))))
4193 CmdArgs.push_back("-fms-compatibility");
4194
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004195 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004196 if (!MSVT.empty())
4197 CmdArgs.push_back(
4198 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4199
4200 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4201 if (ImplyVCPPCXXVer) {
4202 StringRef LanguageStandard;
4203 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4204 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4205 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004206 .Case("c++17", "-std=c++17")
4207 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004208 .Default("");
4209 if (LanguageStandard.empty())
4210 D.Diag(clang::diag::warn_drv_unused_argument)
4211 << StdArg->getAsString(Args);
4212 }
4213
4214 if (LanguageStandard.empty()) {
4215 if (IsMSVC2015Compatible)
4216 LanguageStandard = "-std=c++14";
4217 else
4218 LanguageStandard = "-std=c++11";
4219 }
4220
4221 CmdArgs.push_back(LanguageStandard.data());
4222 }
4223
4224 // -fno-borland-extensions is default.
4225 if (Args.hasFlag(options::OPT_fborland_extensions,
4226 options::OPT_fno_borland_extensions, false))
4227 CmdArgs.push_back("-fborland-extensions");
4228
4229 // -fno-declspec is default, except for PS4.
4230 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004231 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004232 CmdArgs.push_back("-fdeclspec");
4233 else if (Args.hasArg(options::OPT_fno_declspec))
4234 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4235
4236 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4237 // than 19.
4238 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4239 options::OPT_fno_threadsafe_statics,
4240 !IsWindowsMSVC || IsMSVC2015Compatible))
4241 CmdArgs.push_back("-fno-threadsafe-statics");
4242
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004243 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004244 // Many old Windows SDK versions require this to parse.
4245 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4246 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004247 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4248 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4249 CmdArgs.push_back("-fdelayed-template-parsing");
4250
4251 // -fgnu-keywords default varies depending on language; only pass if
4252 // specified.
4253 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4254 options::OPT_fno_gnu_keywords))
4255 A->render(Args, CmdArgs);
4256
4257 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4258 false))
4259 CmdArgs.push_back("-fgnu89-inline");
4260
4261 if (Args.hasArg(options::OPT_fno_inline))
4262 CmdArgs.push_back("-fno-inline");
4263
4264 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4265 options::OPT_finline_hint_functions,
4266 options::OPT_fno_inline_functions))
4267 InlineArg->render(Args, CmdArgs);
4268
4269 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4270 options::OPT_fno_experimental_new_pass_manager);
4271
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004272 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4273 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4274 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004275
4276 if (Args.hasFlag(options::OPT_fapplication_extension,
4277 options::OPT_fno_application_extension, false))
4278 CmdArgs.push_back("-fapplication-extension");
4279
4280 // Handle GCC-style exception args.
4281 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004282 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004283 CmdArgs);
4284
Martell Malonec950c652017-11-29 07:25:12 +00004285 // Handle exception personalities
4286 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4287 options::OPT_fseh_exceptions,
4288 options::OPT_fdwarf_exceptions);
4289 if (A) {
4290 const Option &Opt = A->getOption();
4291 if (Opt.matches(options::OPT_fsjlj_exceptions))
4292 CmdArgs.push_back("-fsjlj-exceptions");
4293 if (Opt.matches(options::OPT_fseh_exceptions))
4294 CmdArgs.push_back("-fseh-exceptions");
4295 if (Opt.matches(options::OPT_fdwarf_exceptions))
4296 CmdArgs.push_back("-fdwarf-exceptions");
4297 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004298 switch (getToolChain().GetExceptionModel(Args)) {
4299 default:
4300 break;
4301 case llvm::ExceptionHandling::DwarfCFI:
4302 CmdArgs.push_back("-fdwarf-exceptions");
4303 break;
4304 case llvm::ExceptionHandling::SjLj:
4305 CmdArgs.push_back("-fsjlj-exceptions");
4306 break;
4307 case llvm::ExceptionHandling::WinEH:
4308 CmdArgs.push_back("-fseh-exceptions");
4309 break;
Martell Malonec950c652017-11-29 07:25:12 +00004310 }
4311 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004312
4313 // C++ "sane" operator new.
4314 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4315 options::OPT_fno_assume_sane_operator_new))
4316 CmdArgs.push_back("-fno-assume-sane-operator-new");
4317
4318 // -frelaxed-template-template-args is off by default, as it is a severe
4319 // breaking change until a corresponding change to template partial ordering
4320 // is provided.
4321 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4322 options::OPT_fno_relaxed_template_template_args, false))
4323 CmdArgs.push_back("-frelaxed-template-template-args");
4324
4325 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4326 // most platforms.
4327 if (Args.hasFlag(options::OPT_fsized_deallocation,
4328 options::OPT_fno_sized_deallocation, false))
4329 CmdArgs.push_back("-fsized-deallocation");
4330
4331 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4332 // by default.
4333 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4334 options::OPT_fno_aligned_allocation,
4335 options::OPT_faligned_new_EQ)) {
4336 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4337 CmdArgs.push_back("-fno-aligned-allocation");
4338 else
4339 CmdArgs.push_back("-faligned-allocation");
4340 }
4341
4342 // The default new alignment can be specified using a dedicated option or via
4343 // a GCC-compatible option that also turns on aligned allocation.
4344 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4345 options::OPT_faligned_new_EQ))
4346 CmdArgs.push_back(
4347 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4348
4349 // -fconstant-cfstrings is default, and may be subject to argument translation
4350 // on Darwin.
4351 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4352 options::OPT_fno_constant_cfstrings) ||
4353 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4354 options::OPT_mno_constant_cfstrings))
4355 CmdArgs.push_back("-fno-constant-cfstrings");
4356
David L. Jonesf561aba2017-03-08 01:02:16 +00004357 // -fno-pascal-strings is default, only pass non-default.
4358 if (Args.hasFlag(options::OPT_fpascal_strings,
4359 options::OPT_fno_pascal_strings, false))
4360 CmdArgs.push_back("-fpascal-strings");
4361
4362 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4363 // -fno-pack-struct doesn't apply to -fpack-struct=.
4364 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4365 std::string PackStructStr = "-fpack-struct=";
4366 PackStructStr += A->getValue();
4367 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4368 } else if (Args.hasFlag(options::OPT_fpack_struct,
4369 options::OPT_fno_pack_struct, false)) {
4370 CmdArgs.push_back("-fpack-struct=1");
4371 }
4372
4373 // Handle -fmax-type-align=N and -fno-type-align
4374 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4375 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4376 if (!SkipMaxTypeAlign) {
4377 std::string MaxTypeAlignStr = "-fmax-type-align=";
4378 MaxTypeAlignStr += A->getValue();
4379 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4380 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004381 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004382 if (!SkipMaxTypeAlign) {
4383 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4384 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4385 }
4386 }
4387
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004388 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4389 CmdArgs.push_back("-Qn");
4390
David L. Jonesf561aba2017-03-08 01:02:16 +00004391 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004392 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004393 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4394 !NoCommonDefault))
4395 CmdArgs.push_back("-fno-common");
4396
4397 // -fsigned-bitfields is default, and clang doesn't yet support
4398 // -funsigned-bitfields.
4399 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4400 options::OPT_funsigned_bitfields))
4401 D.Diag(diag::warn_drv_clang_unsupported)
4402 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4403
4404 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4405 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4406 D.Diag(diag::err_drv_clang_unsupported)
4407 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4408
4409 // -finput_charset=UTF-8 is default. Reject others
4410 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4411 StringRef value = inputCharset->getValue();
4412 if (!value.equals_lower("utf-8"))
4413 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4414 << value;
4415 }
4416
4417 // -fexec_charset=UTF-8 is default. Reject others
4418 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4419 StringRef value = execCharset->getValue();
4420 if (!value.equals_lower("utf-8"))
4421 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4422 << value;
4423 }
4424
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004425 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004426
4427 // -fno-asm-blocks is default.
4428 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4429 false))
4430 CmdArgs.push_back("-fasm-blocks");
4431
4432 // -fgnu-inline-asm is default.
4433 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4434 options::OPT_fno_gnu_inline_asm, true))
4435 CmdArgs.push_back("-fno-gnu-inline-asm");
4436
4437 // Enable vectorization per default according to the optimization level
4438 // selected. For optimization levels that want vectorization we use the alias
4439 // option to simplify the hasFlag logic.
4440 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4441 OptSpecifier VectorizeAliasOption =
4442 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4443 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4444 options::OPT_fno_vectorize, EnableVec))
4445 CmdArgs.push_back("-vectorize-loops");
4446
4447 // -fslp-vectorize is enabled based on the optimization level selected.
4448 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4449 OptSpecifier SLPVectAliasOption =
4450 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4451 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4452 options::OPT_fno_slp_vectorize, EnableSLPVec))
4453 CmdArgs.push_back("-vectorize-slp");
4454
Craig Topper9a724aa2017-12-11 21:09:19 +00004455 ParseMPreferVectorWidth(D, Args, CmdArgs);
4456
David L. Jonesf561aba2017-03-08 01:02:16 +00004457 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4458 A->render(Args, CmdArgs);
4459
4460 if (Arg *A = Args.getLastArg(
4461 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4462 A->render(Args, CmdArgs);
4463
4464 // -fdollars-in-identifiers default varies depending on platform and
4465 // language; only pass if specified.
4466 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4467 options::OPT_fno_dollars_in_identifiers)) {
4468 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4469 CmdArgs.push_back("-fdollars-in-identifiers");
4470 else
4471 CmdArgs.push_back("-fno-dollars-in-identifiers");
4472 }
4473
4474 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4475 // practical purposes.
4476 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4477 options::OPT_fno_unit_at_a_time)) {
4478 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4479 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4480 }
4481
4482 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4483 options::OPT_fno_apple_pragma_pack, false))
4484 CmdArgs.push_back("-fapple-pragma-pack");
4485
David L. Jonesf561aba2017-03-08 01:02:16 +00004486 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004487 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004488 options::OPT_fno_save_optimization_record, false)) {
4489 CmdArgs.push_back("-opt-record-file");
4490
4491 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4492 if (A) {
4493 CmdArgs.push_back(A->getValue());
4494 } else {
4495 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004496
4497 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4498 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4499 F = FinalOutput->getValue();
4500 }
4501
4502 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004503 // Use the input filename.
4504 F = llvm::sys::path::stem(Input.getBaseInput());
4505
4506 // If we're compiling for an offload architecture (i.e. a CUDA device),
4507 // we need to make the file name for the device compilation different
4508 // from the host compilation.
4509 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4510 !JA.isDeviceOffloading(Action::OFK_Host)) {
4511 llvm::sys::path::replace_extension(F, "");
4512 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4513 Triple.normalize());
4514 F += "-";
4515 F += JA.getOffloadingArch();
4516 }
4517 }
4518
4519 llvm::sys::path::replace_extension(F, "opt.yaml");
4520 CmdArgs.push_back(Args.MakeArgString(F));
4521 }
4522 }
4523
Richard Smith86a3ef52017-06-09 21:24:02 +00004524 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4525 options::OPT_fno_rewrite_imports, false);
4526 if (RewriteImports)
4527 CmdArgs.push_back("-frewrite-imports");
4528
David L. Jonesf561aba2017-03-08 01:02:16 +00004529 // Enable rewrite includes if the user's asked for it or if we're generating
4530 // diagnostics.
4531 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4532 // nice to enable this when doing a crashdump for modules as well.
4533 if (Args.hasFlag(options::OPT_frewrite_includes,
4534 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004535 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004536 CmdArgs.push_back("-frewrite-includes");
4537
4538 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4539 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4540 options::OPT_traditional_cpp)) {
4541 if (isa<PreprocessJobAction>(JA))
4542 CmdArgs.push_back("-traditional-cpp");
4543 else
4544 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4545 }
4546
4547 Args.AddLastArg(CmdArgs, options::OPT_dM);
4548 Args.AddLastArg(CmdArgs, options::OPT_dD);
4549
4550 // Handle serialized diagnostics.
4551 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4552 CmdArgs.push_back("-serialize-diagnostic-file");
4553 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4554 }
4555
4556 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4557 CmdArgs.push_back("-fretain-comments-from-system-headers");
4558
4559 // Forward -fcomment-block-commands to -cc1.
4560 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4561 // Forward -fparse-all-comments to -cc1.
4562 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4563
4564 // Turn -fplugin=name.so into -load name.so
4565 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4566 CmdArgs.push_back("-load");
4567 CmdArgs.push_back(A->getValue());
4568 A->claim();
4569 }
4570
4571 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004572 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4573 if (!StatsFile.empty())
4574 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004575
4576 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4577 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004578 // -finclude-default-header flag is for preprocessor,
4579 // do not pass it to other cc1 commands when save-temps is enabled
4580 if (C.getDriver().isSaveTempsEnabled() &&
4581 !isa<PreprocessJobAction>(JA)) {
4582 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4583 Arg->claim();
4584 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4585 CmdArgs.push_back(Arg->getValue());
4586 }
4587 }
4588 else {
4589 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4590 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004591 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4592 A->claim();
4593
4594 // We translate this by hand to the -cc1 argument, since nightly test uses
4595 // it and developers have been trained to spell it with -mllvm. Both
4596 // spellings are now deprecated and should be removed.
4597 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4598 CmdArgs.push_back("-disable-llvm-optzns");
4599 } else {
4600 A->render(Args, CmdArgs);
4601 }
4602 }
4603
4604 // With -save-temps, we want to save the unoptimized bitcode output from the
4605 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4606 // by the frontend.
4607 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4608 // has slightly different breakdown between stages.
4609 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4610 // pristine IR generated by the frontend. Ideally, a new compile action should
4611 // be added so both IR can be captured.
4612 if (C.getDriver().isSaveTempsEnabled() &&
4613 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4614 isa<CompileJobAction>(JA))
4615 CmdArgs.push_back("-disable-llvm-passes");
4616
4617 if (Output.getType() == types::TY_Dependencies) {
4618 // Handled with other dependency code.
4619 } else if (Output.isFilename()) {
4620 CmdArgs.push_back("-o");
4621 CmdArgs.push_back(Output.getFilename());
4622 } else {
4623 assert(Output.isNothing() && "Invalid output.");
4624 }
4625
4626 addDashXForInput(Args, Input, CmdArgs);
4627
4628 if (Input.isFilename())
4629 CmdArgs.push_back(Input.getFilename());
4630 else
4631 Input.getInputArg().renderAsInput(Args, CmdArgs);
4632
4633 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4634
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004635 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004636
4637 // Optionally embed the -cc1 level arguments into the debug info, for build
4638 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004639 // Also record command line arguments into the debug info if
4640 // -grecord-gcc-switches options is set on.
4641 // By default, -gno-record-gcc-switches is set on and no recording.
4642 if (getToolChain().UseDwarfDebugFlags() ||
4643 Args.hasFlag(options::OPT_grecord_gcc_switches,
4644 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004645 ArgStringList OriginalArgs;
4646 for (const auto &Arg : Args)
4647 Arg->render(Args, OriginalArgs);
4648
4649 SmallString<256> Flags;
4650 Flags += Exec;
4651 for (const char *OriginalArg : OriginalArgs) {
4652 SmallString<128> EscapedArg;
4653 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4654 Flags += " ";
4655 Flags += EscapedArg;
4656 }
4657 CmdArgs.push_back("-dwarf-debug-flags");
4658 CmdArgs.push_back(Args.MakeArgString(Flags));
4659 }
4660
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004661 if (IsCuda) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004662 // Host-side cuda compilation receives all device-side outputs in a single
4663 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004664 if (Inputs.size() > 1) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004665 assert(Inputs.size() == 2 && "More than one GPU binary!");
4666 CmdArgs.push_back("-fcuda-include-gpubinary");
4667 CmdArgs.push_back(Inputs[1].getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00004668 }
4669
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004670 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4671 CmdArgs.push_back("-fcuda-rdc");
Artem Belevich679dafe2018-05-09 23:10:09 +00004672 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4673 options::OPT_fno_cuda_short_ptr, false))
4674 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004675 }
4676
David L. Jonesf561aba2017-03-08 01:02:16 +00004677 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4678 // to specify the result of the compile phase on the host, so the meaningful
4679 // device declarations can be identified. Also, -fopenmp-is-device is passed
4680 // along to tell the frontend that it is generating code for a device, so that
4681 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004682 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004683 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004684 if (Inputs.size() == 2) {
4685 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4686 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4687 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004688 }
4689
4690 // For all the host OpenMP offloading compile jobs we need to pass the targets
4691 // information using -fopenmp-targets= option.
4692 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4693 SmallString<128> TargetInfo("-fopenmp-targets=");
4694
4695 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4696 assert(Tgts && Tgts->getNumValues() &&
4697 "OpenMP offloading has to have targets specified.");
4698 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4699 if (i)
4700 TargetInfo += ',';
4701 // We need to get the string from the triple because it may be not exactly
4702 // the same as the one we get directly from the arguments.
4703 llvm::Triple T(Tgts->getValue(i));
4704 TargetInfo += T.getTriple();
4705 }
4706 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4707 }
4708
4709 bool WholeProgramVTables =
4710 Args.hasFlag(options::OPT_fwhole_program_vtables,
4711 options::OPT_fno_whole_program_vtables, false);
4712 if (WholeProgramVTables) {
4713 if (!D.isUsingLTO())
4714 D.Diag(diag::err_drv_argument_only_allowed_with)
4715 << "-fwhole-program-vtables"
4716 << "-flto";
4717 CmdArgs.push_back("-fwhole-program-vtables");
4718 }
4719
Amara Emerson4ee9f822018-01-26 00:27:22 +00004720 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4721 options::OPT_fno_experimental_isel)) {
4722 CmdArgs.push_back("-mllvm");
4723 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4724 CmdArgs.push_back("-global-isel=1");
4725
4726 // GISel is on by default on AArch64 -O0, so don't bother adding
4727 // the fallback remarks for it. Other combinations will add a warning of
4728 // some kind.
4729 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4730 bool IsOptLevelSupported = false;
4731
4732 Arg *A = Args.getLastArg(options::OPT_O_Group);
4733 if (Triple.getArch() == llvm::Triple::aarch64) {
4734 if (!A || A->getOption().matches(options::OPT_O0))
4735 IsOptLevelSupported = true;
4736 }
4737 if (!IsArchSupported || !IsOptLevelSupported) {
4738 CmdArgs.push_back("-mllvm");
4739 CmdArgs.push_back("-global-isel-abort=2");
4740
4741 if (!IsArchSupported)
4742 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4743 else
4744 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4745 }
4746 } else {
4747 CmdArgs.push_back("-global-isel=0");
4748 }
4749 }
4750
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00004751 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4752 options::OPT_fno_force_enable_int128)) {
4753 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4754 CmdArgs.push_back("-fforce-enable-int128");
4755 }
4756
Peter Collingbourne54d13b42018-05-30 03:40:04 +00004757 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
4758 options::OPT_fno_complete_member_pointers, false))
4759 CmdArgs.push_back("-fcomplete-member-pointers");
4760
Jessica Paquette36a25672018-06-29 18:06:10 +00004761 if (Arg *A = Args.getLastArg(options::OPT_moutline,
4762 options::OPT_mno_outline)) {
4763 if (A->getOption().matches(options::OPT_moutline)) {
4764 // We only support -moutline in AArch64 right now. If we're not compiling
4765 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
4766 // proper mllvm flags.
4767 if (Triple.getArch() != llvm::Triple::aarch64) {
4768 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
4769 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00004770 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00004771 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004772 }
Jessica Paquette36a25672018-06-29 18:06:10 +00004773 } else {
4774 // Disable all outlining behaviour.
4775 CmdArgs.push_back("-mllvm");
4776 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004777 }
4778 }
4779
David L. Jonesf561aba2017-03-08 01:02:16 +00004780 // Finally add the compile command to the compilation.
4781 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4782 Output.getType() == types::TY_Object &&
4783 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4784 auto CLCommand =
4785 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4786 C.addCommand(llvm::make_unique<FallbackCommand>(
4787 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4788 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4789 isa<PrecompileJobAction>(JA)) {
4790 // In /fallback builds, run the main compilation even if the pch generation
4791 // fails, so that the main compilation's fallback to cl.exe runs.
4792 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4793 CmdArgs, Inputs));
4794 } else {
4795 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4796 }
4797
David L. Jonesf561aba2017-03-08 01:02:16 +00004798 if (Arg *A = Args.getLastArg(options::OPT_pg))
4799 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4800 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4801 << A->getAsString(Args);
4802
4803 // Claim some arguments which clang supports automatically.
4804
4805 // -fpch-preprocess is used with gcc to add a special marker in the output to
4806 // include the PCH file. Clang's PTH solution is completely transparent, so we
4807 // do not need to deal with it at all.
4808 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4809
4810 // Claim some arguments which clang doesn't support, but we don't
4811 // care to warn the user about.
4812 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4813 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4814
4815 // Disable warnings for clang -E -emit-llvm foo.c
4816 Args.ClaimAllArgs(options::OPT_emit_llvm);
4817}
4818
4819Clang::Clang(const ToolChain &TC)
4820 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4821 // as it is for other tools. Some operations on a Tool actually test
4822 // whether that tool is Clang based on the Tool's Name as a string.
4823 : Tool("clang", "clang frontend", TC, RF_Full) {}
4824
4825Clang::~Clang() {}
4826
4827/// Add options related to the Objective-C runtime/ABI.
4828///
4829/// Returns true if the runtime is non-fragile.
4830ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4831 ArgStringList &cmdArgs,
4832 RewriteKind rewriteKind) const {
4833 // Look for the controlling runtime option.
4834 Arg *runtimeArg =
4835 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4836 options::OPT_fobjc_runtime_EQ);
4837
4838 // Just forward -fobjc-runtime= to the frontend. This supercedes
4839 // options about fragility.
4840 if (runtimeArg &&
4841 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4842 ObjCRuntime runtime;
4843 StringRef value = runtimeArg->getValue();
4844 if (runtime.tryParse(value)) {
4845 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4846 << value;
4847 }
David Chisnall404bbcb2018-05-22 10:13:06 +00004848 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
4849 (runtime.getVersion() >= VersionTuple(2, 0)))
4850 if (!getToolChain().getTriple().isOSBinFormatELF()) {
4851 getToolChain().getDriver().Diag(
4852 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
4853 << runtime.getVersion().getMajor();
4854 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004855
4856 runtimeArg->render(args, cmdArgs);
4857 return runtime;
4858 }
4859
4860 // Otherwise, we'll need the ABI "version". Version numbers are
4861 // slightly confusing for historical reasons:
4862 // 1 - Traditional "fragile" ABI
4863 // 2 - Non-fragile ABI, version 1
4864 // 3 - Non-fragile ABI, version 2
4865 unsigned objcABIVersion = 1;
4866 // If -fobjc-abi-version= is present, use that to set the version.
4867 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4868 StringRef value = abiArg->getValue();
4869 if (value == "1")
4870 objcABIVersion = 1;
4871 else if (value == "2")
4872 objcABIVersion = 2;
4873 else if (value == "3")
4874 objcABIVersion = 3;
4875 else
4876 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4877 } else {
4878 // Otherwise, determine if we are using the non-fragile ABI.
4879 bool nonFragileABIIsDefault =
4880 (rewriteKind == RK_NonFragile ||
4881 (rewriteKind == RK_None &&
4882 getToolChain().IsObjCNonFragileABIDefault()));
4883 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4884 options::OPT_fno_objc_nonfragile_abi,
4885 nonFragileABIIsDefault)) {
4886// Determine the non-fragile ABI version to use.
4887#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4888 unsigned nonFragileABIVersion = 1;
4889#else
4890 unsigned nonFragileABIVersion = 2;
4891#endif
4892
4893 if (Arg *abiArg =
4894 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4895 StringRef value = abiArg->getValue();
4896 if (value == "1")
4897 nonFragileABIVersion = 1;
4898 else if (value == "2")
4899 nonFragileABIVersion = 2;
4900 else
4901 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4902 << value;
4903 }
4904
4905 objcABIVersion = 1 + nonFragileABIVersion;
4906 } else {
4907 objcABIVersion = 1;
4908 }
4909 }
4910
4911 // We don't actually care about the ABI version other than whether
4912 // it's non-fragile.
4913 bool isNonFragile = objcABIVersion != 1;
4914
4915 // If we have no runtime argument, ask the toolchain for its default runtime.
4916 // However, the rewriter only really supports the Mac runtime, so assume that.
4917 ObjCRuntime runtime;
4918 if (!runtimeArg) {
4919 switch (rewriteKind) {
4920 case RK_None:
4921 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4922 break;
4923 case RK_Fragile:
4924 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4925 break;
4926 case RK_NonFragile:
4927 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4928 break;
4929 }
4930
4931 // -fnext-runtime
4932 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4933 // On Darwin, make this use the default behavior for the toolchain.
4934 if (getToolChain().getTriple().isOSDarwin()) {
4935 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4936
4937 // Otherwise, build for a generic macosx port.
4938 } else {
4939 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4940 }
4941
4942 // -fgnu-runtime
4943 } else {
4944 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4945 // Legacy behaviour is to target the gnustep runtime if we are in
4946 // non-fragile mode or the GCC runtime in fragile mode.
4947 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00004948 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00004949 else
4950 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4951 }
4952
4953 cmdArgs.push_back(
4954 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4955 return runtime;
4956}
4957
4958static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4959 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4960 I += HaveDash;
4961 return !HaveDash;
4962}
4963
4964namespace {
4965struct EHFlags {
4966 bool Synch = false;
4967 bool Asynch = false;
4968 bool NoUnwindC = false;
4969};
4970} // end anonymous namespace
4971
4972/// /EH controls whether to run destructor cleanups when exceptions are
4973/// thrown. There are three modifiers:
4974/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4975/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4976/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4977/// - c: Assume that extern "C" functions are implicitly nounwind.
4978/// The default is /EHs-c-, meaning cleanups are disabled.
4979static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4980 EHFlags EH;
4981
4982 std::vector<std::string> EHArgs =
4983 Args.getAllArgValues(options::OPT__SLASH_EH);
4984 for (auto EHVal : EHArgs) {
4985 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4986 switch (EHVal[I]) {
4987 case 'a':
4988 EH.Asynch = maybeConsumeDash(EHVal, I);
4989 if (EH.Asynch)
4990 EH.Synch = false;
4991 continue;
4992 case 'c':
4993 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4994 continue;
4995 case 's':
4996 EH.Synch = maybeConsumeDash(EHVal, I);
4997 if (EH.Synch)
4998 EH.Asynch = false;
4999 continue;
5000 default:
5001 break;
5002 }
5003 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5004 break;
5005 }
5006 }
5007 // The /GX, /GX- flags are only processed if there are not /EH flags.
5008 // The default is that /GX is not specified.
5009 if (EHArgs.empty() &&
5010 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5011 /*default=*/false)) {
5012 EH.Synch = true;
5013 EH.NoUnwindC = true;
5014 }
5015
5016 return EH;
5017}
5018
5019void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5020 ArgStringList &CmdArgs,
5021 codegenoptions::DebugInfoKind *DebugInfoKind,
5022 bool *EmitCodeView) const {
5023 unsigned RTOptionID = options::OPT__SLASH_MT;
5024
5025 if (Args.hasArg(options::OPT__SLASH_LDd))
5026 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5027 // but defining _DEBUG is sticky.
5028 RTOptionID = options::OPT__SLASH_MTd;
5029
5030 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5031 RTOptionID = A->getOption().getID();
5032
5033 StringRef FlagForCRT;
5034 switch (RTOptionID) {
5035 case options::OPT__SLASH_MD:
5036 if (Args.hasArg(options::OPT__SLASH_LDd))
5037 CmdArgs.push_back("-D_DEBUG");
5038 CmdArgs.push_back("-D_MT");
5039 CmdArgs.push_back("-D_DLL");
5040 FlagForCRT = "--dependent-lib=msvcrt";
5041 break;
5042 case options::OPT__SLASH_MDd:
5043 CmdArgs.push_back("-D_DEBUG");
5044 CmdArgs.push_back("-D_MT");
5045 CmdArgs.push_back("-D_DLL");
5046 FlagForCRT = "--dependent-lib=msvcrtd";
5047 break;
5048 case options::OPT__SLASH_MT:
5049 if (Args.hasArg(options::OPT__SLASH_LDd))
5050 CmdArgs.push_back("-D_DEBUG");
5051 CmdArgs.push_back("-D_MT");
5052 CmdArgs.push_back("-flto-visibility-public-std");
5053 FlagForCRT = "--dependent-lib=libcmt";
5054 break;
5055 case options::OPT__SLASH_MTd:
5056 CmdArgs.push_back("-D_DEBUG");
5057 CmdArgs.push_back("-D_MT");
5058 CmdArgs.push_back("-flto-visibility-public-std");
5059 FlagForCRT = "--dependent-lib=libcmtd";
5060 break;
5061 default:
5062 llvm_unreachable("Unexpected option ID.");
5063 }
5064
5065 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5066 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5067 } else {
5068 CmdArgs.push_back(FlagForCRT.data());
5069
5070 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5071 // users want. The /Za flag to cl.exe turns this off, but it's not
5072 // implemented in clang.
5073 CmdArgs.push_back("--dependent-lib=oldnames");
5074 }
5075
Erich Keane425f48d2018-05-04 15:58:31 +00005076 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5077 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005078
5079 // This controls whether or not we emit RTTI data for polymorphic types.
5080 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5081 /*default=*/false))
5082 CmdArgs.push_back("-fno-rtti-data");
5083
5084 // This controls whether or not we emit stack-protector instrumentation.
5085 // In MSVC, Buffer Security Check (/GS) is on by default.
5086 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5087 /*default=*/true)) {
5088 CmdArgs.push_back("-stack-protector");
5089 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5090 }
5091
5092 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5093 if (Arg *DebugInfoArg =
5094 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5095 options::OPT_gline_tables_only)) {
5096 *EmitCodeView = true;
5097 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5098 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5099 else
5100 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5101 CmdArgs.push_back("-gcodeview");
5102 } else {
5103 *EmitCodeView = false;
5104 }
5105
5106 const Driver &D = getToolChain().getDriver();
5107 EHFlags EH = parseClangCLEHFlags(D, Args);
5108 if (EH.Synch || EH.Asynch) {
5109 if (types::isCXX(InputType))
5110 CmdArgs.push_back("-fcxx-exceptions");
5111 CmdArgs.push_back("-fexceptions");
5112 }
5113 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5114 CmdArgs.push_back("-fexternc-nounwind");
5115
5116 // /EP should expand to -E -P.
5117 if (Args.hasArg(options::OPT__SLASH_EP)) {
5118 CmdArgs.push_back("-E");
5119 CmdArgs.push_back("-P");
5120 }
5121
5122 unsigned VolatileOptionID;
5123 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5124 getToolChain().getArch() == llvm::Triple::x86)
5125 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5126 else
5127 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5128
5129 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5130 VolatileOptionID = A->getOption().getID();
5131
5132 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5133 CmdArgs.push_back("-fms-volatile");
5134
5135 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5136 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5137 if (MostGeneralArg && BestCaseArg)
5138 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5139 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5140
5141 if (MostGeneralArg) {
5142 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5143 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5144 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5145
5146 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5147 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5148 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5149 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5150 << FirstConflict->getAsString(Args)
5151 << SecondConflict->getAsString(Args);
5152
5153 if (SingleArg)
5154 CmdArgs.push_back("-fms-memptr-rep=single");
5155 else if (MultipleArg)
5156 CmdArgs.push_back("-fms-memptr-rep=multiple");
5157 else
5158 CmdArgs.push_back("-fms-memptr-rep=virtual");
5159 }
5160
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005161 // Parse the default calling convention options.
5162 if (Arg *CCArg =
5163 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005164 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5165 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005166 unsigned DCCOptId = CCArg->getOption().getID();
5167 const char *DCCFlag = nullptr;
5168 bool ArchSupported = true;
5169 llvm::Triple::ArchType Arch = getToolChain().getArch();
5170 switch (DCCOptId) {
5171 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005172 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005173 break;
5174 case options::OPT__SLASH_Gr:
5175 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005176 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005177 break;
5178 case options::OPT__SLASH_Gz:
5179 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005180 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005181 break;
5182 case options::OPT__SLASH_Gv:
5183 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005184 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005185 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005186 case options::OPT__SLASH_Gregcall:
5187 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5188 DCCFlag = "-fdefault-calling-conv=regcall";
5189 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005190 }
5191
5192 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5193 if (ArchSupported && DCCFlag)
5194 CmdArgs.push_back(DCCFlag);
5195 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005196
5197 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5198 A->render(Args, CmdArgs);
5199
5200 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5201 CmdArgs.push_back("-fdiagnostics-format");
5202 if (Args.hasArg(options::OPT__SLASH_fallback))
5203 CmdArgs.push_back("msvc-fallback");
5204 else
5205 CmdArgs.push_back("msvc");
5206 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005207
5208 if (Args.hasArg(options::OPT__SLASH_Guard) &&
5209 Args.getLastArgValue(options::OPT__SLASH_Guard).equals_lower("cf"))
5210 CmdArgs.push_back("-cfguard");
David L. Jonesf561aba2017-03-08 01:02:16 +00005211}
5212
5213visualstudio::Compiler *Clang::getCLFallback() const {
5214 if (!CLFallback)
5215 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5216 return CLFallback.get();
5217}
5218
5219
5220const char *Clang::getBaseInputName(const ArgList &Args,
5221 const InputInfo &Input) {
5222 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5223}
5224
5225const char *Clang::getBaseInputStem(const ArgList &Args,
5226 const InputInfoList &Inputs) {
5227 const char *Str = getBaseInputName(Args, Inputs[0]);
5228
5229 if (const char *End = strrchr(Str, '.'))
5230 return Args.MakeArgString(std::string(Str, End));
5231
5232 return Str;
5233}
5234
5235const char *Clang::getDependencyFileName(const ArgList &Args,
5236 const InputInfoList &Inputs) {
5237 // FIXME: Think about this more.
5238 std::string Res;
5239
5240 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5241 std::string Str(OutputOpt->getValue());
5242 Res = Str.substr(0, Str.rfind('.'));
5243 } else {
5244 Res = getBaseInputStem(Args, Inputs);
5245 }
5246 return Args.MakeArgString(Res + ".d");
5247}
5248
5249// Begin ClangAs
5250
5251void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5252 ArgStringList &CmdArgs) const {
5253 StringRef CPUName;
5254 StringRef ABIName;
5255 const llvm::Triple &Triple = getToolChain().getTriple();
5256 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5257
5258 CmdArgs.push_back("-target-abi");
5259 CmdArgs.push_back(ABIName.data());
5260}
5261
5262void ClangAs::AddX86TargetArgs(const ArgList &Args,
5263 ArgStringList &CmdArgs) const {
5264 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5265 StringRef Value = A->getValue();
5266 if (Value == "intel" || Value == "att") {
5267 CmdArgs.push_back("-mllvm");
5268 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5269 } else {
5270 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5271 << A->getOption().getName() << Value;
5272 }
5273 }
5274}
5275
5276void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5277 const InputInfo &Output, const InputInfoList &Inputs,
5278 const ArgList &Args,
5279 const char *LinkingOutput) const {
5280 ArgStringList CmdArgs;
5281
5282 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5283 const InputInfo &Input = Inputs[0];
5284
5285 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5286 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005287 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005288
5289 // Don't warn about "clang -w -c foo.s"
5290 Args.ClaimAllArgs(options::OPT_w);
5291 // and "clang -emit-llvm -c foo.s"
5292 Args.ClaimAllArgs(options::OPT_emit_llvm);
5293
5294 claimNoWarnArgs(Args);
5295
5296 // Invoke ourselves in -cc1as mode.
5297 //
5298 // FIXME: Implement custom jobs for internal actions.
5299 CmdArgs.push_back("-cc1as");
5300
5301 // Add the "effective" target triple.
5302 CmdArgs.push_back("-triple");
5303 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5304
5305 // Set the output mode, we currently only expect to be used as a real
5306 // assembler.
5307 CmdArgs.push_back("-filetype");
5308 CmdArgs.push_back("obj");
5309
5310 // Set the main file name, so that debug info works even with
5311 // -save-temps or preprocessed assembly.
5312 CmdArgs.push_back("-main-file-name");
5313 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5314
5315 // Add the target cpu
5316 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5317 if (!CPU.empty()) {
5318 CmdArgs.push_back("-target-cpu");
5319 CmdArgs.push_back(Args.MakeArgString(CPU));
5320 }
5321
5322 // Add the target features
5323 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5324
5325 // Ignore explicit -force_cpusubtype_ALL option.
5326 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5327
5328 // Pass along any -I options so we get proper .include search paths.
5329 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5330
5331 // Determine the original source input.
5332 const Action *SourceAction = &JA;
5333 while (SourceAction->getKind() != Action::InputClass) {
5334 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5335 SourceAction = SourceAction->getInputs()[0];
5336 }
5337
5338 // Forward -g and handle debug info related flags, assuming we are dealing
5339 // with an actual assembly file.
5340 bool WantDebug = false;
5341 unsigned DwarfVersion = 0;
5342 Args.ClaimAllArgs(options::OPT_g_Group);
5343 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5344 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5345 !A->getOption().matches(options::OPT_ggdb0);
5346 if (WantDebug)
5347 DwarfVersion = DwarfVersionNum(A->getSpelling());
5348 }
5349 if (DwarfVersion == 0)
5350 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5351
5352 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5353
5354 if (SourceAction->getType() == types::TY_Asm ||
5355 SourceAction->getType() == types::TY_PP_Asm) {
5356 // You might think that it would be ok to set DebugInfoKind outside of
5357 // the guard for source type, however there is a test which asserts
5358 // that some assembler invocation receives no -debug-info-kind,
5359 // and it's not clear whether that test is just overly restrictive.
5360 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5361 : codegenoptions::NoDebugInfo);
5362 // Add the -fdebug-compilation-dir flag if needed.
5363 addDebugCompDirArg(Args, CmdArgs);
5364
Paul Robinson9b292b42018-07-10 15:15:24 +00005365 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5366
David L. Jonesf561aba2017-03-08 01:02:16 +00005367 // Set the AT_producer to the clang version when using the integrated
5368 // assembler on assembly source files.
5369 CmdArgs.push_back("-dwarf-debug-producer");
5370 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5371
5372 // And pass along -I options
5373 Args.AddAllArgs(CmdArgs, options::OPT_I);
5374 }
5375 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5376 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005377 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5378
David L. Jonesf561aba2017-03-08 01:02:16 +00005379
5380 // Handle -fPIC et al -- the relocation-model affects the assembler
5381 // for some targets.
5382 llvm::Reloc::Model RelocationModel;
5383 unsigned PICLevel;
5384 bool IsPIE;
5385 std::tie(RelocationModel, PICLevel, IsPIE) =
5386 ParsePICArgs(getToolChain(), Args);
5387
5388 const char *RMName = RelocationModelName(RelocationModel);
5389 if (RMName) {
5390 CmdArgs.push_back("-mrelocation-model");
5391 CmdArgs.push_back(RMName);
5392 }
5393
5394 // Optionally embed the -cc1as level arguments into the debug info, for build
5395 // analysis.
5396 if (getToolChain().UseDwarfDebugFlags()) {
5397 ArgStringList OriginalArgs;
5398 for (const auto &Arg : Args)
5399 Arg->render(Args, OriginalArgs);
5400
5401 SmallString<256> Flags;
5402 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5403 Flags += Exec;
5404 for (const char *OriginalArg : OriginalArgs) {
5405 SmallString<128> EscapedArg;
5406 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5407 Flags += " ";
5408 Flags += EscapedArg;
5409 }
5410 CmdArgs.push_back("-dwarf-debug-flags");
5411 CmdArgs.push_back(Args.MakeArgString(Flags));
5412 }
5413
5414 // FIXME: Add -static support, once we have it.
5415
5416 // Add target specific flags.
5417 switch (getToolChain().getArch()) {
5418 default:
5419 break;
5420
5421 case llvm::Triple::mips:
5422 case llvm::Triple::mipsel:
5423 case llvm::Triple::mips64:
5424 case llvm::Triple::mips64el:
5425 AddMIPSTargetArgs(Args, CmdArgs);
5426 break;
5427
5428 case llvm::Triple::x86:
5429 case llvm::Triple::x86_64:
5430 AddX86TargetArgs(Args, CmdArgs);
5431 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005432
5433 case llvm::Triple::arm:
5434 case llvm::Triple::armeb:
5435 case llvm::Triple::thumb:
5436 case llvm::Triple::thumbeb:
5437 // This isn't in AddARMTargetArgs because we want to do this for assembly
5438 // only, not C/C++.
5439 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5440 options::OPT_mno_default_build_attributes, true)) {
5441 CmdArgs.push_back("-mllvm");
5442 CmdArgs.push_back("-arm-add-build-attributes");
5443 }
5444 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005445 }
5446
5447 // Consume all the warning flags. Usually this would be handled more
5448 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5449 // doesn't handle that so rather than warning about unused flags that are
5450 // actually used, we'll lie by omission instead.
5451 // FIXME: Stop lying and consume only the appropriate driver flags
5452 Args.ClaimAllArgs(options::OPT_W_Group);
5453
5454 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5455 getToolChain().getDriver());
5456
5457 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5458
5459 assert(Output.isFilename() && "Unexpected lipo output.");
5460 CmdArgs.push_back("-o");
5461 CmdArgs.push_back(Output.getFilename());
5462
Peter Collingbourne91d02842018-05-22 18:52:37 +00005463 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5464 getToolChain().getTriple().isOSLinux()) {
5465 CmdArgs.push_back("-split-dwarf-file");
5466 CmdArgs.push_back(SplitDebugName(Args, Input));
5467 }
5468
David L. Jonesf561aba2017-03-08 01:02:16 +00005469 assert(Input.isFilename() && "Invalid input.");
5470 CmdArgs.push_back(Input.getFilename());
5471
5472 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5473 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005474}
5475
5476// Begin OffloadBundler
5477
5478void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5479 const InputInfo &Output,
5480 const InputInfoList &Inputs,
5481 const llvm::opt::ArgList &TCArgs,
5482 const char *LinkingOutput) const {
5483 // The version with only one output is expected to refer to a bundling job.
5484 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5485
5486 // The bundling command looks like this:
5487 // clang-offload-bundler -type=bc
5488 // -targets=host-triple,openmp-triple1,openmp-triple2
5489 // -outputs=input_file
5490 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5491
5492 ArgStringList CmdArgs;
5493
5494 // Get the type.
5495 CmdArgs.push_back(TCArgs.MakeArgString(
5496 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5497
5498 assert(JA.getInputs().size() == Inputs.size() &&
5499 "Not have inputs for all dependence actions??");
5500
5501 // Get the targets.
5502 SmallString<128> Triples;
5503 Triples += "-targets=";
5504 for (unsigned I = 0; I < Inputs.size(); ++I) {
5505 if (I)
5506 Triples += ',';
5507
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005508 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005509 Action::OffloadKind CurKind = Action::OFK_Host;
5510 const ToolChain *CurTC = &getToolChain();
5511 const Action *CurDep = JA.getInputs()[I];
5512
5513 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005514 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005515 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005516 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005517 CurKind = A->getOffloadingDeviceKind();
5518 CurTC = TC;
5519 });
5520 }
5521 Triples += Action::GetOffloadKindName(CurKind);
5522 Triples += '-';
5523 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005524 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5525 Triples += '-';
5526 Triples += CurDep->getOffloadingArch();
5527 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005528 }
5529 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5530
5531 // Get bundled file command.
5532 CmdArgs.push_back(
5533 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5534
5535 // Get unbundled files command.
5536 SmallString<128> UB;
5537 UB += "-inputs=";
5538 for (unsigned I = 0; I < Inputs.size(); ++I) {
5539 if (I)
5540 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005541
5542 // Find ToolChain for this input.
5543 const ToolChain *CurTC = &getToolChain();
5544 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5545 CurTC = nullptr;
5546 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5547 assert(CurTC == nullptr && "Expected one dependence!");
5548 CurTC = TC;
5549 });
5550 }
5551 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005552 }
5553 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5554
5555 // All the inputs are encoded as commands.
5556 C.addCommand(llvm::make_unique<Command>(
5557 JA, *this,
5558 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5559 CmdArgs, None));
5560}
5561
5562void OffloadBundler::ConstructJobMultipleOutputs(
5563 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5564 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5565 const char *LinkingOutput) const {
5566 // The version with multiple outputs is expected to refer to a unbundling job.
5567 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5568
5569 // The unbundling command looks like this:
5570 // clang-offload-bundler -type=bc
5571 // -targets=host-triple,openmp-triple1,openmp-triple2
5572 // -inputs=input_file
5573 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5574 // -unbundle
5575
5576 ArgStringList CmdArgs;
5577
5578 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5579 InputInfo Input = Inputs.front();
5580
5581 // Get the type.
5582 CmdArgs.push_back(TCArgs.MakeArgString(
5583 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5584
5585 // Get the targets.
5586 SmallString<128> Triples;
5587 Triples += "-targets=";
5588 auto DepInfo = UA.getDependentActionsInfo();
5589 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5590 if (I)
5591 Triples += ',';
5592
5593 auto &Dep = DepInfo[I];
5594 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5595 Triples += '-';
5596 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005597 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5598 !Dep.DependentBoundArch.empty()) {
5599 Triples += '-';
5600 Triples += Dep.DependentBoundArch;
5601 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005602 }
5603
5604 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5605
5606 // Get bundled file command.
5607 CmdArgs.push_back(
5608 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5609
5610 // Get unbundled files command.
5611 SmallString<128> UB;
5612 UB += "-outputs=";
5613 for (unsigned I = 0; I < Outputs.size(); ++I) {
5614 if (I)
5615 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005616 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005617 }
5618 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5619 CmdArgs.push_back("-unbundle");
5620
5621 // All the inputs are encoded as commands.
5622 C.addCommand(llvm::make_unique<Command>(
5623 JA, *this,
5624 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5625 CmdArgs, None));
5626}