blob: d392f68897ca4b23430b5a622799fa53e7059e2a [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 }
1087
1088 bool RenderedImplicitInclude = false;
1089 int AI = -1;
1090 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1091 ++AI;
1092
1093 if (getToolChain().getDriver().IsCLMode() &&
1094 A->getOption().matches(options::OPT_include)) {
1095 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
1096 // include is compiled into foo.h, and everything after goes into
1097 // the .obj file. /Yufoo.h means that all includes prior to and including
1098 // foo.h are completely skipped and replaced with a use of the pch file
1099 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
1100 // just mean that the last one wins.) If /Yc and /Yu are both present
1101 // and refer to the same file, /Yc wins.
1102 // Note that OPT__SLASH_FI gets mapped to OPT_include.
1103 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
1104 // cl.exe seems to support both flags with different values, but that
1105 // seems strange (which flag does /Fp now refer to?), so don't implement
1106 // that until someone needs it.
1107 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
1108 if (PchIndex != -1) {
1109 if (isa<PrecompileJobAction>(JA)) {
1110 // When building the pch, skip all includes after the pch.
1111 assert(YcIndex != -1 && PchIndex == YcIndex);
1112 if (AI >= YcIndex)
1113 continue;
1114 } else {
1115 // When using the pch, skip all includes prior to the pch.
1116 if (AI < PchIndex) {
1117 A->claim();
1118 continue;
1119 }
1120 if (AI == PchIndex) {
1121 A->claim();
1122 CmdArgs.push_back("-include-pch");
1123 CmdArgs.push_back(
1124 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
1125 continue;
1126 }
1127 }
1128 }
1129 } else if (A->getOption().matches(options::OPT_include)) {
1130 // Handling of gcc-style gch precompiled headers.
1131 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1132 RenderedImplicitInclude = true;
1133
1134 // Use PCH if the user requested it.
1135 bool UsePCH = D.CCCUsePCH;
1136
1137 bool FoundPTH = false;
1138 bool FoundPCH = false;
1139 SmallString<128> P(A->getValue());
1140 // We want the files to have a name like foo.h.pch. Add a dummy extension
1141 // so that replace_extension does the right thing.
1142 P += ".dummy";
1143 if (UsePCH) {
1144 llvm::sys::path::replace_extension(P, "pch");
1145 if (llvm::sys::fs::exists(P))
1146 FoundPCH = true;
1147 }
1148
1149 if (!FoundPCH) {
1150 llvm::sys::path::replace_extension(P, "pth");
1151 if (llvm::sys::fs::exists(P))
1152 FoundPTH = true;
1153 }
1154
1155 if (!FoundPCH && !FoundPTH) {
1156 llvm::sys::path::replace_extension(P, "gch");
1157 if (llvm::sys::fs::exists(P)) {
1158 FoundPCH = UsePCH;
1159 FoundPTH = !UsePCH;
1160 }
1161 }
1162
1163 if (FoundPCH || FoundPTH) {
1164 if (IsFirstImplicitInclude) {
1165 A->claim();
1166 if (UsePCH)
1167 CmdArgs.push_back("-include-pch");
1168 else
1169 CmdArgs.push_back("-include-pth");
1170 CmdArgs.push_back(Args.MakeArgString(P));
1171 continue;
1172 } else {
1173 // Ignore the PCH if not first on command line and emit warning.
1174 D.Diag(diag::warn_drv_pch_not_first_include) << P
1175 << A->getAsString(Args);
1176 }
1177 }
1178 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1179 // Handling of paths which must come late. These entries are handled by
1180 // the toolchain itself after the resource dir is inserted in the right
1181 // search order.
1182 // Do not claim the argument so that the use of the argument does not
1183 // silently go unnoticed on toolchains which do not honour the option.
1184 continue;
1185 }
1186
1187 // Not translated, render as usual.
1188 A->claim();
1189 A->render(Args, CmdArgs);
1190 }
1191
1192 Args.AddAllArgs(CmdArgs,
1193 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1194 options::OPT_F, options::OPT_index_header_map});
1195
1196 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1197
1198 // FIXME: There is a very unfortunate problem here, some troubled
1199 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1200 // really support that we would have to parse and then translate
1201 // those options. :(
1202 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1203 options::OPT_Xpreprocessor);
1204
1205 // -I- is a deprecated GCC feature, reject it.
1206 if (Arg *A = Args.getLastArg(options::OPT_I_))
1207 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1208
1209 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1210 // -isysroot to the CC1 invocation.
1211 StringRef sysroot = C.getSysRoot();
1212 if (sysroot != "") {
1213 if (!Args.hasArg(options::OPT_isysroot)) {
1214 CmdArgs.push_back("-isysroot");
1215 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1216 }
1217 }
1218
1219 // Parse additional include paths from environment variables.
1220 // FIXME: We should probably sink the logic for handling these from the
1221 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1222 // CPATH - included following the user specified includes (but prior to
1223 // builtin and standard includes).
1224 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1225 // C_INCLUDE_PATH - system includes enabled when compiling C.
1226 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1227 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1228 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1229 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1230 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1231 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1232 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1233
1234 // While adding the include arguments, we also attempt to retrieve the
1235 // arguments of related offloading toolchains or arguments that are specific
1236 // of an offloading programming model.
1237
1238 // Add C++ include arguments, if needed.
1239 if (types::isCXX(Inputs[0].getType()))
1240 forAllAssociatedToolChains(C, JA, getToolChain(),
1241 [&Args, &CmdArgs](const ToolChain &TC) {
1242 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1243 });
1244
1245 // Add system include arguments for all targets but IAMCU.
1246 if (!IsIAMCU)
1247 forAllAssociatedToolChains(C, JA, getToolChain(),
1248 [&Args, &CmdArgs](const ToolChain &TC) {
1249 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1250 });
1251 else {
1252 // For IAMCU add special include arguments.
1253 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1254 }
1255}
1256
1257// FIXME: Move to target hook.
1258static bool isSignedCharDefault(const llvm::Triple &Triple) {
1259 switch (Triple.getArch()) {
1260 default:
1261 return true;
1262
1263 case llvm::Triple::aarch64:
1264 case llvm::Triple::aarch64_be:
1265 case llvm::Triple::arm:
1266 case llvm::Triple::armeb:
1267 case llvm::Triple::thumb:
1268 case llvm::Triple::thumbeb:
1269 if (Triple.isOSDarwin() || Triple.isOSWindows())
1270 return true;
1271 return false;
1272
1273 case llvm::Triple::ppc:
1274 case llvm::Triple::ppc64:
1275 if (Triple.isOSDarwin())
1276 return true;
1277 return false;
1278
1279 case llvm::Triple::hexagon:
1280 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001281 case llvm::Triple::riscv32:
1282 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001283 case llvm::Triple::systemz:
1284 case llvm::Triple::xcore:
1285 return false;
1286 }
1287}
1288
1289static bool isNoCommonDefault(const llvm::Triple &Triple) {
1290 switch (Triple.getArch()) {
1291 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001292 if (Triple.isOSFuchsia())
1293 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001294 return false;
1295
1296 case llvm::Triple::xcore:
1297 case llvm::Triple::wasm32:
1298 case llvm::Triple::wasm64:
1299 return true;
1300 }
1301}
1302
1303void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1304 ArgStringList &CmdArgs, bool KernelOrKext) const {
1305 // Select the ABI to use.
1306 // FIXME: Support -meabi.
1307 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1308 const char *ABIName = nullptr;
Eric Christopher53b2cb72017-06-30 00:03:56 +00001309 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
David L. Jonesf561aba2017-03-08 01:02:16 +00001310 ABIName = A->getValue();
Eric Christopher53b2cb72017-06-30 00:03:56 +00001311 else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001312 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001313 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001314 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001315
David L. Jonesf561aba2017-03-08 01:02:16 +00001316 CmdArgs.push_back("-target-abi");
1317 CmdArgs.push_back(ABIName);
1318
1319 // Determine floating point ABI from the options & target defaults.
1320 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1321 if (ABI == arm::FloatABI::Soft) {
1322 // Floating point operations and argument passing are soft.
1323 // FIXME: This changes CPP defines, we need -target-soft-float.
1324 CmdArgs.push_back("-msoft-float");
1325 CmdArgs.push_back("-mfloat-abi");
1326 CmdArgs.push_back("soft");
1327 } else if (ABI == arm::FloatABI::SoftFP) {
1328 // Floating point operations are hard, but argument passing is soft.
1329 CmdArgs.push_back("-mfloat-abi");
1330 CmdArgs.push_back("soft");
1331 } else {
1332 // Floating point operations and argument passing are hard.
1333 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1334 CmdArgs.push_back("-mfloat-abi");
1335 CmdArgs.push_back("hard");
1336 }
1337
1338 // Forward the -mglobal-merge option for explicit control over the pass.
1339 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1340 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001341 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001342 if (A->getOption().matches(options::OPT_mno_global_merge))
1343 CmdArgs.push_back("-arm-global-merge=false");
1344 else
1345 CmdArgs.push_back("-arm-global-merge=true");
1346 }
1347
1348 if (!Args.hasFlag(options::OPT_mimplicit_float,
1349 options::OPT_mno_implicit_float, true))
1350 CmdArgs.push_back("-no-implicit-float");
1351}
1352
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001353void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1354 const ArgList &Args, bool KernelOrKext,
1355 ArgStringList &CmdArgs) const {
1356 const ToolChain &TC = getToolChain();
1357
1358 // Add the target features
1359 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1360
1361 // Add target specific flags.
1362 switch (TC.getArch()) {
1363 default:
1364 break;
1365
1366 case llvm::Triple::arm:
1367 case llvm::Triple::armeb:
1368 case llvm::Triple::thumb:
1369 case llvm::Triple::thumbeb:
1370 // Use the effective triple, which takes into account the deployment target.
1371 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1372 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1373 break;
1374
1375 case llvm::Triple::aarch64:
1376 case llvm::Triple::aarch64_be:
1377 AddAArch64TargetArgs(Args, CmdArgs);
1378 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1379 break;
1380
1381 case llvm::Triple::mips:
1382 case llvm::Triple::mipsel:
1383 case llvm::Triple::mips64:
1384 case llvm::Triple::mips64el:
1385 AddMIPSTargetArgs(Args, CmdArgs);
1386 break;
1387
1388 case llvm::Triple::ppc:
1389 case llvm::Triple::ppc64:
1390 case llvm::Triple::ppc64le:
1391 AddPPCTargetArgs(Args, CmdArgs);
1392 break;
1393
Alex Bradbury71f45452018-01-11 13:36:56 +00001394 case llvm::Triple::riscv32:
1395 case llvm::Triple::riscv64:
1396 AddRISCVTargetArgs(Args, CmdArgs);
1397 break;
1398
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001399 case llvm::Triple::sparc:
1400 case llvm::Triple::sparcel:
1401 case llvm::Triple::sparcv9:
1402 AddSparcTargetArgs(Args, CmdArgs);
1403 break;
1404
1405 case llvm::Triple::systemz:
1406 AddSystemZTargetArgs(Args, CmdArgs);
1407 break;
1408
1409 case llvm::Triple::x86:
1410 case llvm::Triple::x86_64:
1411 AddX86TargetArgs(Args, CmdArgs);
1412 break;
1413
1414 case llvm::Triple::lanai:
1415 AddLanaiTargetArgs(Args, CmdArgs);
1416 break;
1417
1418 case llvm::Triple::hexagon:
1419 AddHexagonTargetArgs(Args, CmdArgs);
1420 break;
1421
1422 case llvm::Triple::wasm32:
1423 case llvm::Triple::wasm64:
1424 AddWebAssemblyTargetArgs(Args, CmdArgs);
1425 break;
1426 }
1427}
1428
David L. Jonesf561aba2017-03-08 01:02:16 +00001429void Clang::AddAArch64TargetArgs(const ArgList &Args,
1430 ArgStringList &CmdArgs) const {
1431 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1432
1433 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1434 Args.hasArg(options::OPT_mkernel) ||
1435 Args.hasArg(options::OPT_fapple_kext))
1436 CmdArgs.push_back("-disable-red-zone");
1437
1438 if (!Args.hasFlag(options::OPT_mimplicit_float,
1439 options::OPT_mno_implicit_float, true))
1440 CmdArgs.push_back("-no-implicit-float");
1441
1442 const char *ABIName = nullptr;
1443 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1444 ABIName = A->getValue();
1445 else if (Triple.isOSDarwin())
1446 ABIName = "darwinpcs";
1447 else
1448 ABIName = "aapcs";
1449
1450 CmdArgs.push_back("-target-abi");
1451 CmdArgs.push_back(ABIName);
1452
1453 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1454 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001455 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001456 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1457 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1458 else
1459 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1460 } else if (Triple.isAndroid()) {
1461 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001462 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001463 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1464 }
1465
1466 // Forward the -mglobal-merge option for explicit control over the pass.
1467 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1468 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001469 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001470 if (A->getOption().matches(options::OPT_mno_global_merge))
1471 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1472 else
1473 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1474 }
Jessica Paquette8e71ee32018-05-02 16:42:51 +00001475
Jessica Paquette544bb552018-05-08 20:58:32 +00001476 if (!Args.hasArg(options::OPT_mno_outline) &&
1477 Args.getLastArg(options::OPT_moutline)) {
Jessica Paquette8e71ee32018-05-02 16:42:51 +00001478 CmdArgs.push_back("-mllvm");
1479 CmdArgs.push_back("-enable-machine-outliner");
1480 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001481}
1482
1483void Clang::AddMIPSTargetArgs(const ArgList &Args,
1484 ArgStringList &CmdArgs) const {
1485 const Driver &D = getToolChain().getDriver();
1486 StringRef CPUName;
1487 StringRef ABIName;
1488 const llvm::Triple &Triple = getToolChain().getTriple();
1489 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1490
1491 CmdArgs.push_back("-target-abi");
1492 CmdArgs.push_back(ABIName.data());
1493
1494 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1495 if (ABI == mips::FloatABI::Soft) {
1496 // Floating point operations and argument passing are soft.
1497 CmdArgs.push_back("-msoft-float");
1498 CmdArgs.push_back("-mfloat-abi");
1499 CmdArgs.push_back("soft");
1500 } else {
1501 // Floating point operations and argument passing are hard.
1502 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1503 CmdArgs.push_back("-mfloat-abi");
1504 CmdArgs.push_back("hard");
1505 }
1506
1507 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1508 if (A->getOption().matches(options::OPT_mxgot)) {
1509 CmdArgs.push_back("-mllvm");
1510 CmdArgs.push_back("-mxgot");
1511 }
1512 }
1513
1514 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1515 options::OPT_mno_ldc1_sdc1)) {
1516 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1517 CmdArgs.push_back("-mllvm");
1518 CmdArgs.push_back("-mno-ldc1-sdc1");
1519 }
1520 }
1521
1522 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1523 options::OPT_mno_check_zero_division)) {
1524 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1525 CmdArgs.push_back("-mllvm");
1526 CmdArgs.push_back("-mno-check-zero-division");
1527 }
1528 }
1529
1530 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1531 StringRef v = A->getValue();
1532 CmdArgs.push_back("-mllvm");
1533 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1534 A->claim();
1535 }
1536
Simon Dardis31636a12017-07-20 14:04:12 +00001537 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1538 Arg *ABICalls =
1539 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1540
1541 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1542 // -mgpopt is the default for static, -fno-pic environments but these two
1543 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1544 // the only case where -mllvm -mgpopt is passed.
1545 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1546 // passed explicitly when compiling something with -mabicalls
1547 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001548 //
1549 // When the ABI in use is N64, we also need to determine the PIC mode that
1550 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001551 bool NoABICalls =
1552 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001553
1554 llvm::Reloc::Model RelocationModel;
1555 unsigned PICLevel;
1556 bool IsPIE;
1557 std::tie(RelocationModel, PICLevel, IsPIE) =
1558 ParsePICArgs(getToolChain(), Args);
1559
1560 NoABICalls = NoABICalls ||
1561 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1562
Simon Dardis31636a12017-07-20 14:04:12 +00001563 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1564 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1565 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1566 CmdArgs.push_back("-mllvm");
1567 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001568
1569 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1570 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001571 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001572 options::OPT_mno_extern_sdata);
1573 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1574 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001575 if (LocalSData) {
1576 CmdArgs.push_back("-mllvm");
1577 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1578 CmdArgs.push_back("-mlocal-sdata=1");
1579 } else {
1580 CmdArgs.push_back("-mlocal-sdata=0");
1581 }
1582 LocalSData->claim();
1583 }
1584
Simon Dardis7d318782017-07-24 14:02:09 +00001585 if (ExternSData) {
1586 CmdArgs.push_back("-mllvm");
1587 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1588 CmdArgs.push_back("-mextern-sdata=1");
1589 } else {
1590 CmdArgs.push_back("-mextern-sdata=0");
1591 }
1592 ExternSData->claim();
1593 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001594
1595 if (EmbeddedData) {
1596 CmdArgs.push_back("-mllvm");
1597 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1598 CmdArgs.push_back("-membedded-data=1");
1599 } else {
1600 CmdArgs.push_back("-membedded-data=0");
1601 }
1602 EmbeddedData->claim();
1603 }
1604
Simon Dardis31636a12017-07-20 14:04:12 +00001605 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1606 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1607
1608 if (GPOpt)
1609 GPOpt->claim();
1610
David L. Jonesf561aba2017-03-08 01:02:16 +00001611 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1612 StringRef Val = StringRef(A->getValue());
1613 if (mips::hasCompactBranches(CPUName)) {
1614 if (Val == "never" || Val == "always" || Val == "optimal") {
1615 CmdArgs.push_back("-mllvm");
1616 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1617 } else
1618 D.Diag(diag::err_drv_unsupported_option_argument)
1619 << A->getOption().getName() << Val;
1620 } else
1621 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1622 }
1623}
1624
1625void Clang::AddPPCTargetArgs(const ArgList &Args,
1626 ArgStringList &CmdArgs) const {
1627 // Select the ABI to use.
1628 const char *ABIName = nullptr;
1629 if (getToolChain().getTriple().isOSLinux())
1630 switch (getToolChain().getArch()) {
1631 case llvm::Triple::ppc64: {
1632 // When targeting a processor that supports QPX, or if QPX is
1633 // specifically enabled, default to using the ABI that supports QPX (so
1634 // long as it is not specifically disabled).
1635 bool HasQPX = false;
1636 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1637 HasQPX = A->getValue() == StringRef("a2q");
1638 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1639 if (HasQPX) {
1640 ABIName = "elfv1-qpx";
1641 break;
1642 }
1643
1644 ABIName = "elfv1";
1645 break;
1646 }
1647 case llvm::Triple::ppc64le:
1648 ABIName = "elfv2";
1649 break;
1650 default:
1651 break;
1652 }
1653
1654 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1655 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1656 // the option if given as we don't have backend support for any targets
1657 // that don't use the altivec abi.
1658 if (StringRef(A->getValue()) != "altivec")
1659 ABIName = A->getValue();
1660
1661 ppc::FloatABI FloatABI =
1662 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1663
1664 if (FloatABI == ppc::FloatABI::Soft) {
1665 // Floating point operations and argument passing are soft.
1666 CmdArgs.push_back("-msoft-float");
1667 CmdArgs.push_back("-mfloat-abi");
1668 CmdArgs.push_back("soft");
1669 } else {
1670 // Floating point operations and argument passing are hard.
1671 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1672 CmdArgs.push_back("-mfloat-abi");
1673 CmdArgs.push_back("hard");
1674 }
1675
1676 if (ABIName) {
1677 CmdArgs.push_back("-target-abi");
1678 CmdArgs.push_back(ABIName);
1679 }
1680}
1681
Alex Bradbury71f45452018-01-11 13:36:56 +00001682void Clang::AddRISCVTargetArgs(const ArgList &Args,
1683 ArgStringList &CmdArgs) const {
1684 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001685 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001686 const char *ABIName = nullptr;
1687 const llvm::Triple &Triple = getToolChain().getTriple();
1688 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1689 ABIName = A->getValue();
1690 else if (Triple.getArch() == llvm::Triple::riscv32)
1691 ABIName = "ilp32";
1692 else if (Triple.getArch() == llvm::Triple::riscv64)
1693 ABIName = "lp64";
1694 else
1695 llvm_unreachable("Unexpected triple!");
1696
1697 CmdArgs.push_back("-target-abi");
1698 CmdArgs.push_back(ABIName);
1699}
1700
David L. Jonesf561aba2017-03-08 01:02:16 +00001701void Clang::AddSparcTargetArgs(const ArgList &Args,
1702 ArgStringList &CmdArgs) const {
1703 sparc::FloatABI FloatABI =
1704 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1705
1706 if (FloatABI == sparc::FloatABI::Soft) {
1707 // Floating point operations and argument passing are soft.
1708 CmdArgs.push_back("-msoft-float");
1709 CmdArgs.push_back("-mfloat-abi");
1710 CmdArgs.push_back("soft");
1711 } else {
1712 // Floating point operations and argument passing are hard.
1713 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1714 CmdArgs.push_back("-mfloat-abi");
1715 CmdArgs.push_back("hard");
1716 }
1717}
1718
1719void Clang::AddSystemZTargetArgs(const ArgList &Args,
1720 ArgStringList &CmdArgs) const {
1721 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1722 CmdArgs.push_back("-mbackchain");
1723}
1724
1725void Clang::AddX86TargetArgs(const ArgList &Args,
1726 ArgStringList &CmdArgs) const {
1727 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1728 Args.hasArg(options::OPT_mkernel) ||
1729 Args.hasArg(options::OPT_fapple_kext))
1730 CmdArgs.push_back("-disable-red-zone");
1731
1732 // Default to avoid implicit floating-point for kernel/kext code, but allow
1733 // that to be overridden with -mno-soft-float.
1734 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1735 Args.hasArg(options::OPT_fapple_kext));
1736 if (Arg *A = Args.getLastArg(
1737 options::OPT_msoft_float, options::OPT_mno_soft_float,
1738 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1739 const Option &O = A->getOption();
1740 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1741 O.matches(options::OPT_msoft_float));
1742 }
1743 if (NoImplicitFloat)
1744 CmdArgs.push_back("-no-implicit-float");
1745
1746 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1747 StringRef Value = A->getValue();
1748 if (Value == "intel" || Value == "att") {
1749 CmdArgs.push_back("-mllvm");
1750 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1751 } else {
1752 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1753 << A->getOption().getName() << Value;
1754 }
Nico Webere3712cf2018-01-17 13:34:20 +00001755 } else if (getToolChain().getDriver().IsCLMode()) {
1756 CmdArgs.push_back("-mllvm");
1757 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001758 }
1759
1760 // Set flags to support MCU ABI.
1761 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1762 CmdArgs.push_back("-mfloat-abi");
1763 CmdArgs.push_back("soft");
1764 CmdArgs.push_back("-mstack-alignment=4");
1765 }
1766}
1767
1768void Clang::AddHexagonTargetArgs(const ArgList &Args,
1769 ArgStringList &CmdArgs) const {
1770 CmdArgs.push_back("-mqdsp6-compat");
1771 CmdArgs.push_back("-Wreturn-type");
1772
1773 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001774 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001775 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1776 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001777 }
1778
1779 if (!Args.hasArg(options::OPT_fno_short_enums))
1780 CmdArgs.push_back("-fshort-enums");
1781 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1782 CmdArgs.push_back("-mllvm");
1783 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1784 }
1785 CmdArgs.push_back("-mllvm");
1786 CmdArgs.push_back("-machine-sink-split=0");
1787}
1788
1789void Clang::AddLanaiTargetArgs(const ArgList &Args,
1790 ArgStringList &CmdArgs) const {
1791 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1792 StringRef CPUName = A->getValue();
1793
1794 CmdArgs.push_back("-target-cpu");
1795 CmdArgs.push_back(Args.MakeArgString(CPUName));
1796 }
1797 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1798 StringRef Value = A->getValue();
1799 // Only support mregparm=4 to support old usage. Report error for all other
1800 // cases.
1801 int Mregparm;
1802 if (Value.getAsInteger(10, Mregparm)) {
1803 if (Mregparm != 4) {
1804 getToolChain().getDriver().Diag(
1805 diag::err_drv_unsupported_option_argument)
1806 << A->getOption().getName() << Value;
1807 }
1808 }
1809 }
1810}
1811
1812void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1813 ArgStringList &CmdArgs) const {
1814 // Default to "hidden" visibility.
1815 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1816 options::OPT_fvisibility_ms_compat)) {
1817 CmdArgs.push_back("-fvisibility");
1818 CmdArgs.push_back("hidden");
1819 }
1820}
1821
1822void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1823 StringRef Target, const InputInfo &Output,
1824 const InputInfo &Input, const ArgList &Args) const {
1825 // If this is a dry run, do not create the compilation database file.
1826 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1827 return;
1828
1829 using llvm::yaml::escape;
1830 const Driver &D = getToolChain().getDriver();
1831
1832 if (!CompilationDatabase) {
1833 std::error_code EC;
1834 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1835 if (EC) {
1836 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1837 << EC.message();
1838 return;
1839 }
1840 CompilationDatabase = std::move(File);
1841 }
1842 auto &CDB = *CompilationDatabase;
1843 SmallString<128> Buf;
1844 if (llvm::sys::fs::current_path(Buf))
1845 Buf = ".";
1846 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1847 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1848 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1849 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1850 Buf = "-x";
1851 Buf += types::getTypeName(Input.getType());
1852 CDB << ", \"" << escape(Buf) << "\"";
1853 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1854 Buf = "--sysroot=";
1855 Buf += D.SysRoot;
1856 CDB << ", \"" << escape(Buf) << "\"";
1857 }
1858 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1859 for (auto &A: Args) {
1860 auto &O = A->getOption();
1861 // Skip language selection, which is positional.
1862 if (O.getID() == options::OPT_x)
1863 continue;
1864 // Skip writing dependency output and the compilation database itself.
1865 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1866 continue;
1867 // Skip inputs.
1868 if (O.getKind() == Option::InputClass)
1869 continue;
1870 // All other arguments are quoted and appended.
1871 ArgStringList ASL;
1872 A->render(Args, ASL);
1873 for (auto &it: ASL)
1874 CDB << ", \"" << escape(it) << "\"";
1875 }
1876 Buf = "--target=";
1877 Buf += Target;
1878 CDB << ", \"" << escape(Buf) << "\"]},\n";
1879}
1880
1881static void CollectArgsForIntegratedAssembler(Compilation &C,
1882 const ArgList &Args,
1883 ArgStringList &CmdArgs,
1884 const Driver &D) {
1885 if (UseRelaxAll(C, Args))
1886 CmdArgs.push_back("-mrelax-all");
1887
1888 // Only default to -mincremental-linker-compatible if we think we are
1889 // targeting the MSVC linker.
1890 bool DefaultIncrementalLinkerCompatible =
1891 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1892 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1893 options::OPT_mno_incremental_linker_compatible,
1894 DefaultIncrementalLinkerCompatible))
1895 CmdArgs.push_back("-mincremental-linker-compatible");
1896
1897 switch (C.getDefaultToolChain().getArch()) {
1898 case llvm::Triple::arm:
1899 case llvm::Triple::armeb:
1900 case llvm::Triple::thumb:
1901 case llvm::Triple::thumbeb:
1902 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1903 StringRef Value = A->getValue();
1904 if (Value == "always" || Value == "never" || Value == "arm" ||
1905 Value == "thumb") {
1906 CmdArgs.push_back("-mllvm");
1907 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1908 } else {
1909 D.Diag(diag::err_drv_unsupported_option_argument)
1910 << A->getOption().getName() << Value;
1911 }
1912 }
1913 break;
1914 default:
1915 break;
1916 }
1917
1918 // When passing -I arguments to the assembler we sometimes need to
1919 // unconditionally take the next argument. For example, when parsing
1920 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1921 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1922 // arg after parsing the '-I' arg.
1923 bool TakeNextArg = false;
1924
Petr Hosek5668d832017-11-22 01:38:31 +00001925 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001926 const char *MipsTargetFeature = nullptr;
1927 for (const Arg *A :
1928 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1929 A->claim();
1930
1931 for (StringRef Value : A->getValues()) {
1932 if (TakeNextArg) {
1933 CmdArgs.push_back(Value.data());
1934 TakeNextArg = false;
1935 continue;
1936 }
1937
1938 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1939 Value == "-mbig-obj")
1940 continue; // LLVM handles bigobj automatically
1941
1942 switch (C.getDefaultToolChain().getArch()) {
1943 default:
1944 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001945 case llvm::Triple::thumb:
1946 case llvm::Triple::thumbeb:
1947 case llvm::Triple::arm:
1948 case llvm::Triple::armeb:
1949 if (Value == "-mthumb")
1950 // -mthumb has already been processed in ComputeLLVMTriple()
1951 // recognize but skip over here.
1952 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001953 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001954 case llvm::Triple::mips:
1955 case llvm::Triple::mipsel:
1956 case llvm::Triple::mips64:
1957 case llvm::Triple::mips64el:
1958 if (Value == "--trap") {
1959 CmdArgs.push_back("-target-feature");
1960 CmdArgs.push_back("+use-tcc-in-div");
1961 continue;
1962 }
1963 if (Value == "--break") {
1964 CmdArgs.push_back("-target-feature");
1965 CmdArgs.push_back("-use-tcc-in-div");
1966 continue;
1967 }
1968 if (Value.startswith("-msoft-float")) {
1969 CmdArgs.push_back("-target-feature");
1970 CmdArgs.push_back("+soft-float");
1971 continue;
1972 }
1973 if (Value.startswith("-mhard-float")) {
1974 CmdArgs.push_back("-target-feature");
1975 CmdArgs.push_back("-soft-float");
1976 continue;
1977 }
1978
1979 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1980 .Case("-mips1", "+mips1")
1981 .Case("-mips2", "+mips2")
1982 .Case("-mips3", "+mips3")
1983 .Case("-mips4", "+mips4")
1984 .Case("-mips5", "+mips5")
1985 .Case("-mips32", "+mips32")
1986 .Case("-mips32r2", "+mips32r2")
1987 .Case("-mips32r3", "+mips32r3")
1988 .Case("-mips32r5", "+mips32r5")
1989 .Case("-mips32r6", "+mips32r6")
1990 .Case("-mips64", "+mips64")
1991 .Case("-mips64r2", "+mips64r2")
1992 .Case("-mips64r3", "+mips64r3")
1993 .Case("-mips64r5", "+mips64r5")
1994 .Case("-mips64r6", "+mips64r6")
1995 .Default(nullptr);
1996 if (MipsTargetFeature)
1997 continue;
1998 }
1999
2000 if (Value == "-force_cpusubtype_ALL") {
2001 // Do nothing, this is the default and we don't support anything else.
2002 } else if (Value == "-L") {
2003 CmdArgs.push_back("-msave-temp-labels");
2004 } else if (Value == "--fatal-warnings") {
2005 CmdArgs.push_back("-massembler-fatal-warnings");
2006 } else if (Value == "--noexecstack") {
2007 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002008 } else if (Value.startswith("-compress-debug-sections") ||
2009 Value.startswith("--compress-debug-sections") ||
2010 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002011 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002012 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002013 } else if (Value == "-mrelax-relocations=yes" ||
2014 Value == "--mrelax-relocations=yes") {
2015 UseRelaxRelocations = true;
2016 } else if (Value == "-mrelax-relocations=no" ||
2017 Value == "--mrelax-relocations=no") {
2018 UseRelaxRelocations = false;
2019 } else if (Value.startswith("-I")) {
2020 CmdArgs.push_back(Value.data());
2021 // We need to consume the next argument if the current arg is a plain
2022 // -I. The next arg will be the include directory.
2023 if (Value == "-I")
2024 TakeNextArg = true;
2025 } else if (Value.startswith("-gdwarf-")) {
2026 // "-gdwarf-N" options are not cc1as options.
2027 unsigned DwarfVersion = DwarfVersionNum(Value);
2028 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2029 CmdArgs.push_back(Value.data());
2030 } else {
2031 RenderDebugEnablingArgs(Args, CmdArgs,
2032 codegenoptions::LimitedDebugInfo,
2033 DwarfVersion, llvm::DebuggerKind::Default);
2034 }
2035 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2036 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2037 // Do nothing, we'll validate it later.
2038 } else if (Value == "-defsym") {
2039 if (A->getNumValues() != 2) {
2040 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2041 break;
2042 }
2043 const char *S = A->getValue(1);
2044 auto Pair = StringRef(S).split('=');
2045 auto Sym = Pair.first;
2046 auto SVal = Pair.second;
2047
2048 if (Sym.empty() || SVal.empty()) {
2049 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2050 break;
2051 }
2052 int64_t IVal;
2053 if (SVal.getAsInteger(0, IVal)) {
2054 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2055 break;
2056 }
2057 CmdArgs.push_back(Value.data());
2058 TakeNextArg = true;
2059 } else {
2060 D.Diag(diag::err_drv_unsupported_option_argument)
2061 << A->getOption().getName() << Value;
2062 }
2063 }
2064 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002065 if (UseRelaxRelocations)
2066 CmdArgs.push_back("--mrelax-relocations");
2067 if (MipsTargetFeature != nullptr) {
2068 CmdArgs.push_back("-target-feature");
2069 CmdArgs.push_back(MipsTargetFeature);
2070 }
2071}
2072
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002073static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2074 bool OFastEnabled, const ArgList &Args,
2075 ArgStringList &CmdArgs) {
2076 // Handle various floating point optimization flags, mapping them to the
2077 // appropriate LLVM code generation flags. This is complicated by several
2078 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002079 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002080 // LLVM flags based on the final state.
2081 bool HonorINFs = true;
2082 bool HonorNaNs = true;
2083 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2084 bool MathErrno = TC.IsMathErrnoDefault();
2085 bool AssociativeMath = false;
2086 bool ReciprocalMath = false;
2087 bool SignedZeros = true;
2088 bool TrappingMath = true;
2089 StringRef DenormalFPMath = "";
2090 StringRef FPContract = "";
2091
2092 for (const Arg *A : Args) {
2093 switch (A->getOption().getID()) {
2094 // If this isn't an FP option skip the claim below
2095 default: continue;
2096
2097 // Options controlling individual features
2098 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2099 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2100 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2101 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2102 case options::OPT_fmath_errno: MathErrno = true; break;
2103 case options::OPT_fno_math_errno: MathErrno = false; break;
2104 case options::OPT_fassociative_math: AssociativeMath = true; break;
2105 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2106 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2107 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2108 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2109 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2110 case options::OPT_ftrapping_math: TrappingMath = true; break;
2111 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2112
2113 case options::OPT_fdenormal_fp_math_EQ:
2114 DenormalFPMath = A->getValue();
2115 break;
2116
2117 // Validate and pass through -fp-contract option.
2118 case options::OPT_ffp_contract: {
2119 StringRef Val = A->getValue();
2120 if (Val == "fast" || Val == "on" || Val == "off")
2121 FPContract = Val;
2122 else
2123 D.Diag(diag::err_drv_unsupported_option_argument)
2124 << A->getOption().getName() << Val;
2125 break;
2126 }
2127
2128 case options::OPT_ffinite_math_only:
2129 HonorINFs = false;
2130 HonorNaNs = false;
2131 break;
2132 case options::OPT_fno_finite_math_only:
2133 HonorINFs = true;
2134 HonorNaNs = true;
2135 break;
2136
2137 case options::OPT_funsafe_math_optimizations:
2138 AssociativeMath = true;
2139 ReciprocalMath = true;
2140 SignedZeros = false;
2141 TrappingMath = false;
2142 break;
2143 case options::OPT_fno_unsafe_math_optimizations:
2144 AssociativeMath = false;
2145 ReciprocalMath = false;
2146 SignedZeros = true;
2147 TrappingMath = true;
2148 // -fno_unsafe_math_optimizations restores default denormal handling
2149 DenormalFPMath = "";
2150 break;
2151
2152 case options::OPT_Ofast:
2153 // If -Ofast is the optimization level, then -ffast-math should be enabled
2154 if (!OFastEnabled)
2155 continue;
2156 LLVM_FALLTHROUGH;
2157 case options::OPT_ffast_math:
2158 HonorINFs = false;
2159 HonorNaNs = false;
2160 MathErrno = false;
2161 AssociativeMath = true;
2162 ReciprocalMath = true;
2163 SignedZeros = false;
2164 TrappingMath = false;
2165 // If fast-math is set then set the fp-contract mode to fast.
2166 FPContract = "fast";
2167 break;
2168 case options::OPT_fno_fast_math:
2169 HonorINFs = true;
2170 HonorNaNs = true;
2171 // Turning on -ffast-math (with either flag) removes the need for
2172 // MathErrno. However, turning *off* -ffast-math merely restores the
2173 // toolchain default (which may be false).
2174 MathErrno = TC.IsMathErrnoDefault();
2175 AssociativeMath = false;
2176 ReciprocalMath = false;
2177 SignedZeros = true;
2178 TrappingMath = true;
2179 // -fno_fast_math restores default denormal and fpcontract handling
2180 DenormalFPMath = "";
2181 FPContract = "";
2182 break;
2183 }
2184
2185 // If we handled this option claim it
2186 A->claim();
2187 }
2188
2189 if (!HonorINFs)
2190 CmdArgs.push_back("-menable-no-infs");
2191
2192 if (!HonorNaNs)
2193 CmdArgs.push_back("-menable-no-nans");
2194
2195 if (MathErrno)
2196 CmdArgs.push_back("-fmath-errno");
2197
2198 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2199 !TrappingMath)
2200 CmdArgs.push_back("-menable-unsafe-fp-math");
2201
2202 if (!SignedZeros)
2203 CmdArgs.push_back("-fno-signed-zeros");
2204
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002205 if (AssociativeMath && !SignedZeros && !TrappingMath)
2206 CmdArgs.push_back("-mreassociate");
2207
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002208 if (ReciprocalMath)
2209 CmdArgs.push_back("-freciprocal-math");
2210
2211 if (!TrappingMath)
2212 CmdArgs.push_back("-fno-trapping-math");
2213
2214 if (!DenormalFPMath.empty())
2215 CmdArgs.push_back(
2216 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2217
2218 if (!FPContract.empty())
2219 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2220
2221 ParseMRecip(D, Args, CmdArgs);
2222
2223 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2224 // individual features enabled by -ffast-math instead of the option itself as
2225 // that's consistent with gcc's behaviour.
2226 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2227 ReciprocalMath && !SignedZeros && !TrappingMath)
2228 CmdArgs.push_back("-ffast-math");
2229
2230 // Handle __FINITE_MATH_ONLY__ similarly.
2231 if (!HonorINFs && !HonorNaNs)
2232 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002233
2234 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2235 CmdArgs.push_back("-mfpmath");
2236 CmdArgs.push_back(A->getValue());
2237 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002238
2239 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002240 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2241 options::OPT_fstrict_float_cast_overflow, false))
2242 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002243}
2244
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002245static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2246 const llvm::Triple &Triple,
2247 const InputInfo &Input) {
2248 // Enable region store model by default.
2249 CmdArgs.push_back("-analyzer-store=region");
2250
2251 // Treat blocks as analysis entry points.
2252 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2253
2254 CmdArgs.push_back("-analyzer-eagerly-assume");
2255
2256 // Add default argument set.
2257 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2258 CmdArgs.push_back("-analyzer-checker=core");
2259 CmdArgs.push_back("-analyzer-checker=apiModeling");
2260
2261 if (!Triple.isWindowsMSVCEnvironment()) {
2262 CmdArgs.push_back("-analyzer-checker=unix");
2263 } else {
2264 // Enable "unix" checkers that also work on Windows.
2265 CmdArgs.push_back("-analyzer-checker=unix.API");
2266 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2267 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2268 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2269 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2270 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2271 }
2272
2273 // Disable some unix checkers for PS4.
2274 if (Triple.isPS4CPU()) {
2275 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2276 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2277 }
2278
2279 if (Triple.isOSDarwin())
2280 CmdArgs.push_back("-analyzer-checker=osx");
2281
2282 CmdArgs.push_back("-analyzer-checker=deadcode");
2283
2284 if (types::isCXX(Input.getType()))
2285 CmdArgs.push_back("-analyzer-checker=cplusplus");
2286
2287 if (!Triple.isPS4CPU()) {
2288 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2289 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2290 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2291 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2292 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2293 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2294 }
2295
2296 // Default nullability checks.
2297 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2298 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2299 }
2300
2301 // Set the output format. The default is plist, for (lame) historical reasons.
2302 CmdArgs.push_back("-analyzer-output");
2303 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2304 CmdArgs.push_back(A->getValue());
2305 else
2306 CmdArgs.push_back("plist");
2307
2308 // Disable the presentation of standard compiler warnings when using
2309 // --analyze. We only want to show static analyzer diagnostics or frontend
2310 // errors.
2311 CmdArgs.push_back("-w");
2312
2313 // Add -Xanalyzer arguments when running as analyzer.
2314 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2315}
2316
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002317static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002318 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002319 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2320
2321 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2322 // doesn't even have a stack!
2323 if (EffectiveTriple.isNVPTX())
2324 return;
2325
2326 // -stack-protector=0 is default.
2327 unsigned StackProtectorLevel = 0;
2328 unsigned DefaultStackProtectorLevel =
2329 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2330
2331 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2332 options::OPT_fstack_protector_all,
2333 options::OPT_fstack_protector_strong,
2334 options::OPT_fstack_protector)) {
2335 if (A->getOption().matches(options::OPT_fstack_protector))
2336 StackProtectorLevel =
2337 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2338 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2339 StackProtectorLevel = LangOptions::SSPStrong;
2340 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2341 StackProtectorLevel = LangOptions::SSPReq;
2342 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002343 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002344 }
2345
2346 if (StackProtectorLevel) {
2347 CmdArgs.push_back("-stack-protector");
2348 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2349 }
2350
2351 // --param ssp-buffer-size=
2352 for (const Arg *A : Args.filtered(options::OPT__param)) {
2353 StringRef Str(A->getValue());
2354 if (Str.startswith("ssp-buffer-size=")) {
2355 if (StackProtectorLevel) {
2356 CmdArgs.push_back("-stack-protector-buffer-size");
2357 // FIXME: Verify the argument is a valid integer.
2358 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2359 }
2360 A->claim();
2361 }
2362 }
2363}
2364
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002365static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2366 const unsigned ForwardedArguments[] = {
2367 options::OPT_cl_opt_disable,
2368 options::OPT_cl_strict_aliasing,
2369 options::OPT_cl_single_precision_constant,
2370 options::OPT_cl_finite_math_only,
2371 options::OPT_cl_kernel_arg_info,
2372 options::OPT_cl_unsafe_math_optimizations,
2373 options::OPT_cl_fast_relaxed_math,
2374 options::OPT_cl_mad_enable,
2375 options::OPT_cl_no_signed_zeros,
2376 options::OPT_cl_denorms_are_zero,
2377 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002378 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002379 };
2380
2381 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2382 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2383 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2384 }
2385
2386 for (const auto &Arg : ForwardedArguments)
2387 if (const auto *A = Args.getLastArg(Arg))
2388 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2389}
2390
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002391static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2392 ArgStringList &CmdArgs) {
2393 bool ARCMTEnabled = false;
2394 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2395 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2396 options::OPT_ccc_arcmt_modify,
2397 options::OPT_ccc_arcmt_migrate)) {
2398 ARCMTEnabled = true;
2399 switch (A->getOption().getID()) {
2400 default: llvm_unreachable("missed a case");
2401 case options::OPT_ccc_arcmt_check:
2402 CmdArgs.push_back("-arcmt-check");
2403 break;
2404 case options::OPT_ccc_arcmt_modify:
2405 CmdArgs.push_back("-arcmt-modify");
2406 break;
2407 case options::OPT_ccc_arcmt_migrate:
2408 CmdArgs.push_back("-arcmt-migrate");
2409 CmdArgs.push_back("-mt-migrate-directory");
2410 CmdArgs.push_back(A->getValue());
2411
2412 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2413 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2414 break;
2415 }
2416 }
2417 } else {
2418 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2419 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2420 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2421 }
2422
2423 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2424 if (ARCMTEnabled)
2425 D.Diag(diag::err_drv_argument_not_allowed_with)
2426 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2427
2428 CmdArgs.push_back("-mt-migrate-directory");
2429 CmdArgs.push_back(A->getValue());
2430
2431 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2432 options::OPT_objcmt_migrate_subscripting,
2433 options::OPT_objcmt_migrate_property)) {
2434 // None specified, means enable them all.
2435 CmdArgs.push_back("-objcmt-migrate-literals");
2436 CmdArgs.push_back("-objcmt-migrate-subscripting");
2437 CmdArgs.push_back("-objcmt-migrate-property");
2438 } else {
2439 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2440 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2441 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2442 }
2443 } else {
2444 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2445 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2446 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2447 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2448 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2449 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2450 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2451 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2452 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2453 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2454 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2455 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2456 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2457 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2458 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2459 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2460 }
2461}
2462
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002463static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2464 const ArgList &Args, ArgStringList &CmdArgs) {
2465 // -fbuiltin is default unless -mkernel is used.
2466 bool UseBuiltins =
2467 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2468 !Args.hasArg(options::OPT_mkernel));
2469 if (!UseBuiltins)
2470 CmdArgs.push_back("-fno-builtin");
2471
2472 // -ffreestanding implies -fno-builtin.
2473 if (Args.hasArg(options::OPT_ffreestanding))
2474 UseBuiltins = false;
2475
2476 // Process the -fno-builtin-* options.
2477 for (const auto &Arg : Args) {
2478 const Option &O = Arg->getOption();
2479 if (!O.matches(options::OPT_fno_builtin_))
2480 continue;
2481
2482 Arg->claim();
2483
2484 // If -fno-builtin is specified, then there's no need to pass the option to
2485 // the frontend.
2486 if (!UseBuiltins)
2487 continue;
2488
2489 StringRef FuncName = Arg->getValue();
2490 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2491 }
2492
2493 // le32-specific flags:
2494 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2495 // by default.
2496 if (TC.getArch() == llvm::Triple::le32)
2497 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002498}
2499
Adrian Prantl70599032018-02-09 18:43:10 +00002500void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2501 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2502 llvm::sys::path::append(Result, "org.llvm.clang.");
2503 appendUserToPath(Result);
2504 llvm::sys::path::append(Result, "ModuleCache");
2505}
2506
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002507static void RenderModulesOptions(Compilation &C, const Driver &D,
2508 const ArgList &Args, const InputInfo &Input,
2509 const InputInfo &Output,
2510 ArgStringList &CmdArgs, bool &HaveModules) {
2511 // -fmodules enables the use of precompiled modules (off by default).
2512 // Users can pass -fno-cxx-modules to turn off modules support for
2513 // C++/Objective-C++ programs.
2514 bool HaveClangModules = false;
2515 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2516 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2517 options::OPT_fno_cxx_modules, true);
2518 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2519 CmdArgs.push_back("-fmodules");
2520 HaveClangModules = true;
2521 }
2522 }
2523
2524 HaveModules = HaveClangModules;
2525 if (Args.hasArg(options::OPT_fmodules_ts)) {
2526 CmdArgs.push_back("-fmodules-ts");
2527 HaveModules = true;
2528 }
2529
2530 // -fmodule-maps enables implicit reading of module map files. By default,
2531 // this is enabled if we are using Clang's flavor of precompiled modules.
2532 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2533 options::OPT_fno_implicit_module_maps, HaveClangModules))
2534 CmdArgs.push_back("-fimplicit-module-maps");
2535
2536 // -fmodules-decluse checks that modules used are declared so (off by default)
2537 if (Args.hasFlag(options::OPT_fmodules_decluse,
2538 options::OPT_fno_modules_decluse, false))
2539 CmdArgs.push_back("-fmodules-decluse");
2540
2541 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2542 // all #included headers are part of modules.
2543 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2544 options::OPT_fno_modules_strict_decluse, false))
2545 CmdArgs.push_back("-fmodules-strict-decluse");
2546
2547 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002548 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002549 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2550 options::OPT_fno_implicit_modules, HaveClangModules)) {
2551 if (HaveModules)
2552 CmdArgs.push_back("-fno-implicit-modules");
2553 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002554 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002555 // -fmodule-cache-path specifies where our implicitly-built module files
2556 // should be written.
2557 SmallString<128> Path;
2558 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2559 Path = A->getValue();
2560
2561 if (C.isForDiagnostics()) {
2562 // When generating crash reports, we want to emit the modules along with
2563 // the reproduction sources, so we ignore any provided module path.
2564 Path = Output.getFilename();
2565 llvm::sys::path::replace_extension(Path, ".cache");
2566 llvm::sys::path::append(Path, "modules");
2567 } else if (Path.empty()) {
2568 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002569 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002570 }
2571
2572 const char Arg[] = "-fmodules-cache-path=";
2573 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2574 CmdArgs.push_back(Args.MakeArgString(Path));
2575 }
2576
2577 if (HaveModules) {
2578 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2579 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2580 CmdArgs.push_back(Args.MakeArgString(
2581 std::string("-fprebuilt-module-path=") + A->getValue()));
2582 A->claim();
2583 }
2584 }
2585
2586 // -fmodule-name specifies the module that is currently being built (or
2587 // used for header checking by -fmodule-maps).
2588 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2589
2590 // -fmodule-map-file can be used to specify files containing module
2591 // definitions.
2592 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2593
2594 // -fbuiltin-module-map can be used to load the clang
2595 // builtin headers modulemap file.
2596 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2597 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2598 llvm::sys::path::append(BuiltinModuleMap, "include");
2599 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2600 if (llvm::sys::fs::exists(BuiltinModuleMap))
2601 CmdArgs.push_back(
2602 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2603 }
2604
2605 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2606 // names to precompiled module files (the module is loaded only if used).
2607 // The -fmodule-file=<file> form can be used to unconditionally load
2608 // precompiled module files (whether used or not).
2609 if (HaveModules)
2610 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2611 else
2612 Args.ClaimAllArgs(options::OPT_fmodule_file);
2613
2614 // When building modules and generating crashdumps, we need to dump a module
2615 // dependency VFS alongside the output.
2616 if (HaveClangModules && C.isForDiagnostics()) {
2617 SmallString<128> VFSDir(Output.getFilename());
2618 llvm::sys::path::replace_extension(VFSDir, ".cache");
2619 // Add the cache directory as a temp so the crash diagnostics pick it up.
2620 C.addTempFile(Args.MakeArgString(VFSDir));
2621
2622 llvm::sys::path::append(VFSDir, "vfs");
2623 CmdArgs.push_back("-module-dependency-dir");
2624 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2625 }
2626
2627 if (HaveClangModules)
2628 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2629
2630 // Pass through all -fmodules-ignore-macro arguments.
2631 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2632 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2633 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2634
2635 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2636
2637 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2638 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2639 D.Diag(diag::err_drv_argument_not_allowed_with)
2640 << A->getAsString(Args) << "-fbuild-session-timestamp";
2641
2642 llvm::sys::fs::file_status Status;
2643 if (llvm::sys::fs::status(A->getValue(), Status))
2644 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2645 CmdArgs.push_back(
2646 Args.MakeArgString("-fbuild-session-timestamp=" +
2647 Twine((uint64_t)Status.getLastModificationTime()
2648 .time_since_epoch()
2649 .count())));
2650 }
2651
2652 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2653 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2654 options::OPT_fbuild_session_file))
2655 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2656
2657 Args.AddLastArg(CmdArgs,
2658 options::OPT_fmodules_validate_once_per_build_session);
2659 }
2660
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002661 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2662 options::OPT_fno_modules_validate_system_headers,
2663 ImplicitModules))
2664 CmdArgs.push_back("-fmodules-validate-system-headers");
2665
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002666 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2667}
2668
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002669static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2670 ArgStringList &CmdArgs) {
2671 // -fsigned-char is default.
2672 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2673 options::OPT_fno_signed_char,
2674 options::OPT_funsigned_char,
2675 options::OPT_fno_unsigned_char)) {
2676 if (A->getOption().matches(options::OPT_funsigned_char) ||
2677 A->getOption().matches(options::OPT_fno_signed_char)) {
2678 CmdArgs.push_back("-fno-signed-char");
2679 }
2680 } else if (!isSignedCharDefault(T)) {
2681 CmdArgs.push_back("-fno-signed-char");
2682 }
2683
Richard Smith3a8244d2018-05-01 05:02:45 +00002684 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2685 CmdArgs.push_back("-fchar8_t");
2686
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002687 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2688 options::OPT_fno_short_wchar)) {
2689 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2690 CmdArgs.push_back("-fwchar-type=short");
2691 CmdArgs.push_back("-fno-signed-wchar");
2692 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002693 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002694 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002695 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2696 T.getOS() == llvm::Triple::OpenBSD))
2697 CmdArgs.push_back("-fno-signed-wchar");
2698 else
2699 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002700 }
2701 }
2702}
2703
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002704static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2705 const llvm::Triple &T, const ArgList &Args,
2706 ObjCRuntime &Runtime, bool InferCovariantReturns,
2707 const InputInfo &Input, ArgStringList &CmdArgs) {
2708 const llvm::Triple::ArchType Arch = TC.getArch();
2709
2710 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2711 // is the default. Except for deployment target of 10.5, next runtime is
2712 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2713 if (Runtime.isNonFragile()) {
2714 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2715 options::OPT_fno_objc_legacy_dispatch,
2716 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2717 if (TC.UseObjCMixedDispatch())
2718 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2719 else
2720 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2721 }
2722 }
2723
2724 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2725 // to do Array/Dictionary subscripting by default.
2726 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2727 !T.isMacOSXVersionLT(10, 7) &&
2728 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2729 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2730
2731 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2732 // NOTE: This logic is duplicated in ToolChains.cpp.
2733 if (isObjCAutoRefCount(Args)) {
2734 TC.CheckObjCARC();
2735
2736 CmdArgs.push_back("-fobjc-arc");
2737
2738 // FIXME: It seems like this entire block, and several around it should be
2739 // wrapped in isObjC, but for now we just use it here as this is where it
2740 // was being used previously.
2741 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2742 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2743 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2744 else
2745 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2746 }
2747
2748 // Allow the user to enable full exceptions code emission.
2749 // We default off for Objective-C, on for Objective-C++.
2750 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2751 options::OPT_fno_objc_arc_exceptions,
2752 /*default=*/types::isCXX(Input.getType())))
2753 CmdArgs.push_back("-fobjc-arc-exceptions");
2754 }
2755
2756 // Silence warning for full exception code emission options when explicitly
2757 // set to use no ARC.
2758 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2759 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2760 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2761 }
2762
2763 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2764 // rewriter.
2765 if (InferCovariantReturns)
2766 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2767
2768 // Pass down -fobjc-weak or -fno-objc-weak if present.
2769 if (types::isObjC(Input.getType())) {
2770 auto WeakArg =
2771 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2772 if (!WeakArg) {
2773 // nothing to do
2774 } else if (!Runtime.allowsWeak()) {
2775 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2776 D.Diag(diag::err_objc_weak_unsupported);
2777 } else {
2778 WeakArg->render(Args, CmdArgs);
2779 }
2780 }
2781}
2782
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002783static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2784 ArgStringList &CmdArgs) {
2785 bool CaretDefault = true;
2786 bool ColumnDefault = true;
2787
2788 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2789 options::OPT__SLASH_diagnostics_column,
2790 options::OPT__SLASH_diagnostics_caret)) {
2791 switch (A->getOption().getID()) {
2792 case options::OPT__SLASH_diagnostics_caret:
2793 CaretDefault = true;
2794 ColumnDefault = true;
2795 break;
2796 case options::OPT__SLASH_diagnostics_column:
2797 CaretDefault = false;
2798 ColumnDefault = true;
2799 break;
2800 case options::OPT__SLASH_diagnostics_classic:
2801 CaretDefault = false;
2802 ColumnDefault = false;
2803 break;
2804 }
2805 }
2806
2807 // -fcaret-diagnostics is default.
2808 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2809 options::OPT_fno_caret_diagnostics, CaretDefault))
2810 CmdArgs.push_back("-fno-caret-diagnostics");
2811
2812 // -fdiagnostics-fixit-info is default, only pass non-default.
2813 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2814 options::OPT_fno_diagnostics_fixit_info))
2815 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2816
2817 // Enable -fdiagnostics-show-option by default.
2818 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2819 options::OPT_fno_diagnostics_show_option))
2820 CmdArgs.push_back("-fdiagnostics-show-option");
2821
2822 if (const Arg *A =
2823 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2824 CmdArgs.push_back("-fdiagnostics-show-category");
2825 CmdArgs.push_back(A->getValue());
2826 }
2827
2828 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2829 options::OPT_fno_diagnostics_show_hotness, false))
2830 CmdArgs.push_back("-fdiagnostics-show-hotness");
2831
2832 if (const Arg *A =
2833 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2834 std::string Opt =
2835 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2836 CmdArgs.push_back(Args.MakeArgString(Opt));
2837 }
2838
2839 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2840 CmdArgs.push_back("-fdiagnostics-format");
2841 CmdArgs.push_back(A->getValue());
2842 }
2843
2844 if (const Arg *A = Args.getLastArg(
2845 options::OPT_fdiagnostics_show_note_include_stack,
2846 options::OPT_fno_diagnostics_show_note_include_stack)) {
2847 const Option &O = A->getOption();
2848 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2849 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2850 else
2851 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2852 }
2853
2854 // Color diagnostics are parsed by the driver directly from argv and later
2855 // re-parsed to construct this job; claim any possible color diagnostic here
2856 // to avoid warn_drv_unused_argument and diagnose bad
2857 // OPT_fdiagnostics_color_EQ values.
2858 for (const Arg *A : Args) {
2859 const Option &O = A->getOption();
2860 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2861 !O.matches(options::OPT_fdiagnostics_color) &&
2862 !O.matches(options::OPT_fno_color_diagnostics) &&
2863 !O.matches(options::OPT_fno_diagnostics_color) &&
2864 !O.matches(options::OPT_fdiagnostics_color_EQ))
2865 continue;
2866
2867 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2868 StringRef Value(A->getValue());
2869 if (Value != "always" && Value != "never" && Value != "auto")
2870 D.Diag(diag::err_drv_clang_unsupported)
2871 << ("-fdiagnostics-color=" + Value).str();
2872 }
2873 A->claim();
2874 }
2875
2876 if (D.getDiags().getDiagnosticOptions().ShowColors)
2877 CmdArgs.push_back("-fcolor-diagnostics");
2878
2879 if (Args.hasArg(options::OPT_fansi_escape_codes))
2880 CmdArgs.push_back("-fansi-escape-codes");
2881
2882 if (!Args.hasFlag(options::OPT_fshow_source_location,
2883 options::OPT_fno_show_source_location))
2884 CmdArgs.push_back("-fno-show-source-location");
2885
2886 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2887 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2888
2889 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2890 ColumnDefault))
2891 CmdArgs.push_back("-fno-show-column");
2892
2893 if (!Args.hasFlag(options::OPT_fspell_checking,
2894 options::OPT_fno_spell_checking))
2895 CmdArgs.push_back("-fno-spell-checking");
2896}
2897
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002898static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2899 const llvm::Triple &T, const ArgList &Args,
2900 bool EmitCodeView, bool IsWindowsMSVC,
2901 ArgStringList &CmdArgs,
2902 codegenoptions::DebugInfoKind &DebugInfoKind,
2903 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002904 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2905 options::OPT_fno_debug_info_for_profiling, false))
2906 CmdArgs.push_back("-fdebug-info-for-profiling");
2907
2908 // The 'g' groups options involve a somewhat intricate sequence of decisions
2909 // about what to pass from the driver to the frontend, but by the time they
2910 // reach cc1 they've been factored into three well-defined orthogonal choices:
2911 // * what level of debug info to generate
2912 // * what dwarf version to write
2913 // * what debugger tuning to use
2914 // This avoids having to monkey around further in cc1 other than to disable
2915 // codeview if not running in a Windows environment. Perhaps even that
2916 // decision should be made in the driver as well though.
2917 unsigned DWARFVersion = 0;
2918 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2919
2920 bool SplitDWARFInlining =
2921 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2922 options::OPT_fno_split_dwarf_inlining, true);
2923
2924 Args.ClaimAllArgs(options::OPT_g_Group);
2925
2926 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2927
2928 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2929 // If the last option explicitly specified a debug-info level, use it.
2930 if (A->getOption().matches(options::OPT_gN_Group)) {
2931 DebugInfoKind = DebugLevelToInfoKind(*A);
2932 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2933 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2934 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2935 // This gets a bit more complicated if you've disabled inline info in the
2936 // skeleton CUs (SplitDWARFInlining) - then there's value in composing
2937 // split-dwarf and line-tables-only, so let those compose naturally in
2938 // that case.
2939 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2940 if (SplitDWARFArg) {
2941 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2942 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2943 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2944 SplitDWARFInlining))
2945 SplitDWARFArg = nullptr;
2946 } else if (SplitDWARFInlining)
2947 DebugInfoKind = codegenoptions::NoDebugInfo;
2948 }
2949 } else {
2950 // For any other 'g' option, use Limited.
2951 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2952 }
2953 }
2954
2955 // If a debugger tuning argument appeared, remember it.
2956 if (const Arg *A =
2957 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2958 if (A->getOption().matches(options::OPT_glldb))
2959 DebuggerTuning = llvm::DebuggerKind::LLDB;
2960 else if (A->getOption().matches(options::OPT_gsce))
2961 DebuggerTuning = llvm::DebuggerKind::SCE;
2962 else
2963 DebuggerTuning = llvm::DebuggerKind::GDB;
2964 }
2965
2966 // If a -gdwarf argument appeared, remember it.
2967 if (const Arg *A =
2968 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2969 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2970 DWARFVersion = DwarfVersionNum(A->getSpelling());
2971
2972 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2973 // argument parsing.
Reid Kleckner54af3e72018-02-26 22:55:33 +00002974 if (EmitCodeView) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002975 // DWARFVersion remains at 0 if no explicit choice was made.
2976 CmdArgs.push_back("-gcodeview");
2977 } else if (DWARFVersion == 0 &&
2978 DebugInfoKind != codegenoptions::NoDebugInfo) {
2979 DWARFVersion = TC.GetDefaultDwarfVersion();
2980 }
2981
2982 // We ignore flag -gstrict-dwarf for now.
2983 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2984 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2985
Paul Robinsona8280812017-09-29 21:25:07 +00002986 // Column info is included by default for everything except SCE and CodeView.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002987 // Clang doesn't track end columns, just starting columns, which, in theory,
2988 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2989 // debuggers don't handle missing end columns well, so it's better not to
2990 // include any column info.
2991 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00002992 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00002993 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002994 CmdArgs.push_back("-dwarf-column-info");
2995
2996 // FIXME: Move backend command line options to the module.
2997 // If -gline-tables-only is the last option it wins.
2998 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2999 Args.hasArg(options::OPT_gmodules)) {
3000 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3001 CmdArgs.push_back("-dwarf-ext-refs");
3002 CmdArgs.push_back("-fmodule-format=obj");
3003 }
3004
3005 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3006 // splitting and extraction.
3007 // FIXME: Currently only works on Linux.
3008 if (T.isOSLinux()) {
3009 if (!SplitDWARFInlining)
3010 CmdArgs.push_back("-fno-split-dwarf-inlining");
3011
3012 if (SplitDWARFArg) {
3013 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3014 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3015 CmdArgs.push_back("-enable-split-dwarf");
3016 }
3017 }
3018
3019 // After we've dealt with all combinations of things that could
3020 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3021 // figure out if we need to "upgrade" it to standalone debug info.
3022 // We parse these two '-f' options whether or not they will be used,
3023 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3024 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3025 options::OPT_fno_standalone_debug,
3026 TC.GetDefaultStandaloneDebug());
3027 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3028 DebugInfoKind = codegenoptions::FullDebugInfo;
3029
Scott Lindera2fbcef2018-02-26 17:32:31 +00003030 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, false)) {
3031 // Source embedding is a vendor extension to DWARF v5. By now we have
3032 // checked if a DWARF version was stated explicitly, and have otherwise
3033 // fallen back to the target default, so if this is still not at least 5 we
3034 // emit an error.
3035 if (DWARFVersion < 5)
3036 D.Diag(diag::err_drv_argument_only_allowed_with)
3037 << Args.getLastArg(options::OPT_gembed_source)->getAsString(Args)
3038 << "-gdwarf-5";
3039 CmdArgs.push_back("-gembed-source");
3040 }
3041
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003042 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3043 DebuggerTuning);
3044
3045 // -fdebug-macro turns on macro debug info generation.
3046 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3047 false))
3048 CmdArgs.push_back("-debug-info-macro");
3049
3050 // -ggnu-pubnames turns on gnu style pubnames in the backend.
Peter Collingbourneb52e2362017-09-12 21:50:41 +00003051 if (Args.hasArg(options::OPT_ggnu_pubnames))
3052 CmdArgs.push_back("-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003053
3054 // -gdwarf-aranges turns on the emission of the aranges section in the
3055 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003056 // Always enabled for SCE tuning.
3057 if (Args.hasArg(options::OPT_gdwarf_aranges) ||
3058 DebuggerTuning == llvm::DebuggerKind::SCE) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003059 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003060 CmdArgs.push_back("-generate-arange-section");
3061 }
3062
3063 if (Args.hasFlag(options::OPT_fdebug_types_section,
3064 options::OPT_fno_debug_types_section, false)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003065 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003066 CmdArgs.push_back("-generate-type-units");
3067 }
3068
Paul Robinson1787f812017-09-28 18:37:02 +00003069 // Decide how to render forward declarations of template instantiations.
3070 // SCE wants full descriptions, others just get them in the name.
3071 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3072 CmdArgs.push_back("-debug-forward-template-params");
3073
Paul Robinsona8280812017-09-29 21:25:07 +00003074 // Do we need to explicitly import anonymous namespaces into the parent scope?
3075 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3076 CmdArgs.push_back("-dwarf-explicit-import");
3077
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003078 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
3079}
3080
David L. Jonesf561aba2017-03-08 01:02:16 +00003081void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3082 const InputInfo &Output, const InputInfoList &Inputs,
3083 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003084 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003085 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3086 const std::string &TripleStr = Triple.getTriple();
3087
3088 bool KernelOrKext =
3089 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3090 const Driver &D = getToolChain().getDriver();
3091 ArgStringList CmdArgs;
3092
3093 // Check number of inputs for sanity. We need at least one input.
3094 assert(Inputs.size() >= 1 && "Must have at least one input.");
3095 const InputInfo &Input = Inputs[0];
Yaxun Liu398612b2018-05-08 21:02:12 +00003096 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003097 // device-side compilations). OpenMP device jobs also take the host IR as a
3098 // second input. All other jobs are expected to have exactly one
3099 // input.
3100 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003101 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003102 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Yaxun Liu398612b2018-05-08 21:02:12 +00003103 assert((IsCuda || IsHIP || (IsOpenMPDevice && Inputs.size() == 2) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003104 Inputs.size() == 1) &&
3105 "Unable to handle multiple inputs.");
3106
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003107 const llvm::Triple *AuxTriple =
3108 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3109
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003110 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3111 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3112 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003113 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003114
Yaxun Liu398612b2018-05-08 21:02:12 +00003115 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3116 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3117 // Windows), we need to pass Windows-specific flags to cc1.
3118 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003119 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3120 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3121 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3122 }
3123
3124 // C++ is not supported for IAMCU.
3125 if (IsIAMCU && types::isCXX(Input.getType()))
3126 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3127
3128 // Invoke ourselves in -cc1 mode.
3129 //
3130 // FIXME: Implement custom jobs for internal actions.
3131 CmdArgs.push_back("-cc1");
3132
3133 // Add the "effective" target triple.
3134 CmdArgs.push_back("-triple");
3135 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3136
3137 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3138 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3139 Args.ClaimAllArgs(options::OPT_MJ);
3140 }
3141
Yaxun Liu398612b2018-05-08 21:02:12 +00003142 if (IsCuda || IsHIP) {
3143 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3144 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003145 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003146 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3147 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003148 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3149 ->getTriple()
3150 .normalize();
3151 else
Yaxun Liu398612b2018-05-08 21:02:12 +00003152 NormalizedTriple =
3153 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3154 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3155 ->getTriple()
3156 .normalize();
David L. Jonesf561aba2017-03-08 01:02:16 +00003157
3158 CmdArgs.push_back("-aux-triple");
3159 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3160 }
3161
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003162 if (IsOpenMPDevice) {
3163 // We have to pass the triple of the host if compiling for an OpenMP device.
3164 std::string NormalizedTriple =
3165 C.getSingleOffloadToolChain<Action::OFK_Host>()
3166 ->getTriple()
3167 .normalize();
3168 CmdArgs.push_back("-aux-triple");
3169 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3170 }
3171
David L. Jonesf561aba2017-03-08 01:02:16 +00003172 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3173 Triple.getArch() == llvm::Triple::thumb)) {
3174 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3175 unsigned Version;
3176 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3177 if (Version < 7)
3178 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3179 << TripleStr;
3180 }
3181
3182 // Push all default warning arguments that are specific to
3183 // the given target. These come before user provided warning options
3184 // are provided.
3185 getToolChain().addClangWarningOptions(CmdArgs);
3186
3187 // Select the appropriate action.
3188 RewriteKind rewriteKind = RK_None;
3189
3190 if (isa<AnalyzeJobAction>(JA)) {
3191 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3192 CmdArgs.push_back("-analyze");
3193 } else if (isa<MigrateJobAction>(JA)) {
3194 CmdArgs.push_back("-migrate");
3195 } else if (isa<PreprocessJobAction>(JA)) {
3196 if (Output.getType() == types::TY_Dependencies)
3197 CmdArgs.push_back("-Eonly");
3198 else {
3199 CmdArgs.push_back("-E");
3200 if (Args.hasArg(options::OPT_rewrite_objc) &&
3201 !Args.hasArg(options::OPT_g_Group))
3202 CmdArgs.push_back("-P");
3203 }
3204 } else if (isa<AssembleJobAction>(JA)) {
3205 CmdArgs.push_back("-emit-obj");
3206
3207 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3208
3209 // Also ignore explicit -force_cpusubtype_ALL option.
3210 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3211 } else if (isa<PrecompileJobAction>(JA)) {
3212 // Use PCH if the user requested it.
3213 bool UsePCH = D.CCCUsePCH;
3214
3215 if (JA.getType() == types::TY_Nothing)
3216 CmdArgs.push_back("-fsyntax-only");
3217 else if (JA.getType() == types::TY_ModuleFile)
3218 CmdArgs.push_back("-emit-module-interface");
3219 else if (UsePCH)
3220 CmdArgs.push_back("-emit-pch");
3221 else
3222 CmdArgs.push_back("-emit-pth");
3223 } else if (isa<VerifyPCHJobAction>(JA)) {
3224 CmdArgs.push_back("-verify-pch");
3225 } else {
3226 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3227 "Invalid action for clang tool.");
3228 if (JA.getType() == types::TY_Nothing) {
3229 CmdArgs.push_back("-fsyntax-only");
3230 } else if (JA.getType() == types::TY_LLVM_IR ||
3231 JA.getType() == types::TY_LTO_IR) {
3232 CmdArgs.push_back("-emit-llvm");
3233 } else if (JA.getType() == types::TY_LLVM_BC ||
3234 JA.getType() == types::TY_LTO_BC) {
3235 CmdArgs.push_back("-emit-llvm-bc");
3236 } else if (JA.getType() == types::TY_PP_Asm) {
3237 CmdArgs.push_back("-S");
3238 } else if (JA.getType() == types::TY_AST) {
3239 CmdArgs.push_back("-emit-pch");
3240 } else if (JA.getType() == types::TY_ModuleFile) {
3241 CmdArgs.push_back("-module-file-info");
3242 } else if (JA.getType() == types::TY_RewrittenObjC) {
3243 CmdArgs.push_back("-rewrite-objc");
3244 rewriteKind = RK_NonFragile;
3245 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3246 CmdArgs.push_back("-rewrite-objc");
3247 rewriteKind = RK_Fragile;
3248 } else {
3249 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3250 }
3251
3252 // Preserve use-list order by default when emitting bitcode, so that
3253 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3254 // same result as running passes here. For LTO, we don't need to preserve
3255 // the use-list order, since serialization to bitcode is part of the flow.
3256 if (JA.getType() == types::TY_LLVM_BC)
3257 CmdArgs.push_back("-emit-llvm-uselists");
3258
Artem Belevichecb178b2018-03-21 22:22:59 +00003259 // Device-side jobs do not support LTO.
3260 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3261 JA.isDeviceOffloading(Action::OFK_Host));
3262
3263 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003264 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3265
Paul Robinsond23f2a82017-07-13 21:25:47 +00003266 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3267 // does not support LTO unit features (CFI, whole program vtable opt)
3268 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003269 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003270 D.getLTOMode() == LTOK_Full)
3271 CmdArgs.push_back("-flto-unit");
3272 }
3273 }
3274
3275 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3276 if (!types::isLLVMIR(Input.getType()))
3277 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3278 << "-x ir";
3279 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3280 }
3281
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003282 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003283 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3284
David L. Jonesf561aba2017-03-08 01:02:16 +00003285 // Embed-bitcode option.
3286 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3287 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3288 // Add flags implied by -fembed-bitcode.
3289 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3290 // Disable all llvm IR level optimizations.
3291 CmdArgs.push_back("-disable-llvm-passes");
3292 }
3293 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3294 CmdArgs.push_back("-fembed-bitcode=marker");
3295
3296 // We normally speed up the clang process a bit by skipping destructors at
3297 // exit, but when we're generating diagnostics we can rely on some of the
3298 // cleanup.
3299 if (!C.isForDiagnostics())
3300 CmdArgs.push_back("-disable-free");
3301
David L. Jonesf561aba2017-03-08 01:02:16 +00003302#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003303 const bool IsAssertBuild = false;
3304#else
3305 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003306#endif
3307
Eric Fiselier123c7492018-02-07 18:36:51 +00003308 // Disable the verification pass in -asserts builds.
3309 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003310 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003311
3312 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003313 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3314 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003315 CmdArgs.push_back("-discard-value-names");
3316
David L. Jonesf561aba2017-03-08 01:02:16 +00003317 // Set the main file name, so that debug info works even with
3318 // -save-temps.
3319 CmdArgs.push_back("-main-file-name");
3320 CmdArgs.push_back(getBaseInputName(Args, Input));
3321
3322 // Some flags which affect the language (via preprocessor
3323 // defines).
3324 if (Args.hasArg(options::OPT_static))
3325 CmdArgs.push_back("-static-define");
3326
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003327 if (isa<AnalyzeJobAction>(JA))
3328 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003329
3330 CheckCodeGenerationOptions(D, Args);
3331
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003332 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3333 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3334 if (FunctionAlignment) {
3335 CmdArgs.push_back("-function-alignment");
3336 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3337 }
3338
David L. Jonesf561aba2017-03-08 01:02:16 +00003339 llvm::Reloc::Model RelocationModel;
3340 unsigned PICLevel;
3341 bool IsPIE;
3342 std::tie(RelocationModel, PICLevel, IsPIE) =
3343 ParsePICArgs(getToolChain(), Args);
3344
3345 const char *RMName = RelocationModelName(RelocationModel);
3346
3347 if ((RelocationModel == llvm::Reloc::ROPI ||
3348 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3349 types::isCXX(Input.getType()) &&
3350 !Args.hasArg(options::OPT_fallow_unsupported))
3351 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3352
3353 if (RMName) {
3354 CmdArgs.push_back("-mrelocation-model");
3355 CmdArgs.push_back(RMName);
3356 }
3357 if (PICLevel > 0) {
3358 CmdArgs.push_back("-pic-level");
3359 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3360 if (IsPIE)
3361 CmdArgs.push_back("-pic-is-pie");
3362 }
3363
3364 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3365 CmdArgs.push_back("-meabi");
3366 CmdArgs.push_back(A->getValue());
3367 }
3368
3369 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003370 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3371 if (!getToolChain().isThreadModelSupported(A->getValue()))
3372 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3373 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003374 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003375 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003376 else
3377 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3378
3379 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3380
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003381 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3382 options::OPT_fno_merge_all_constants, false))
3383 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003384
3385 // LLVM Code Generator Options.
3386
3387 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3388 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3389 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3390 options::OPT_frewrite_map_file_EQ)) {
3391 StringRef Map = A->getValue();
3392 if (!llvm::sys::fs::exists(Map)) {
3393 D.Diag(diag::err_drv_no_such_file) << Map;
3394 } else {
3395 CmdArgs.push_back("-frewrite-map-file");
3396 CmdArgs.push_back(A->getValue());
3397 A->claim();
3398 }
3399 }
3400 }
3401
3402 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3403 StringRef v = A->getValue();
3404 CmdArgs.push_back("-mllvm");
3405 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3406 A->claim();
3407 }
3408
3409 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3410 true))
3411 CmdArgs.push_back("-fno-jump-tables");
3412
Dehao Chen5e97f232017-08-24 21:37:33 +00003413 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3414 options::OPT_fno_profile_sample_accurate, false))
3415 CmdArgs.push_back("-fprofile-sample-accurate");
3416
David L. Jonesf561aba2017-03-08 01:02:16 +00003417 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3418 options::OPT_fno_preserve_as_comments, true))
3419 CmdArgs.push_back("-fno-preserve-as-comments");
3420
3421 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3422 CmdArgs.push_back("-mregparm");
3423 CmdArgs.push_back(A->getValue());
3424 }
3425
3426 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3427 options::OPT_freg_struct_return)) {
3428 if (getToolChain().getArch() != llvm::Triple::x86) {
3429 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003430 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003431 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3432 CmdArgs.push_back("-fpcc-struct-return");
3433 } else {
3434 assert(A->getOption().matches(options::OPT_freg_struct_return));
3435 CmdArgs.push_back("-freg-struct-return");
3436 }
3437 }
3438
3439 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3440 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3441
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003442 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003443 CmdArgs.push_back("-mdisable-fp-elim");
3444 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3445 options::OPT_fno_zero_initialized_in_bss))
3446 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3447
3448 bool OFastEnabled = isOptimizationLevelFast(Args);
3449 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3450 // enabled. This alias option is being used to simplify the hasFlag logic.
3451 OptSpecifier StrictAliasingAliasOption =
3452 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3453 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3454 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003455 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003456 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3457 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3458 CmdArgs.push_back("-relaxed-aliasing");
3459 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3460 options::OPT_fno_struct_path_tbaa))
3461 CmdArgs.push_back("-no-struct-path-tbaa");
3462 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3463 false))
3464 CmdArgs.push_back("-fstrict-enums");
3465 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3466 true))
3467 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003468 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3469 options::OPT_fno_allow_editor_placeholders, false))
3470 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003471 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3472 options::OPT_fno_strict_vtable_pointers,
3473 false))
3474 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003475 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3476 options::OPT_fno_force_emit_vtables,
3477 false))
3478 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003479 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3480 options::OPT_fno_optimize_sibling_calls))
3481 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003482 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003483 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003484 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003485
Wei Mi9b3d6272017-10-16 16:50:27 +00003486 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3487 options::OPT_fno_fine_grained_bitfield_accesses);
3488
David L. Jonesf561aba2017-03-08 01:02:16 +00003489 // Handle segmented stacks.
3490 if (Args.hasArg(options::OPT_fsplit_stack))
3491 CmdArgs.push_back("-split-stacks");
3492
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003493 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003494
3495 // Decide whether to use verbose asm. Verbose assembly is the default on
3496 // toolchains which have the integrated assembler on by default.
3497 bool IsIntegratedAssemblerDefault =
3498 getToolChain().IsIntegratedAssemblerDefault();
3499 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3500 IsIntegratedAssemblerDefault) ||
3501 Args.hasArg(options::OPT_dA))
3502 CmdArgs.push_back("-masm-verbose");
3503
3504 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3505 IsIntegratedAssemblerDefault))
3506 CmdArgs.push_back("-no-integrated-as");
3507
3508 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3509 CmdArgs.push_back("-mdebug-pass");
3510 CmdArgs.push_back("Structure");
3511 }
3512 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3513 CmdArgs.push_back("-mdebug-pass");
3514 CmdArgs.push_back("Arguments");
3515 }
3516
3517 // Enable -mconstructor-aliases except on darwin, where we have to work around
3518 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3519 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003520 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003521 CmdArgs.push_back("-mconstructor-aliases");
3522
3523 // Darwin's kernel doesn't support guard variables; just die if we
3524 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003525 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003526 CmdArgs.push_back("-fforbid-guard-variables");
3527
3528 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3529 false)) {
3530 CmdArgs.push_back("-mms-bitfields");
3531 }
3532
3533 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3534 options::OPT_mno_pie_copy_relocations,
3535 false)) {
3536 CmdArgs.push_back("-mpie-copy-relocations");
3537 }
3538
Sriraman Tallam5c651482017-11-07 19:37:51 +00003539 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3540 CmdArgs.push_back("-fno-plt");
3541 }
3542
Vedant Kumardf502592017-09-12 22:51:53 +00003543 // -fhosted is default.
3544 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3545 // use Freestanding.
3546 bool Freestanding =
3547 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3548 KernelOrKext;
3549 if (Freestanding)
3550 CmdArgs.push_back("-ffreestanding");
3551
David L. Jonesf561aba2017-03-08 01:02:16 +00003552 // This is a coarse approximation of what llvm-gcc actually does, both
3553 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3554 // complicated ways.
3555 bool AsynchronousUnwindTables =
3556 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3557 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003558 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003559 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003560 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003561 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3562 AsynchronousUnwindTables))
3563 CmdArgs.push_back("-munwind-tables");
3564
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003565 getToolChain().addClangTargetOptions(Args, CmdArgs,
3566 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003567
3568 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3569 CmdArgs.push_back("-mlimit-float-precision");
3570 CmdArgs.push_back(A->getValue());
3571 }
3572
3573 // FIXME: Handle -mtune=.
3574 (void)Args.hasArg(options::OPT_mtune_EQ);
3575
3576 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3577 CmdArgs.push_back("-mcode-model");
3578 CmdArgs.push_back(A->getValue());
3579 }
3580
3581 // Add the target cpu
3582 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3583 if (!CPU.empty()) {
3584 CmdArgs.push_back("-target-cpu");
3585 CmdArgs.push_back(Args.MakeArgString(CPU));
3586 }
3587
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003588 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003589
David L. Jonesf561aba2017-03-08 01:02:16 +00003590 // These two are potentially updated by AddClangCLArgs.
3591 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3592 bool EmitCodeView = false;
3593
3594 // Add clang-cl arguments.
3595 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003596 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003597 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
Reid Kleckner54af3e72018-02-26 22:55:33 +00003598 else
3599 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
David L. Jonesf561aba2017-03-08 01:02:16 +00003600
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003601 const Arg *SplitDWARFArg = nullptr;
3602 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3603 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3604
3605 // Add the split debug info name to the command lines here so we
3606 // can propagate it to the backend.
3607 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3608 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3609 isa<BackendJobAction>(JA));
3610 const char *SplitDWARFOut;
3611 if (SplitDWARF) {
3612 CmdArgs.push_back("-split-dwarf-file");
3613 SplitDWARFOut = SplitDebugName(Args, Input);
3614 CmdArgs.push_back(SplitDWARFOut);
3615 }
3616
David L. Jonesf561aba2017-03-08 01:02:16 +00003617 // Pass the linker version in use.
3618 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3619 CmdArgs.push_back("-target-linker-version");
3620 CmdArgs.push_back(A->getValue());
3621 }
3622
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003623 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003624 CmdArgs.push_back("-momit-leaf-frame-pointer");
3625
3626 // Explicitly error on some things we know we don't support and can't just
3627 // ignore.
3628 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3629 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003630 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003631 getToolChain().getArch() == llvm::Triple::x86) {
3632 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3633 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3634 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3635 << Unsupported->getOption().getName();
3636 }
Eric Christopher758aad72017-03-21 22:06:18 +00003637 // The faltivec option has been superseded by the maltivec option.
3638 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3639 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3640 << Unsupported->getOption().getName()
3641 << "please use -maltivec and include altivec.h explicitly";
3642 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3643 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3644 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003645 }
3646
3647 Args.AddAllArgs(CmdArgs, options::OPT_v);
3648 Args.AddLastArg(CmdArgs, options::OPT_H);
3649 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3650 CmdArgs.push_back("-header-include-file");
3651 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3652 : "-");
3653 }
3654 Args.AddLastArg(CmdArgs, options::OPT_P);
3655 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3656
3657 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3658 CmdArgs.push_back("-diagnostic-log-file");
3659 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3660 : "-");
3661 }
3662
David L. Jonesf561aba2017-03-08 01:02:16 +00003663 bool UseSeparateSections = isUseSeparateSections(Triple);
3664
3665 if (Args.hasFlag(options::OPT_ffunction_sections,
3666 options::OPT_fno_function_sections, UseSeparateSections)) {
3667 CmdArgs.push_back("-ffunction-sections");
3668 }
3669
3670 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3671 UseSeparateSections)) {
3672 CmdArgs.push_back("-fdata-sections");
3673 }
3674
3675 if (!Args.hasFlag(options::OPT_funique_section_names,
3676 options::OPT_fno_unique_section_names, true))
3677 CmdArgs.push_back("-fno-unique-section-names");
3678
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003679 if (auto *A = Args.getLastArg(
3680 options::OPT_finstrument_functions,
3681 options::OPT_finstrument_functions_after_inlining,
3682 options::OPT_finstrument_function_entry_bare))
3683 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003684
Artem Belevichc30bcad2018-01-24 17:41:02 +00003685 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3686 // sampling, overhead of call arc collection is way too high and there's no
3687 // way to collect the output.
3688 if (!Triple.isNVPTX())
3689 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003690
Richard Smithf667ad52017-08-26 01:04:35 +00003691 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3692 ABICompatArg->render(Args, CmdArgs);
3693
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003694 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
3695 if (RawTriple.isPS4CPU()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003696 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003697 PS4cpu::addSanitizerArgs(getToolChain(), CmdArgs);
3698 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003699
3700 // Pass options for controlling the default header search paths.
3701 if (Args.hasArg(options::OPT_nostdinc)) {
3702 CmdArgs.push_back("-nostdsysteminc");
3703 CmdArgs.push_back("-nobuiltininc");
3704 } else {
3705 if (Args.hasArg(options::OPT_nostdlibinc))
3706 CmdArgs.push_back("-nostdsysteminc");
3707 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3708 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3709 }
3710
3711 // Pass the path to compiler resource files.
3712 CmdArgs.push_back("-resource-dir");
3713 CmdArgs.push_back(D.ResourceDir.c_str());
3714
3715 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3716
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003717 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003718
3719 // Add preprocessing options like -I, -D, etc. if we are using the
3720 // preprocessor.
3721 //
3722 // FIXME: Support -fpreprocessed
3723 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3724 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3725
3726 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3727 // that "The compiler can only warn and ignore the option if not recognized".
3728 // When building with ccache, it will pass -D options to clang even on
3729 // preprocessed inputs and configure concludes that -fPIC is not supported.
3730 Args.ClaimAllArgs(options::OPT_D);
3731
3732 // Manually translate -O4 to -O3; let clang reject others.
3733 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3734 if (A->getOption().matches(options::OPT_O4)) {
3735 CmdArgs.push_back("-O3");
3736 D.Diag(diag::warn_O4_is_O3);
3737 } else {
3738 A->render(Args, CmdArgs);
3739 }
3740 }
3741
3742 // Warn about ignored options to clang.
3743 for (const Arg *A :
3744 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3745 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3746 A->claim();
3747 }
3748
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003749 for (const Arg *A :
3750 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3751 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3752 A->claim();
3753 }
3754
David L. Jonesf561aba2017-03-08 01:02:16 +00003755 claimNoWarnArgs(Args);
3756
3757 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3758
3759 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3760 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3761 CmdArgs.push_back("-pedantic");
3762 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3763 Args.AddLastArg(CmdArgs, options::OPT_w);
3764
Leonard Chanf921d852018-06-04 16:07:52 +00003765 // Fixed point flags
3766 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
3767 /*Default=*/false))
3768 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
3769
David L. Jonesf561aba2017-03-08 01:02:16 +00003770 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3771 // (-ansi is equivalent to -std=c89 or -std=c++98).
3772 //
3773 // If a std is supplied, only add -trigraphs if it follows the
3774 // option.
3775 bool ImplyVCPPCXXVer = false;
3776 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3777 if (Std->getOption().matches(options::OPT_ansi))
3778 if (types::isCXX(InputType))
3779 CmdArgs.push_back("-std=c++98");
3780 else
3781 CmdArgs.push_back("-std=c89");
3782 else
3783 Std->render(Args, CmdArgs);
3784
3785 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3786 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3787 options::OPT_ftrigraphs,
3788 options::OPT_fno_trigraphs))
3789 if (A != Std)
3790 A->render(Args, CmdArgs);
3791 } else {
3792 // Honor -std-default.
3793 //
3794 // FIXME: Clang doesn't correctly handle -std= when the input language
3795 // doesn't match. For the time being just ignore this for C++ inputs;
3796 // eventually we want to do all the standard defaulting here instead of
3797 // splitting it between the driver and clang -cc1.
3798 if (!types::isCXX(InputType))
3799 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3800 /*Joined=*/true);
3801 else if (IsWindowsMSVC)
3802 ImplyVCPPCXXVer = true;
3803
3804 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3805 options::OPT_fno_trigraphs);
3806 }
3807
3808 // GCC's behavior for -Wwrite-strings is a bit strange:
3809 // * In C, this "warning flag" changes the types of string literals from
3810 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3811 // for the discarded qualifier.
3812 // * In C++, this is just a normal warning flag.
3813 //
3814 // Implementing this warning correctly in C is hard, so we follow GCC's
3815 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3816 // a non-const char* in C, rather than using this crude hack.
3817 if (!types::isCXX(InputType)) {
3818 // FIXME: This should behave just like a warning flag, and thus should also
3819 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3820 Arg *WriteStrings =
3821 Args.getLastArg(options::OPT_Wwrite_strings,
3822 options::OPT_Wno_write_strings, options::OPT_w);
3823 if (WriteStrings &&
3824 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3825 CmdArgs.push_back("-fconst-strings");
3826 }
3827
3828 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3829 // during C++ compilation, which it is by default. GCC keeps this define even
3830 // in the presence of '-w', match this behavior bug-for-bug.
3831 if (types::isCXX(InputType) &&
3832 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3833 true)) {
3834 CmdArgs.push_back("-fdeprecated-macro");
3835 }
3836
3837 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3838 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3839 if (Asm->getOption().matches(options::OPT_fasm))
3840 CmdArgs.push_back("-fgnu-keywords");
3841 else
3842 CmdArgs.push_back("-fno-gnu-keywords");
3843 }
3844
3845 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3846 CmdArgs.push_back("-fno-dwarf-directory-asm");
3847
3848 if (ShouldDisableAutolink(Args, getToolChain()))
3849 CmdArgs.push_back("-fno-autolink");
3850
3851 // Add in -fdebug-compilation-dir if necessary.
3852 addDebugCompDirArg(Args, CmdArgs);
3853
3854 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3855 StringRef Map = A->getValue();
3856 if (Map.find('=') == StringRef::npos)
3857 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3858 else
3859 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3860 A->claim();
3861 }
3862
3863 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3864 options::OPT_ftemplate_depth_EQ)) {
3865 CmdArgs.push_back("-ftemplate-depth");
3866 CmdArgs.push_back(A->getValue());
3867 }
3868
3869 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3870 CmdArgs.push_back("-foperator-arrow-depth");
3871 CmdArgs.push_back(A->getValue());
3872 }
3873
3874 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3875 CmdArgs.push_back("-fconstexpr-depth");
3876 CmdArgs.push_back(A->getValue());
3877 }
3878
3879 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3880 CmdArgs.push_back("-fconstexpr-steps");
3881 CmdArgs.push_back(A->getValue());
3882 }
3883
3884 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3885 CmdArgs.push_back("-fbracket-depth");
3886 CmdArgs.push_back(A->getValue());
3887 }
3888
3889 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3890 options::OPT_Wlarge_by_value_copy_def)) {
3891 if (A->getNumValues()) {
3892 StringRef bytes = A->getValue();
3893 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3894 } else
3895 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3896 }
3897
3898 if (Args.hasArg(options::OPT_relocatable_pch))
3899 CmdArgs.push_back("-relocatable-pch");
3900
3901 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3902 CmdArgs.push_back("-fconstant-string-class");
3903 CmdArgs.push_back(A->getValue());
3904 }
3905
3906 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3907 CmdArgs.push_back("-ftabstop");
3908 CmdArgs.push_back(A->getValue());
3909 }
3910
Sean Eveson5110d4f2018-01-08 13:42:26 +00003911 if (Args.hasFlag(options::OPT_fstack_size_section,
3912 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3913 CmdArgs.push_back("-fstack-size-section");
3914
David L. Jonesf561aba2017-03-08 01:02:16 +00003915 CmdArgs.push_back("-ferror-limit");
3916 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3917 CmdArgs.push_back(A->getValue());
3918 else
3919 CmdArgs.push_back("19");
3920
3921 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3922 CmdArgs.push_back("-fmacro-backtrace-limit");
3923 CmdArgs.push_back(A->getValue());
3924 }
3925
3926 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3927 CmdArgs.push_back("-ftemplate-backtrace-limit");
3928 CmdArgs.push_back(A->getValue());
3929 }
3930
3931 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3932 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3933 CmdArgs.push_back(A->getValue());
3934 }
3935
3936 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3937 CmdArgs.push_back("-fspell-checking-limit");
3938 CmdArgs.push_back(A->getValue());
3939 }
3940
3941 // Pass -fmessage-length=.
3942 CmdArgs.push_back("-fmessage-length");
3943 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3944 CmdArgs.push_back(A->getValue());
3945 } else {
3946 // If -fmessage-length=N was not specified, determine whether this is a
3947 // terminal and, if so, implicitly define -fmessage-length appropriately.
3948 unsigned N = llvm::sys::Process::StandardErrColumns();
3949 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3950 }
3951
3952 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3953 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3954 options::OPT_fvisibility_ms_compat)) {
3955 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3956 CmdArgs.push_back("-fvisibility");
3957 CmdArgs.push_back(A->getValue());
3958 } else {
3959 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3960 CmdArgs.push_back("-fvisibility");
3961 CmdArgs.push_back("hidden");
3962 CmdArgs.push_back("-ftype-visibility");
3963 CmdArgs.push_back("default");
3964 }
3965 }
3966
3967 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3968
3969 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3970
David L. Jonesf561aba2017-03-08 01:02:16 +00003971 // Forward -f (flag) options which we can pass directly.
3972 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3973 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3974 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00003975 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
3976 options::OPT_fno_emulated_tls);
3977
David L. Jonesf561aba2017-03-08 01:02:16 +00003978 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003979 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003980 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003981
David L. Jonesf561aba2017-03-08 01:02:16 +00003982 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3983 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3984
3985 // Forward flags for OpenMP. We don't do this if the current action is an
3986 // device offloading action other than OpenMP.
3987 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3988 options::OPT_fno_openmp, false) &&
3989 (JA.isDeviceOffloading(Action::OFK_None) ||
3990 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003991 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003992 case Driver::OMPRT_OMP:
3993 case Driver::OMPRT_IOMP5:
3994 // Clang can generate useful OpenMP code for these two runtime libraries.
3995 CmdArgs.push_back("-fopenmp");
3996
3997 // If no option regarding the use of TLS in OpenMP codegeneration is
3998 // given, decide a default based on the target. Otherwise rely on the
3999 // options and pass the right information to the frontend.
4000 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4001 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4002 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004003 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4004 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004005 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00004006
4007 // When in OpenMP offloading mode with NVPTX target, forward
4008 // cuda-mode flag
4009 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
4010 options::OPT_fno_openmp_cuda_mode);
David L. Jonesf561aba2017-03-08 01:02:16 +00004011 break;
4012 default:
4013 // By default, if Clang doesn't know how to generate useful OpenMP code
4014 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4015 // down to the actual compilation.
4016 // FIXME: It would be better to have a mode which *only* omits IR
4017 // generation based on the OpenMP support so that we get consistent
4018 // semantic analysis, etc.
4019 break;
4020 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004021 } else {
4022 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4023 options::OPT_fno_openmp_simd);
4024 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004025 }
4026
4027 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4028 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4029
Dean Michael Berris835832d2017-03-30 00:29:36 +00004030 const XRayArgs &XRay = getToolChain().getXRayArgs();
4031 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
4032
David L. Jonesf561aba2017-03-08 01:02:16 +00004033 if (getToolChain().SupportsProfiling())
4034 Args.AddLastArg(CmdArgs, options::OPT_pg);
4035
4036 if (getToolChain().SupportsProfiling())
4037 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4038
4039 // -flax-vector-conversions is default.
4040 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4041 options::OPT_fno_lax_vector_conversions))
4042 CmdArgs.push_back("-fno-lax-vector-conversions");
4043
4044 if (Args.getLastArg(options::OPT_fapple_kext) ||
4045 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4046 CmdArgs.push_back("-fapple-kext");
4047
4048 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4049 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4050 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4051 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4052 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4053
4054 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4055 CmdArgs.push_back("-ftrapv-handler");
4056 CmdArgs.push_back(A->getValue());
4057 }
4058
4059 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4060
4061 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4062 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4063 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4064 if (A->getOption().matches(options::OPT_fwrapv))
4065 CmdArgs.push_back("-fwrapv");
4066 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4067 options::OPT_fno_strict_overflow)) {
4068 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4069 CmdArgs.push_back("-fwrapv");
4070 }
4071
4072 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4073 options::OPT_fno_reroll_loops))
4074 if (A->getOption().matches(options::OPT_freroll_loops))
4075 CmdArgs.push_back("-freroll-loops");
4076
4077 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4078 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4079 options::OPT_fno_unroll_loops);
4080
4081 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4082
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004083 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004084
4085 // Translate -mstackrealign
4086 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4087 false))
4088 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4089
4090 if (Args.hasArg(options::OPT_mstack_alignment)) {
4091 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4092 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4093 }
4094
4095 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4096 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4097
4098 if (!Size.empty())
4099 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4100 else
4101 CmdArgs.push_back("-mstack-probe-size=0");
4102 }
4103
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004104 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4105 options::OPT_mno_stack_arg_probe, true))
4106 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4107
David L. Jonesf561aba2017-03-08 01:02:16 +00004108 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4109 options::OPT_mno_restrict_it)) {
4110 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004111 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004112 CmdArgs.push_back("-arm-restrict-it");
4113 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004114 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004115 CmdArgs.push_back("-arm-no-restrict-it");
4116 }
4117 } else if (Triple.isOSWindows() &&
4118 (Triple.getArch() == llvm::Triple::arm ||
4119 Triple.getArch() == llvm::Triple::thumb)) {
4120 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004121 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004122 CmdArgs.push_back("-arm-restrict-it");
4123 }
4124
4125 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004126 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004127
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004128 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4129 CmdArgs.push_back(
4130 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4131 }
4132
David L. Jonesf561aba2017-03-08 01:02:16 +00004133 // Forward -f options with positive and negative forms; we translate
4134 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004135 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004136 StringRef fname = A->getValue();
4137 if (!llvm::sys::fs::exists(fname))
4138 D.Diag(diag::err_drv_no_such_file) << fname;
4139 else
4140 A->render(Args, CmdArgs);
4141 }
4142
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004143 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004144
4145 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4146 options::OPT_fno_assume_sane_operator_new))
4147 CmdArgs.push_back("-fno-assume-sane-operator-new");
4148
4149 // -fblocks=0 is default.
4150 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4151 getToolChain().IsBlocksDefault()) ||
4152 (Args.hasArg(options::OPT_fgnu_runtime) &&
4153 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4154 !Args.hasArg(options::OPT_fno_blocks))) {
4155 CmdArgs.push_back("-fblocks");
4156
4157 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4158 !getToolChain().hasBlocksRuntime())
4159 CmdArgs.push_back("-fblocks-runtime-optional");
4160 }
4161
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004162 // -fencode-extended-block-signature=1 is default.
4163 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4164 CmdArgs.push_back("-fencode-extended-block-signature");
4165
David L. Jonesf561aba2017-03-08 01:02:16 +00004166 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4167 false) &&
4168 types::isCXX(InputType)) {
4169 CmdArgs.push_back("-fcoroutines-ts");
4170 }
4171
Aaron Ballman61736552017-10-21 20:28:58 +00004172 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4173 options::OPT_fno_double_square_bracket_attributes);
4174
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004175 bool HaveModules = false;
4176 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004177
4178 // -faccess-control is default.
4179 if (Args.hasFlag(options::OPT_fno_access_control,
4180 options::OPT_faccess_control, false))
4181 CmdArgs.push_back("-fno-access-control");
4182
4183 // -felide-constructors is the default.
4184 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4185 options::OPT_felide_constructors, false))
4186 CmdArgs.push_back("-fno-elide-constructors");
4187
4188 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4189
4190 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004191 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004192 CmdArgs.push_back("-fno-rtti");
4193
4194 // -fshort-enums=0 is default for all architectures except Hexagon.
4195 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4196 getToolChain().getArch() == llvm::Triple::hexagon))
4197 CmdArgs.push_back("-fshort-enums");
4198
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004199 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004200
4201 // -fuse-cxa-atexit is default.
4202 if (!Args.hasFlag(
4203 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004204 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004205 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004206 getToolChain().getArch() != llvm::Triple::hexagon &&
4207 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004208 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4209 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004210 KernelOrKext)
4211 CmdArgs.push_back("-fno-use-cxa-atexit");
4212
Akira Hatanaka617e2612018-04-17 18:41:52 +00004213 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4214 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004215 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004216 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4217
David L. Jonesf561aba2017-03-08 01:02:16 +00004218 // -fms-extensions=0 is default.
4219 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4220 IsWindowsMSVC))
4221 CmdArgs.push_back("-fms-extensions");
4222
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004223 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004224 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004225 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004226 CmdArgs.push_back("-fuse-line-directives");
4227
4228 // -fms-compatibility=0 is default.
4229 if (Args.hasFlag(options::OPT_fms_compatibility,
4230 options::OPT_fno_ms_compatibility,
4231 (IsWindowsMSVC &&
4232 Args.hasFlag(options::OPT_fms_extensions,
4233 options::OPT_fno_ms_extensions, true))))
4234 CmdArgs.push_back("-fms-compatibility");
4235
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004236 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004237 if (!MSVT.empty())
4238 CmdArgs.push_back(
4239 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4240
4241 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4242 if (ImplyVCPPCXXVer) {
4243 StringRef LanguageStandard;
4244 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4245 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4246 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004247 .Case("c++17", "-std=c++17")
4248 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004249 .Default("");
4250 if (LanguageStandard.empty())
4251 D.Diag(clang::diag::warn_drv_unused_argument)
4252 << StdArg->getAsString(Args);
4253 }
4254
4255 if (LanguageStandard.empty()) {
4256 if (IsMSVC2015Compatible)
4257 LanguageStandard = "-std=c++14";
4258 else
4259 LanguageStandard = "-std=c++11";
4260 }
4261
4262 CmdArgs.push_back(LanguageStandard.data());
4263 }
4264
4265 // -fno-borland-extensions is default.
4266 if (Args.hasFlag(options::OPT_fborland_extensions,
4267 options::OPT_fno_borland_extensions, false))
4268 CmdArgs.push_back("-fborland-extensions");
4269
4270 // -fno-declspec is default, except for PS4.
4271 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004272 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004273 CmdArgs.push_back("-fdeclspec");
4274 else if (Args.hasArg(options::OPT_fno_declspec))
4275 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4276
4277 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4278 // than 19.
4279 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4280 options::OPT_fno_threadsafe_statics,
4281 !IsWindowsMSVC || IsMSVC2015Compatible))
4282 CmdArgs.push_back("-fno-threadsafe-statics");
4283
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004284 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004285 // Many old Windows SDK versions require this to parse.
4286 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4287 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004288 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4289 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4290 CmdArgs.push_back("-fdelayed-template-parsing");
4291
4292 // -fgnu-keywords default varies depending on language; only pass if
4293 // specified.
4294 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4295 options::OPT_fno_gnu_keywords))
4296 A->render(Args, CmdArgs);
4297
4298 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4299 false))
4300 CmdArgs.push_back("-fgnu89-inline");
4301
4302 if (Args.hasArg(options::OPT_fno_inline))
4303 CmdArgs.push_back("-fno-inline");
4304
4305 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4306 options::OPT_finline_hint_functions,
4307 options::OPT_fno_inline_functions))
4308 InlineArg->render(Args, CmdArgs);
4309
4310 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4311 options::OPT_fno_experimental_new_pass_manager);
4312
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004313 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4314 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4315 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004316
4317 if (Args.hasFlag(options::OPT_fapplication_extension,
4318 options::OPT_fno_application_extension, false))
4319 CmdArgs.push_back("-fapplication-extension");
4320
4321 // Handle GCC-style exception args.
4322 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004323 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004324 CmdArgs);
4325
Martell Malonec950c652017-11-29 07:25:12 +00004326 // Handle exception personalities
4327 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4328 options::OPT_fseh_exceptions,
4329 options::OPT_fdwarf_exceptions);
4330 if (A) {
4331 const Option &Opt = A->getOption();
4332 if (Opt.matches(options::OPT_fsjlj_exceptions))
4333 CmdArgs.push_back("-fsjlj-exceptions");
4334 if (Opt.matches(options::OPT_fseh_exceptions))
4335 CmdArgs.push_back("-fseh-exceptions");
4336 if (Opt.matches(options::OPT_fdwarf_exceptions))
4337 CmdArgs.push_back("-fdwarf-exceptions");
4338 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004339 switch (getToolChain().GetExceptionModel(Args)) {
4340 default:
4341 break;
4342 case llvm::ExceptionHandling::DwarfCFI:
4343 CmdArgs.push_back("-fdwarf-exceptions");
4344 break;
4345 case llvm::ExceptionHandling::SjLj:
4346 CmdArgs.push_back("-fsjlj-exceptions");
4347 break;
4348 case llvm::ExceptionHandling::WinEH:
4349 CmdArgs.push_back("-fseh-exceptions");
4350 break;
Martell Malonec950c652017-11-29 07:25:12 +00004351 }
4352 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004353
4354 // C++ "sane" operator new.
4355 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4356 options::OPT_fno_assume_sane_operator_new))
4357 CmdArgs.push_back("-fno-assume-sane-operator-new");
4358
4359 // -frelaxed-template-template-args is off by default, as it is a severe
4360 // breaking change until a corresponding change to template partial ordering
4361 // is provided.
4362 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4363 options::OPT_fno_relaxed_template_template_args, false))
4364 CmdArgs.push_back("-frelaxed-template-template-args");
4365
4366 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4367 // most platforms.
4368 if (Args.hasFlag(options::OPT_fsized_deallocation,
4369 options::OPT_fno_sized_deallocation, false))
4370 CmdArgs.push_back("-fsized-deallocation");
4371
4372 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4373 // by default.
4374 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4375 options::OPT_fno_aligned_allocation,
4376 options::OPT_faligned_new_EQ)) {
4377 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4378 CmdArgs.push_back("-fno-aligned-allocation");
4379 else
4380 CmdArgs.push_back("-faligned-allocation");
4381 }
4382
4383 // The default new alignment can be specified using a dedicated option or via
4384 // a GCC-compatible option that also turns on aligned allocation.
4385 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4386 options::OPT_faligned_new_EQ))
4387 CmdArgs.push_back(
4388 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4389
4390 // -fconstant-cfstrings is default, and may be subject to argument translation
4391 // on Darwin.
4392 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4393 options::OPT_fno_constant_cfstrings) ||
4394 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4395 options::OPT_mno_constant_cfstrings))
4396 CmdArgs.push_back("-fno-constant-cfstrings");
4397
David L. Jonesf561aba2017-03-08 01:02:16 +00004398 // -fno-pascal-strings is default, only pass non-default.
4399 if (Args.hasFlag(options::OPT_fpascal_strings,
4400 options::OPT_fno_pascal_strings, false))
4401 CmdArgs.push_back("-fpascal-strings");
4402
4403 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4404 // -fno-pack-struct doesn't apply to -fpack-struct=.
4405 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4406 std::string PackStructStr = "-fpack-struct=";
4407 PackStructStr += A->getValue();
4408 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4409 } else if (Args.hasFlag(options::OPT_fpack_struct,
4410 options::OPT_fno_pack_struct, false)) {
4411 CmdArgs.push_back("-fpack-struct=1");
4412 }
4413
4414 // Handle -fmax-type-align=N and -fno-type-align
4415 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4416 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4417 if (!SkipMaxTypeAlign) {
4418 std::string MaxTypeAlignStr = "-fmax-type-align=";
4419 MaxTypeAlignStr += A->getValue();
4420 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4421 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004422 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004423 if (!SkipMaxTypeAlign) {
4424 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4425 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4426 }
4427 }
4428
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004429 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4430 CmdArgs.push_back("-Qn");
4431
David L. Jonesf561aba2017-03-08 01:02:16 +00004432 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004433 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004434 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4435 !NoCommonDefault))
4436 CmdArgs.push_back("-fno-common");
4437
4438 // -fsigned-bitfields is default, and clang doesn't yet support
4439 // -funsigned-bitfields.
4440 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4441 options::OPT_funsigned_bitfields))
4442 D.Diag(diag::warn_drv_clang_unsupported)
4443 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4444
4445 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4446 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4447 D.Diag(diag::err_drv_clang_unsupported)
4448 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4449
4450 // -finput_charset=UTF-8 is default. Reject others
4451 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4452 StringRef value = inputCharset->getValue();
4453 if (!value.equals_lower("utf-8"))
4454 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4455 << value;
4456 }
4457
4458 // -fexec_charset=UTF-8 is default. Reject others
4459 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4460 StringRef value = execCharset->getValue();
4461 if (!value.equals_lower("utf-8"))
4462 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4463 << value;
4464 }
4465
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004466 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004467
4468 // -fno-asm-blocks is default.
4469 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4470 false))
4471 CmdArgs.push_back("-fasm-blocks");
4472
4473 // -fgnu-inline-asm is default.
4474 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4475 options::OPT_fno_gnu_inline_asm, true))
4476 CmdArgs.push_back("-fno-gnu-inline-asm");
4477
4478 // Enable vectorization per default according to the optimization level
4479 // selected. For optimization levels that want vectorization we use the alias
4480 // option to simplify the hasFlag logic.
4481 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4482 OptSpecifier VectorizeAliasOption =
4483 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4484 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4485 options::OPT_fno_vectorize, EnableVec))
4486 CmdArgs.push_back("-vectorize-loops");
4487
4488 // -fslp-vectorize is enabled based on the optimization level selected.
4489 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4490 OptSpecifier SLPVectAliasOption =
4491 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4492 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4493 options::OPT_fno_slp_vectorize, EnableSLPVec))
4494 CmdArgs.push_back("-vectorize-slp");
4495
Craig Topper9a724aa2017-12-11 21:09:19 +00004496 ParseMPreferVectorWidth(D, Args, CmdArgs);
4497
David L. Jonesf561aba2017-03-08 01:02:16 +00004498 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4499 A->render(Args, CmdArgs);
4500
4501 if (Arg *A = Args.getLastArg(
4502 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4503 A->render(Args, CmdArgs);
4504
4505 // -fdollars-in-identifiers default varies depending on platform and
4506 // language; only pass if specified.
4507 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4508 options::OPT_fno_dollars_in_identifiers)) {
4509 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4510 CmdArgs.push_back("-fdollars-in-identifiers");
4511 else
4512 CmdArgs.push_back("-fno-dollars-in-identifiers");
4513 }
4514
4515 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4516 // practical purposes.
4517 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4518 options::OPT_fno_unit_at_a_time)) {
4519 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4520 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4521 }
4522
4523 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4524 options::OPT_fno_apple_pragma_pack, false))
4525 CmdArgs.push_back("-fapple-pragma-pack");
4526
David L. Jonesf561aba2017-03-08 01:02:16 +00004527 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004528 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004529 options::OPT_fno_save_optimization_record, false)) {
4530 CmdArgs.push_back("-opt-record-file");
4531
4532 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4533 if (A) {
4534 CmdArgs.push_back(A->getValue());
4535 } else {
4536 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004537
4538 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4539 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4540 F = FinalOutput->getValue();
4541 }
4542
4543 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004544 // Use the input filename.
4545 F = llvm::sys::path::stem(Input.getBaseInput());
4546
4547 // If we're compiling for an offload architecture (i.e. a CUDA device),
4548 // we need to make the file name for the device compilation different
4549 // from the host compilation.
4550 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4551 !JA.isDeviceOffloading(Action::OFK_Host)) {
4552 llvm::sys::path::replace_extension(F, "");
4553 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4554 Triple.normalize());
4555 F += "-";
4556 F += JA.getOffloadingArch();
4557 }
4558 }
4559
4560 llvm::sys::path::replace_extension(F, "opt.yaml");
4561 CmdArgs.push_back(Args.MakeArgString(F));
4562 }
4563 }
4564
Richard Smith86a3ef52017-06-09 21:24:02 +00004565 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4566 options::OPT_fno_rewrite_imports, false);
4567 if (RewriteImports)
4568 CmdArgs.push_back("-frewrite-imports");
4569
David L. Jonesf561aba2017-03-08 01:02:16 +00004570 // Enable rewrite includes if the user's asked for it or if we're generating
4571 // diagnostics.
4572 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4573 // nice to enable this when doing a crashdump for modules as well.
4574 if (Args.hasFlag(options::OPT_frewrite_includes,
4575 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004576 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004577 CmdArgs.push_back("-frewrite-includes");
4578
4579 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4580 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4581 options::OPT_traditional_cpp)) {
4582 if (isa<PreprocessJobAction>(JA))
4583 CmdArgs.push_back("-traditional-cpp");
4584 else
4585 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4586 }
4587
4588 Args.AddLastArg(CmdArgs, options::OPT_dM);
4589 Args.AddLastArg(CmdArgs, options::OPT_dD);
4590
4591 // Handle serialized diagnostics.
4592 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4593 CmdArgs.push_back("-serialize-diagnostic-file");
4594 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4595 }
4596
4597 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4598 CmdArgs.push_back("-fretain-comments-from-system-headers");
4599
4600 // Forward -fcomment-block-commands to -cc1.
4601 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4602 // Forward -fparse-all-comments to -cc1.
4603 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4604
4605 // Turn -fplugin=name.so into -load name.so
4606 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4607 CmdArgs.push_back("-load");
4608 CmdArgs.push_back(A->getValue());
4609 A->claim();
4610 }
4611
4612 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004613 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4614 if (!StatsFile.empty())
4615 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004616
4617 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4618 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004619 // -finclude-default-header flag is for preprocessor,
4620 // do not pass it to other cc1 commands when save-temps is enabled
4621 if (C.getDriver().isSaveTempsEnabled() &&
4622 !isa<PreprocessJobAction>(JA)) {
4623 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4624 Arg->claim();
4625 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4626 CmdArgs.push_back(Arg->getValue());
4627 }
4628 }
4629 else {
4630 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4631 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004632 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4633 A->claim();
4634
4635 // We translate this by hand to the -cc1 argument, since nightly test uses
4636 // it and developers have been trained to spell it with -mllvm. Both
4637 // spellings are now deprecated and should be removed.
4638 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4639 CmdArgs.push_back("-disable-llvm-optzns");
4640 } else {
4641 A->render(Args, CmdArgs);
4642 }
4643 }
4644
4645 // With -save-temps, we want to save the unoptimized bitcode output from the
4646 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4647 // by the frontend.
4648 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4649 // has slightly different breakdown between stages.
4650 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4651 // pristine IR generated by the frontend. Ideally, a new compile action should
4652 // be added so both IR can be captured.
4653 if (C.getDriver().isSaveTempsEnabled() &&
4654 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4655 isa<CompileJobAction>(JA))
4656 CmdArgs.push_back("-disable-llvm-passes");
4657
4658 if (Output.getType() == types::TY_Dependencies) {
4659 // Handled with other dependency code.
4660 } else if (Output.isFilename()) {
4661 CmdArgs.push_back("-o");
4662 CmdArgs.push_back(Output.getFilename());
4663 } else {
4664 assert(Output.isNothing() && "Invalid output.");
4665 }
4666
4667 addDashXForInput(Args, Input, CmdArgs);
4668
4669 if (Input.isFilename())
4670 CmdArgs.push_back(Input.getFilename());
4671 else
4672 Input.getInputArg().renderAsInput(Args, CmdArgs);
4673
4674 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4675
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004676 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004677
4678 // Optionally embed the -cc1 level arguments into the debug info, for build
4679 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004680 // Also record command line arguments into the debug info if
4681 // -grecord-gcc-switches options is set on.
4682 // By default, -gno-record-gcc-switches is set on and no recording.
4683 if (getToolChain().UseDwarfDebugFlags() ||
4684 Args.hasFlag(options::OPT_grecord_gcc_switches,
4685 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004686 ArgStringList OriginalArgs;
4687 for (const auto &Arg : Args)
4688 Arg->render(Args, OriginalArgs);
4689
4690 SmallString<256> Flags;
4691 Flags += Exec;
4692 for (const char *OriginalArg : OriginalArgs) {
4693 SmallString<128> EscapedArg;
4694 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4695 Flags += " ";
4696 Flags += EscapedArg;
4697 }
4698 CmdArgs.push_back("-dwarf-debug-flags");
4699 CmdArgs.push_back(Args.MakeArgString(Flags));
4700 }
4701
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004702 if (IsCuda) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004703 // Host-side cuda compilation receives all device-side outputs in a single
4704 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004705 if (Inputs.size() > 1) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004706 assert(Inputs.size() == 2 && "More than one GPU binary!");
4707 CmdArgs.push_back("-fcuda-include-gpubinary");
4708 CmdArgs.push_back(Inputs[1].getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00004709 }
4710
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004711 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4712 CmdArgs.push_back("-fcuda-rdc");
Artem Belevich679dafe2018-05-09 23:10:09 +00004713 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4714 options::OPT_fno_cuda_short_ptr, false))
4715 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004716 }
4717
David L. Jonesf561aba2017-03-08 01:02:16 +00004718 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4719 // to specify the result of the compile phase on the host, so the meaningful
4720 // device declarations can be identified. Also, -fopenmp-is-device is passed
4721 // along to tell the frontend that it is generating code for a device, so that
4722 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004723 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004724 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004725 if (Inputs.size() == 2) {
4726 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4727 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4728 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004729 }
4730
4731 // For all the host OpenMP offloading compile jobs we need to pass the targets
4732 // information using -fopenmp-targets= option.
4733 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4734 SmallString<128> TargetInfo("-fopenmp-targets=");
4735
4736 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4737 assert(Tgts && Tgts->getNumValues() &&
4738 "OpenMP offloading has to have targets specified.");
4739 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4740 if (i)
4741 TargetInfo += ',';
4742 // We need to get the string from the triple because it may be not exactly
4743 // the same as the one we get directly from the arguments.
4744 llvm::Triple T(Tgts->getValue(i));
4745 TargetInfo += T.getTriple();
4746 }
4747 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4748 }
4749
4750 bool WholeProgramVTables =
4751 Args.hasFlag(options::OPT_fwhole_program_vtables,
4752 options::OPT_fno_whole_program_vtables, false);
4753 if (WholeProgramVTables) {
4754 if (!D.isUsingLTO())
4755 D.Diag(diag::err_drv_argument_only_allowed_with)
4756 << "-fwhole-program-vtables"
4757 << "-flto";
4758 CmdArgs.push_back("-fwhole-program-vtables");
4759 }
4760
Amara Emerson4ee9f822018-01-26 00:27:22 +00004761 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4762 options::OPT_fno_experimental_isel)) {
4763 CmdArgs.push_back("-mllvm");
4764 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4765 CmdArgs.push_back("-global-isel=1");
4766
4767 // GISel is on by default on AArch64 -O0, so don't bother adding
4768 // the fallback remarks for it. Other combinations will add a warning of
4769 // some kind.
4770 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4771 bool IsOptLevelSupported = false;
4772
4773 Arg *A = Args.getLastArg(options::OPT_O_Group);
4774 if (Triple.getArch() == llvm::Triple::aarch64) {
4775 if (!A || A->getOption().matches(options::OPT_O0))
4776 IsOptLevelSupported = true;
4777 }
4778 if (!IsArchSupported || !IsOptLevelSupported) {
4779 CmdArgs.push_back("-mllvm");
4780 CmdArgs.push_back("-global-isel-abort=2");
4781
4782 if (!IsArchSupported)
4783 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4784 else
4785 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4786 }
4787 } else {
4788 CmdArgs.push_back("-global-isel=0");
4789 }
4790 }
4791
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00004792 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4793 options::OPT_fno_force_enable_int128)) {
4794 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4795 CmdArgs.push_back("-fforce-enable-int128");
4796 }
4797
Peter Collingbourne54d13b42018-05-30 03:40:04 +00004798 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
4799 options::OPT_fno_complete_member_pointers, false))
4800 CmdArgs.push_back("-fcomplete-member-pointers");
4801
David L. Jonesf561aba2017-03-08 01:02:16 +00004802 // Finally add the compile command to the compilation.
4803 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4804 Output.getType() == types::TY_Object &&
4805 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4806 auto CLCommand =
4807 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4808 C.addCommand(llvm::make_unique<FallbackCommand>(
4809 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4810 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4811 isa<PrecompileJobAction>(JA)) {
4812 // In /fallback builds, run the main compilation even if the pch generation
4813 // fails, so that the main compilation's fallback to cl.exe runs.
4814 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4815 CmdArgs, Inputs));
4816 } else {
4817 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4818 }
4819
David L. Jonesf561aba2017-03-08 01:02:16 +00004820 if (Arg *A = Args.getLastArg(options::OPT_pg))
4821 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4822 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4823 << A->getAsString(Args);
4824
4825 // Claim some arguments which clang supports automatically.
4826
4827 // -fpch-preprocess is used with gcc to add a special marker in the output to
4828 // include the PCH file. Clang's PTH solution is completely transparent, so we
4829 // do not need to deal with it at all.
4830 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4831
4832 // Claim some arguments which clang doesn't support, but we don't
4833 // care to warn the user about.
4834 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4835 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4836
4837 // Disable warnings for clang -E -emit-llvm foo.c
4838 Args.ClaimAllArgs(options::OPT_emit_llvm);
4839}
4840
4841Clang::Clang(const ToolChain &TC)
4842 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4843 // as it is for other tools. Some operations on a Tool actually test
4844 // whether that tool is Clang based on the Tool's Name as a string.
4845 : Tool("clang", "clang frontend", TC, RF_Full) {}
4846
4847Clang::~Clang() {}
4848
4849/// Add options related to the Objective-C runtime/ABI.
4850///
4851/// Returns true if the runtime is non-fragile.
4852ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4853 ArgStringList &cmdArgs,
4854 RewriteKind rewriteKind) const {
4855 // Look for the controlling runtime option.
4856 Arg *runtimeArg =
4857 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4858 options::OPT_fobjc_runtime_EQ);
4859
4860 // Just forward -fobjc-runtime= to the frontend. This supercedes
4861 // options about fragility.
4862 if (runtimeArg &&
4863 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4864 ObjCRuntime runtime;
4865 StringRef value = runtimeArg->getValue();
4866 if (runtime.tryParse(value)) {
4867 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4868 << value;
4869 }
David Chisnall404bbcb2018-05-22 10:13:06 +00004870 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
4871 (runtime.getVersion() >= VersionTuple(2, 0)))
4872 if (!getToolChain().getTriple().isOSBinFormatELF()) {
4873 getToolChain().getDriver().Diag(
4874 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
4875 << runtime.getVersion().getMajor();
4876 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004877
4878 runtimeArg->render(args, cmdArgs);
4879 return runtime;
4880 }
4881
4882 // Otherwise, we'll need the ABI "version". Version numbers are
4883 // slightly confusing for historical reasons:
4884 // 1 - Traditional "fragile" ABI
4885 // 2 - Non-fragile ABI, version 1
4886 // 3 - Non-fragile ABI, version 2
4887 unsigned objcABIVersion = 1;
4888 // If -fobjc-abi-version= is present, use that to set the version.
4889 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4890 StringRef value = abiArg->getValue();
4891 if (value == "1")
4892 objcABIVersion = 1;
4893 else if (value == "2")
4894 objcABIVersion = 2;
4895 else if (value == "3")
4896 objcABIVersion = 3;
4897 else
4898 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4899 } else {
4900 // Otherwise, determine if we are using the non-fragile ABI.
4901 bool nonFragileABIIsDefault =
4902 (rewriteKind == RK_NonFragile ||
4903 (rewriteKind == RK_None &&
4904 getToolChain().IsObjCNonFragileABIDefault()));
4905 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4906 options::OPT_fno_objc_nonfragile_abi,
4907 nonFragileABIIsDefault)) {
4908// Determine the non-fragile ABI version to use.
4909#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4910 unsigned nonFragileABIVersion = 1;
4911#else
4912 unsigned nonFragileABIVersion = 2;
4913#endif
4914
4915 if (Arg *abiArg =
4916 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4917 StringRef value = abiArg->getValue();
4918 if (value == "1")
4919 nonFragileABIVersion = 1;
4920 else if (value == "2")
4921 nonFragileABIVersion = 2;
4922 else
4923 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4924 << value;
4925 }
4926
4927 objcABIVersion = 1 + nonFragileABIVersion;
4928 } else {
4929 objcABIVersion = 1;
4930 }
4931 }
4932
4933 // We don't actually care about the ABI version other than whether
4934 // it's non-fragile.
4935 bool isNonFragile = objcABIVersion != 1;
4936
4937 // If we have no runtime argument, ask the toolchain for its default runtime.
4938 // However, the rewriter only really supports the Mac runtime, so assume that.
4939 ObjCRuntime runtime;
4940 if (!runtimeArg) {
4941 switch (rewriteKind) {
4942 case RK_None:
4943 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4944 break;
4945 case RK_Fragile:
4946 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4947 break;
4948 case RK_NonFragile:
4949 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4950 break;
4951 }
4952
4953 // -fnext-runtime
4954 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4955 // On Darwin, make this use the default behavior for the toolchain.
4956 if (getToolChain().getTriple().isOSDarwin()) {
4957 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4958
4959 // Otherwise, build for a generic macosx port.
4960 } else {
4961 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4962 }
4963
4964 // -fgnu-runtime
4965 } else {
4966 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4967 // Legacy behaviour is to target the gnustep runtime if we are in
4968 // non-fragile mode or the GCC runtime in fragile mode.
4969 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00004970 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00004971 else
4972 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4973 }
4974
4975 cmdArgs.push_back(
4976 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4977 return runtime;
4978}
4979
4980static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4981 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4982 I += HaveDash;
4983 return !HaveDash;
4984}
4985
4986namespace {
4987struct EHFlags {
4988 bool Synch = false;
4989 bool Asynch = false;
4990 bool NoUnwindC = false;
4991};
4992} // end anonymous namespace
4993
4994/// /EH controls whether to run destructor cleanups when exceptions are
4995/// thrown. There are three modifiers:
4996/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4997/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4998/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4999/// - c: Assume that extern "C" functions are implicitly nounwind.
5000/// The default is /EHs-c-, meaning cleanups are disabled.
5001static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5002 EHFlags EH;
5003
5004 std::vector<std::string> EHArgs =
5005 Args.getAllArgValues(options::OPT__SLASH_EH);
5006 for (auto EHVal : EHArgs) {
5007 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5008 switch (EHVal[I]) {
5009 case 'a':
5010 EH.Asynch = maybeConsumeDash(EHVal, I);
5011 if (EH.Asynch)
5012 EH.Synch = false;
5013 continue;
5014 case 'c':
5015 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5016 continue;
5017 case 's':
5018 EH.Synch = maybeConsumeDash(EHVal, I);
5019 if (EH.Synch)
5020 EH.Asynch = false;
5021 continue;
5022 default:
5023 break;
5024 }
5025 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5026 break;
5027 }
5028 }
5029 // The /GX, /GX- flags are only processed if there are not /EH flags.
5030 // The default is that /GX is not specified.
5031 if (EHArgs.empty() &&
5032 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5033 /*default=*/false)) {
5034 EH.Synch = true;
5035 EH.NoUnwindC = true;
5036 }
5037
5038 return EH;
5039}
5040
5041void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5042 ArgStringList &CmdArgs,
5043 codegenoptions::DebugInfoKind *DebugInfoKind,
5044 bool *EmitCodeView) const {
5045 unsigned RTOptionID = options::OPT__SLASH_MT;
5046
5047 if (Args.hasArg(options::OPT__SLASH_LDd))
5048 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5049 // but defining _DEBUG is sticky.
5050 RTOptionID = options::OPT__SLASH_MTd;
5051
5052 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5053 RTOptionID = A->getOption().getID();
5054
5055 StringRef FlagForCRT;
5056 switch (RTOptionID) {
5057 case options::OPT__SLASH_MD:
5058 if (Args.hasArg(options::OPT__SLASH_LDd))
5059 CmdArgs.push_back("-D_DEBUG");
5060 CmdArgs.push_back("-D_MT");
5061 CmdArgs.push_back("-D_DLL");
5062 FlagForCRT = "--dependent-lib=msvcrt";
5063 break;
5064 case options::OPT__SLASH_MDd:
5065 CmdArgs.push_back("-D_DEBUG");
5066 CmdArgs.push_back("-D_MT");
5067 CmdArgs.push_back("-D_DLL");
5068 FlagForCRT = "--dependent-lib=msvcrtd";
5069 break;
5070 case options::OPT__SLASH_MT:
5071 if (Args.hasArg(options::OPT__SLASH_LDd))
5072 CmdArgs.push_back("-D_DEBUG");
5073 CmdArgs.push_back("-D_MT");
5074 CmdArgs.push_back("-flto-visibility-public-std");
5075 FlagForCRT = "--dependent-lib=libcmt";
5076 break;
5077 case options::OPT__SLASH_MTd:
5078 CmdArgs.push_back("-D_DEBUG");
5079 CmdArgs.push_back("-D_MT");
5080 CmdArgs.push_back("-flto-visibility-public-std");
5081 FlagForCRT = "--dependent-lib=libcmtd";
5082 break;
5083 default:
5084 llvm_unreachable("Unexpected option ID.");
5085 }
5086
5087 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5088 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5089 } else {
5090 CmdArgs.push_back(FlagForCRT.data());
5091
5092 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5093 // users want. The /Za flag to cl.exe turns this off, but it's not
5094 // implemented in clang.
5095 CmdArgs.push_back("--dependent-lib=oldnames");
5096 }
5097
Erich Keane425f48d2018-05-04 15:58:31 +00005098 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5099 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005100
5101 // This controls whether or not we emit RTTI data for polymorphic types.
5102 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5103 /*default=*/false))
5104 CmdArgs.push_back("-fno-rtti-data");
5105
5106 // This controls whether or not we emit stack-protector instrumentation.
5107 // In MSVC, Buffer Security Check (/GS) is on by default.
5108 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5109 /*default=*/true)) {
5110 CmdArgs.push_back("-stack-protector");
5111 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5112 }
5113
5114 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5115 if (Arg *DebugInfoArg =
5116 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5117 options::OPT_gline_tables_only)) {
5118 *EmitCodeView = true;
5119 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5120 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5121 else
5122 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5123 CmdArgs.push_back("-gcodeview");
5124 } else {
5125 *EmitCodeView = false;
5126 }
5127
5128 const Driver &D = getToolChain().getDriver();
5129 EHFlags EH = parseClangCLEHFlags(D, Args);
5130 if (EH.Synch || EH.Asynch) {
5131 if (types::isCXX(InputType))
5132 CmdArgs.push_back("-fcxx-exceptions");
5133 CmdArgs.push_back("-fexceptions");
5134 }
5135 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5136 CmdArgs.push_back("-fexternc-nounwind");
5137
5138 // /EP should expand to -E -P.
5139 if (Args.hasArg(options::OPT__SLASH_EP)) {
5140 CmdArgs.push_back("-E");
5141 CmdArgs.push_back("-P");
5142 }
5143
5144 unsigned VolatileOptionID;
5145 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5146 getToolChain().getArch() == llvm::Triple::x86)
5147 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5148 else
5149 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5150
5151 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5152 VolatileOptionID = A->getOption().getID();
5153
5154 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5155 CmdArgs.push_back("-fms-volatile");
5156
5157 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5158 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5159 if (MostGeneralArg && BestCaseArg)
5160 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5161 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5162
5163 if (MostGeneralArg) {
5164 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5165 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5166 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5167
5168 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5169 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5170 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5171 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5172 << FirstConflict->getAsString(Args)
5173 << SecondConflict->getAsString(Args);
5174
5175 if (SingleArg)
5176 CmdArgs.push_back("-fms-memptr-rep=single");
5177 else if (MultipleArg)
5178 CmdArgs.push_back("-fms-memptr-rep=multiple");
5179 else
5180 CmdArgs.push_back("-fms-memptr-rep=virtual");
5181 }
5182
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005183 // Parse the default calling convention options.
5184 if (Arg *CCArg =
5185 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005186 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5187 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005188 unsigned DCCOptId = CCArg->getOption().getID();
5189 const char *DCCFlag = nullptr;
5190 bool ArchSupported = true;
5191 llvm::Triple::ArchType Arch = getToolChain().getArch();
5192 switch (DCCOptId) {
5193 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005194 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005195 break;
5196 case options::OPT__SLASH_Gr:
5197 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005198 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005199 break;
5200 case options::OPT__SLASH_Gz:
5201 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005202 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005203 break;
5204 case options::OPT__SLASH_Gv:
5205 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005206 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005207 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005208 case options::OPT__SLASH_Gregcall:
5209 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5210 DCCFlag = "-fdefault-calling-conv=regcall";
5211 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005212 }
5213
5214 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5215 if (ArchSupported && DCCFlag)
5216 CmdArgs.push_back(DCCFlag);
5217 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005218
5219 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5220 A->render(Args, CmdArgs);
5221
5222 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5223 CmdArgs.push_back("-fdiagnostics-format");
5224 if (Args.hasArg(options::OPT__SLASH_fallback))
5225 CmdArgs.push_back("msvc-fallback");
5226 else
5227 CmdArgs.push_back("msvc");
5228 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005229
5230 if (Args.hasArg(options::OPT__SLASH_Guard) &&
5231 Args.getLastArgValue(options::OPT__SLASH_Guard).equals_lower("cf"))
5232 CmdArgs.push_back("-cfguard");
David L. Jonesf561aba2017-03-08 01:02:16 +00005233}
5234
5235visualstudio::Compiler *Clang::getCLFallback() const {
5236 if (!CLFallback)
5237 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5238 return CLFallback.get();
5239}
5240
5241
5242const char *Clang::getBaseInputName(const ArgList &Args,
5243 const InputInfo &Input) {
5244 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5245}
5246
5247const char *Clang::getBaseInputStem(const ArgList &Args,
5248 const InputInfoList &Inputs) {
5249 const char *Str = getBaseInputName(Args, Inputs[0]);
5250
5251 if (const char *End = strrchr(Str, '.'))
5252 return Args.MakeArgString(std::string(Str, End));
5253
5254 return Str;
5255}
5256
5257const char *Clang::getDependencyFileName(const ArgList &Args,
5258 const InputInfoList &Inputs) {
5259 // FIXME: Think about this more.
5260 std::string Res;
5261
5262 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5263 std::string Str(OutputOpt->getValue());
5264 Res = Str.substr(0, Str.rfind('.'));
5265 } else {
5266 Res = getBaseInputStem(Args, Inputs);
5267 }
5268 return Args.MakeArgString(Res + ".d");
5269}
5270
5271// Begin ClangAs
5272
5273void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5274 ArgStringList &CmdArgs) const {
5275 StringRef CPUName;
5276 StringRef ABIName;
5277 const llvm::Triple &Triple = getToolChain().getTriple();
5278 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5279
5280 CmdArgs.push_back("-target-abi");
5281 CmdArgs.push_back(ABIName.data());
5282}
5283
5284void ClangAs::AddX86TargetArgs(const ArgList &Args,
5285 ArgStringList &CmdArgs) const {
5286 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5287 StringRef Value = A->getValue();
5288 if (Value == "intel" || Value == "att") {
5289 CmdArgs.push_back("-mllvm");
5290 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5291 } else {
5292 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5293 << A->getOption().getName() << Value;
5294 }
5295 }
5296}
5297
5298void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5299 const InputInfo &Output, const InputInfoList &Inputs,
5300 const ArgList &Args,
5301 const char *LinkingOutput) const {
5302 ArgStringList CmdArgs;
5303
5304 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5305 const InputInfo &Input = Inputs[0];
5306
5307 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5308 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005309 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005310
5311 // Don't warn about "clang -w -c foo.s"
5312 Args.ClaimAllArgs(options::OPT_w);
5313 // and "clang -emit-llvm -c foo.s"
5314 Args.ClaimAllArgs(options::OPT_emit_llvm);
5315
5316 claimNoWarnArgs(Args);
5317
5318 // Invoke ourselves in -cc1as mode.
5319 //
5320 // FIXME: Implement custom jobs for internal actions.
5321 CmdArgs.push_back("-cc1as");
5322
5323 // Add the "effective" target triple.
5324 CmdArgs.push_back("-triple");
5325 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5326
5327 // Set the output mode, we currently only expect to be used as a real
5328 // assembler.
5329 CmdArgs.push_back("-filetype");
5330 CmdArgs.push_back("obj");
5331
5332 // Set the main file name, so that debug info works even with
5333 // -save-temps or preprocessed assembly.
5334 CmdArgs.push_back("-main-file-name");
5335 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5336
5337 // Add the target cpu
5338 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5339 if (!CPU.empty()) {
5340 CmdArgs.push_back("-target-cpu");
5341 CmdArgs.push_back(Args.MakeArgString(CPU));
5342 }
5343
5344 // Add the target features
5345 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5346
5347 // Ignore explicit -force_cpusubtype_ALL option.
5348 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5349
5350 // Pass along any -I options so we get proper .include search paths.
5351 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5352
5353 // Determine the original source input.
5354 const Action *SourceAction = &JA;
5355 while (SourceAction->getKind() != Action::InputClass) {
5356 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5357 SourceAction = SourceAction->getInputs()[0];
5358 }
5359
5360 // Forward -g and handle debug info related flags, assuming we are dealing
5361 // with an actual assembly file.
5362 bool WantDebug = false;
5363 unsigned DwarfVersion = 0;
5364 Args.ClaimAllArgs(options::OPT_g_Group);
5365 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5366 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5367 !A->getOption().matches(options::OPT_ggdb0);
5368 if (WantDebug)
5369 DwarfVersion = DwarfVersionNum(A->getSpelling());
5370 }
5371 if (DwarfVersion == 0)
5372 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5373
5374 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5375
5376 if (SourceAction->getType() == types::TY_Asm ||
5377 SourceAction->getType() == types::TY_PP_Asm) {
5378 // You might think that it would be ok to set DebugInfoKind outside of
5379 // the guard for source type, however there is a test which asserts
5380 // that some assembler invocation receives no -debug-info-kind,
5381 // and it's not clear whether that test is just overly restrictive.
5382 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5383 : codegenoptions::NoDebugInfo);
5384 // Add the -fdebug-compilation-dir flag if needed.
5385 addDebugCompDirArg(Args, CmdArgs);
5386
5387 // Set the AT_producer to the clang version when using the integrated
5388 // assembler on assembly source files.
5389 CmdArgs.push_back("-dwarf-debug-producer");
5390 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5391
5392 // And pass along -I options
5393 Args.AddAllArgs(CmdArgs, options::OPT_I);
5394 }
5395 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5396 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005397 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5398
David L. Jonesf561aba2017-03-08 01:02:16 +00005399
5400 // Handle -fPIC et al -- the relocation-model affects the assembler
5401 // for some targets.
5402 llvm::Reloc::Model RelocationModel;
5403 unsigned PICLevel;
5404 bool IsPIE;
5405 std::tie(RelocationModel, PICLevel, IsPIE) =
5406 ParsePICArgs(getToolChain(), Args);
5407
5408 const char *RMName = RelocationModelName(RelocationModel);
5409 if (RMName) {
5410 CmdArgs.push_back("-mrelocation-model");
5411 CmdArgs.push_back(RMName);
5412 }
5413
5414 // Optionally embed the -cc1as level arguments into the debug info, for build
5415 // analysis.
5416 if (getToolChain().UseDwarfDebugFlags()) {
5417 ArgStringList OriginalArgs;
5418 for (const auto &Arg : Args)
5419 Arg->render(Args, OriginalArgs);
5420
5421 SmallString<256> Flags;
5422 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5423 Flags += Exec;
5424 for (const char *OriginalArg : OriginalArgs) {
5425 SmallString<128> EscapedArg;
5426 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5427 Flags += " ";
5428 Flags += EscapedArg;
5429 }
5430 CmdArgs.push_back("-dwarf-debug-flags");
5431 CmdArgs.push_back(Args.MakeArgString(Flags));
5432 }
5433
5434 // FIXME: Add -static support, once we have it.
5435
5436 // Add target specific flags.
5437 switch (getToolChain().getArch()) {
5438 default:
5439 break;
5440
5441 case llvm::Triple::mips:
5442 case llvm::Triple::mipsel:
5443 case llvm::Triple::mips64:
5444 case llvm::Triple::mips64el:
5445 AddMIPSTargetArgs(Args, CmdArgs);
5446 break;
5447
5448 case llvm::Triple::x86:
5449 case llvm::Triple::x86_64:
5450 AddX86TargetArgs(Args, CmdArgs);
5451 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005452
5453 case llvm::Triple::arm:
5454 case llvm::Triple::armeb:
5455 case llvm::Triple::thumb:
5456 case llvm::Triple::thumbeb:
5457 // This isn't in AddARMTargetArgs because we want to do this for assembly
5458 // only, not C/C++.
5459 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5460 options::OPT_mno_default_build_attributes, true)) {
5461 CmdArgs.push_back("-mllvm");
5462 CmdArgs.push_back("-arm-add-build-attributes");
5463 }
5464 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005465 }
5466
5467 // Consume all the warning flags. Usually this would be handled more
5468 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5469 // doesn't handle that so rather than warning about unused flags that are
5470 // actually used, we'll lie by omission instead.
5471 // FIXME: Stop lying and consume only the appropriate driver flags
5472 Args.ClaimAllArgs(options::OPT_W_Group);
5473
5474 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5475 getToolChain().getDriver());
5476
5477 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5478
5479 assert(Output.isFilename() && "Unexpected lipo output.");
5480 CmdArgs.push_back("-o");
5481 CmdArgs.push_back(Output.getFilename());
5482
Peter Collingbourne91d02842018-05-22 18:52:37 +00005483 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5484 getToolChain().getTriple().isOSLinux()) {
5485 CmdArgs.push_back("-split-dwarf-file");
5486 CmdArgs.push_back(SplitDebugName(Args, Input));
5487 }
5488
David L. Jonesf561aba2017-03-08 01:02:16 +00005489 assert(Input.isFilename() && "Invalid input.");
5490 CmdArgs.push_back(Input.getFilename());
5491
5492 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5493 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005494}
5495
5496// Begin OffloadBundler
5497
5498void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5499 const InputInfo &Output,
5500 const InputInfoList &Inputs,
5501 const llvm::opt::ArgList &TCArgs,
5502 const char *LinkingOutput) const {
5503 // The version with only one output is expected to refer to a bundling job.
5504 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5505
5506 // The bundling command looks like this:
5507 // clang-offload-bundler -type=bc
5508 // -targets=host-triple,openmp-triple1,openmp-triple2
5509 // -outputs=input_file
5510 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5511
5512 ArgStringList CmdArgs;
5513
5514 // Get the type.
5515 CmdArgs.push_back(TCArgs.MakeArgString(
5516 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5517
5518 assert(JA.getInputs().size() == Inputs.size() &&
5519 "Not have inputs for all dependence actions??");
5520
5521 // Get the targets.
5522 SmallString<128> Triples;
5523 Triples += "-targets=";
5524 for (unsigned I = 0; I < Inputs.size(); ++I) {
5525 if (I)
5526 Triples += ',';
5527
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005528 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005529 Action::OffloadKind CurKind = Action::OFK_Host;
5530 const ToolChain *CurTC = &getToolChain();
5531 const Action *CurDep = JA.getInputs()[I];
5532
5533 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005534 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005535 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005536 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005537 CurKind = A->getOffloadingDeviceKind();
5538 CurTC = TC;
5539 });
5540 }
5541 Triples += Action::GetOffloadKindName(CurKind);
5542 Triples += '-';
5543 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005544 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5545 Triples += '-';
5546 Triples += CurDep->getOffloadingArch();
5547 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005548 }
5549 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5550
5551 // Get bundled file command.
5552 CmdArgs.push_back(
5553 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5554
5555 // Get unbundled files command.
5556 SmallString<128> UB;
5557 UB += "-inputs=";
5558 for (unsigned I = 0; I < Inputs.size(); ++I) {
5559 if (I)
5560 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005561
5562 // Find ToolChain for this input.
5563 const ToolChain *CurTC = &getToolChain();
5564 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5565 CurTC = nullptr;
5566 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5567 assert(CurTC == nullptr && "Expected one dependence!");
5568 CurTC = TC;
5569 });
5570 }
5571 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005572 }
5573 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5574
5575 // All the inputs are encoded as commands.
5576 C.addCommand(llvm::make_unique<Command>(
5577 JA, *this,
5578 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5579 CmdArgs, None));
5580}
5581
5582void OffloadBundler::ConstructJobMultipleOutputs(
5583 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5584 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5585 const char *LinkingOutput) const {
5586 // The version with multiple outputs is expected to refer to a unbundling job.
5587 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5588
5589 // The unbundling command looks like this:
5590 // clang-offload-bundler -type=bc
5591 // -targets=host-triple,openmp-triple1,openmp-triple2
5592 // -inputs=input_file
5593 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5594 // -unbundle
5595
5596 ArgStringList CmdArgs;
5597
5598 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5599 InputInfo Input = Inputs.front();
5600
5601 // Get the type.
5602 CmdArgs.push_back(TCArgs.MakeArgString(
5603 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5604
5605 // Get the targets.
5606 SmallString<128> Triples;
5607 Triples += "-targets=";
5608 auto DepInfo = UA.getDependentActionsInfo();
5609 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5610 if (I)
5611 Triples += ',';
5612
5613 auto &Dep = DepInfo[I];
5614 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5615 Triples += '-';
5616 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005617 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5618 !Dep.DependentBoundArch.empty()) {
5619 Triples += '-';
5620 Triples += Dep.DependentBoundArch;
5621 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005622 }
5623
5624 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5625
5626 // Get bundled file command.
5627 CmdArgs.push_back(
5628 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5629
5630 // Get unbundled files command.
5631 SmallString<128> UB;
5632 UB += "-outputs=";
5633 for (unsigned I = 0; I < Outputs.size(); ++I) {
5634 if (I)
5635 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005636 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005637 }
5638 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5639 CmdArgs.push_back("-unbundle");
5640
5641 // All the inputs are encoded as commands.
5642 C.addCommand(llvm::make_unique<Command>(
5643 JA, *this,
5644 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5645 CmdArgs, None));
5646}