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